qunit-2.4.0.js 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049
  1. /*!
  2. * QUnit 2.4.0
  3. * https://qunitjs.com/
  4. *
  5. * Copyright jQuery Foundation and other contributors
  6. * Released under the MIT license
  7. * https://jquery.org/license
  8. *
  9. * Date: 2017-07-08T15:20Z
  10. */
  11. (function (global$1) {
  12. 'use strict';
  13. global$1 = global$1 && 'default' in global$1 ? global$1['default'] : global$1;
  14. var window = global$1.window;
  15. var self$1 = global$1.self;
  16. var console = global$1.console;
  17. var setTimeout = global$1.setTimeout;
  18. var clearTimeout = global$1.clearTimeout;
  19. var document = window && window.document;
  20. var navigator = window && window.navigator;
  21. var localSessionStorage = function () {
  22. var x = "qunit-test-string";
  23. try {
  24. global$1.sessionStorage.setItem(x, x);
  25. global$1.sessionStorage.removeItem(x);
  26. return global$1.sessionStorage;
  27. } catch (e) {
  28. return undefined;
  29. }
  30. }();
  31. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  32. return typeof obj;
  33. } : function (obj) {
  34. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  35. };
  36. var classCallCheck = function (instance, Constructor) {
  37. if (!(instance instanceof Constructor)) {
  38. throw new TypeError("Cannot call a class as a function");
  39. }
  40. };
  41. var createClass = function () {
  42. function defineProperties(target, props) {
  43. for (var i = 0; i < props.length; i++) {
  44. var descriptor = props[i];
  45. descriptor.enumerable = descriptor.enumerable || false;
  46. descriptor.configurable = true;
  47. if ("value" in descriptor) descriptor.writable = true;
  48. Object.defineProperty(target, descriptor.key, descriptor);
  49. }
  50. }
  51. return function (Constructor, protoProps, staticProps) {
  52. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  53. if (staticProps) defineProperties(Constructor, staticProps);
  54. return Constructor;
  55. };
  56. }();
  57. var toConsumableArray = function (arr) {
  58. if (Array.isArray(arr)) {
  59. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  60. return arr2;
  61. } else {
  62. return Array.from(arr);
  63. }
  64. };
  65. var toString = Object.prototype.toString;
  66. var hasOwn = Object.prototype.hasOwnProperty;
  67. var now = Date.now || function () {
  68. return new Date().getTime();
  69. };
  70. var defined = {
  71. document: window && window.document !== undefined,
  72. setTimeout: setTimeout !== undefined
  73. };
  74. // Returns a new Array with the elements that are in a but not in b
  75. function diff(a, b) {
  76. var i,
  77. j,
  78. result = a.slice();
  79. for (i = 0; i < result.length; i++) {
  80. for (j = 0; j < b.length; j++) {
  81. if (result[i] === b[j]) {
  82. result.splice(i, 1);
  83. i--;
  84. break;
  85. }
  86. }
  87. }
  88. return result;
  89. }
  90. /**
  91. * Determines whether an element exists in a given array or not.
  92. *
  93. * @method inArray
  94. * @param {Any} elem
  95. * @param {Array} array
  96. * @return {Boolean}
  97. */
  98. function inArray(elem, array) {
  99. return array.indexOf(elem) !== -1;
  100. }
  101. /**
  102. * Makes a clone of an object using only Array or Object as base,
  103. * and copies over the own enumerable properties.
  104. *
  105. * @param {Object} obj
  106. * @return {Object} New object with only the own properties (recursively).
  107. */
  108. function objectValues(obj) {
  109. var key,
  110. val,
  111. vals = is("array", obj) ? [] : {};
  112. for (key in obj) {
  113. if (hasOwn.call(obj, key)) {
  114. val = obj[key];
  115. vals[key] = val === Object(val) ? objectValues(val) : val;
  116. }
  117. }
  118. return vals;
  119. }
  120. function extend(a, b, undefOnly) {
  121. for (var prop in b) {
  122. if (hasOwn.call(b, prop)) {
  123. if (b[prop] === undefined) {
  124. delete a[prop];
  125. } else if (!(undefOnly && typeof a[prop] !== "undefined")) {
  126. a[prop] = b[prop];
  127. }
  128. }
  129. }
  130. return a;
  131. }
  132. function objectType(obj) {
  133. if (typeof obj === "undefined") {
  134. return "undefined";
  135. }
  136. // Consider: typeof null === object
  137. if (obj === null) {
  138. return "null";
  139. }
  140. var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
  141. type = match && match[1];
  142. switch (type) {
  143. case "Number":
  144. if (isNaN(obj)) {
  145. return "nan";
  146. }
  147. return "number";
  148. case "String":
  149. case "Boolean":
  150. case "Array":
  151. case "Set":
  152. case "Map":
  153. case "Date":
  154. case "RegExp":
  155. case "Function":
  156. case "Symbol":
  157. return type.toLowerCase();
  158. default:
  159. return typeof obj === "undefined" ? "undefined" : _typeof(obj);
  160. }
  161. }
  162. // Safe object type checking
  163. function is(type, obj) {
  164. return objectType(obj) === type;
  165. }
  166. // Based on Java's String.hashCode, a simple but not
  167. // rigorously collision resistant hashing function
  168. function generateHash(module, testName) {
  169. var str = module + "\x1C" + testName;
  170. var hash = 0;
  171. for (var i = 0; i < str.length; i++) {
  172. hash = (hash << 5) - hash + str.charCodeAt(i);
  173. hash |= 0;
  174. }
  175. // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
  176. // strictly necessary but increases user understanding that the id is a SHA-like hash
  177. var hex = (0x100000000 + hash).toString(16);
  178. if (hex.length < 8) {
  179. hex = "0000000" + hex;
  180. }
  181. return hex.slice(-8);
  182. }
  183. // Test for equality any JavaScript type.
  184. // Authors: Philippe Rathé <prathe@gmail.com>, David Chan <david@troi.org>
  185. var equiv = (function () {
  186. // Value pairs queued for comparison. Used for breadth-first processing order, recursion
  187. // detection and avoiding repeated comparison (see below for details).
  188. // Elements are { a: val, b: val }.
  189. var pairs = [];
  190. var getProto = Object.getPrototypeOf || function (obj) {
  191. return obj.__proto__;
  192. };
  193. function useStrictEquality(a, b) {
  194. // This only gets called if a and b are not strict equal, and is used to compare on
  195. // the primitive values inside object wrappers. For example:
  196. // `var i = 1;`
  197. // `var j = new Number(1);`
  198. // Neither a nor b can be null, as a !== b and they have the same type.
  199. if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") {
  200. a = a.valueOf();
  201. }
  202. if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") {
  203. b = b.valueOf();
  204. }
  205. return a === b;
  206. }
  207. function compareConstructors(a, b) {
  208. var protoA = getProto(a);
  209. var protoB = getProto(b);
  210. // Comparing constructors is more strict than using `instanceof`
  211. if (a.constructor === b.constructor) {
  212. return true;
  213. }
  214. // Ref #851
  215. // If the obj prototype descends from a null constructor, treat it
  216. // as a null prototype.
  217. if (protoA && protoA.constructor === null) {
  218. protoA = null;
  219. }
  220. if (protoB && protoB.constructor === null) {
  221. protoB = null;
  222. }
  223. // Allow objects with no prototype to be equivalent to
  224. // objects with Object as their constructor.
  225. if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) {
  226. return true;
  227. }
  228. return false;
  229. }
  230. function getRegExpFlags(regexp) {
  231. return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0];
  232. }
  233. function isContainer(val) {
  234. return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1;
  235. }
  236. function breadthFirstCompareChild(a, b) {
  237. // If a is a container not reference-equal to b, postpone the comparison to the
  238. // end of the pairs queue -- unless (a, b) has been seen before, in which case skip
  239. // over the pair.
  240. if (a === b) {
  241. return true;
  242. }
  243. if (!isContainer(a)) {
  244. return typeEquiv(a, b);
  245. }
  246. if (pairs.every(function (pair) {
  247. return pair.a !== a || pair.b !== b;
  248. })) {
  249. // Not yet started comparing this pair
  250. pairs.push({ a: a, b: b });
  251. }
  252. return true;
  253. }
  254. var callbacks = {
  255. "string": useStrictEquality,
  256. "boolean": useStrictEquality,
  257. "number": useStrictEquality,
  258. "null": useStrictEquality,
  259. "undefined": useStrictEquality,
  260. "symbol": useStrictEquality,
  261. "date": useStrictEquality,
  262. "nan": function nan() {
  263. return true;
  264. },
  265. "regexp": function regexp(a, b) {
  266. return a.source === b.source &&
  267. // Include flags in the comparison
  268. getRegExpFlags(a) === getRegExpFlags(b);
  269. },
  270. // abort (identical references / instance methods were skipped earlier)
  271. "function": function _function() {
  272. return false;
  273. },
  274. "array": function array(a, b) {
  275. var i, len;
  276. len = a.length;
  277. if (len !== b.length) {
  278. // Safe and faster
  279. return false;
  280. }
  281. for (i = 0; i < len; i++) {
  282. // Compare non-containers; queue non-reference-equal containers
  283. if (!breadthFirstCompareChild(a[i], b[i])) {
  284. return false;
  285. }
  286. }
  287. return true;
  288. },
  289. // Define sets a and b to be equivalent if for each element aVal in a, there
  290. // is some element bVal in b such that aVal and bVal are equivalent. Element
  291. // repetitions are not counted, so these are equivalent:
  292. // a = new Set( [ {}, [], [] ] );
  293. // b = new Set( [ {}, {}, [] ] );
  294. "set": function set$$1(a, b) {
  295. var innerEq,
  296. outerEq = true;
  297. if (a.size !== b.size) {
  298. // This optimization has certain quirks because of the lack of
  299. // repetition counting. For instance, adding the same
  300. // (reference-identical) element to two equivalent sets can
  301. // make them non-equivalent.
  302. return false;
  303. }
  304. a.forEach(function (aVal) {
  305. // Short-circuit if the result is already known. (Using for...of
  306. // with a break clause would be cleaner here, but it would cause
  307. // a syntax error on older Javascript implementations even if
  308. // Set is unused)
  309. if (!outerEq) {
  310. return;
  311. }
  312. innerEq = false;
  313. b.forEach(function (bVal) {
  314. var parentPairs;
  315. // Likewise, short-circuit if the result is already known
  316. if (innerEq) {
  317. return;
  318. }
  319. // Swap out the global pairs list, as the nested call to
  320. // innerEquiv will clobber its contents
  321. parentPairs = pairs;
  322. if (innerEquiv(bVal, aVal)) {
  323. innerEq = true;
  324. }
  325. // Replace the global pairs list
  326. pairs = parentPairs;
  327. });
  328. if (!innerEq) {
  329. outerEq = false;
  330. }
  331. });
  332. return outerEq;
  333. },
  334. // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal)
  335. // in a, there is some key-value pair (bKey, bVal) in b such that
  336. // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not
  337. // counted, so these are equivalent:
  338. // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] );
  339. // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] );
  340. "map": function map(a, b) {
  341. var innerEq,
  342. outerEq = true;
  343. if (a.size !== b.size) {
  344. // This optimization has certain quirks because of the lack of
  345. // repetition counting. For instance, adding the same
  346. // (reference-identical) key-value pair to two equivalent maps
  347. // can make them non-equivalent.
  348. return false;
  349. }
  350. a.forEach(function (aVal, aKey) {
  351. // Short-circuit if the result is already known. (Using for...of
  352. // with a break clause would be cleaner here, but it would cause
  353. // a syntax error on older Javascript implementations even if
  354. // Map is unused)
  355. if (!outerEq) {
  356. return;
  357. }
  358. innerEq = false;
  359. b.forEach(function (bVal, bKey) {
  360. var parentPairs;
  361. // Likewise, short-circuit if the result is already known
  362. if (innerEq) {
  363. return;
  364. }
  365. // Swap out the global pairs list, as the nested call to
  366. // innerEquiv will clobber its contents
  367. parentPairs = pairs;
  368. if (innerEquiv([bVal, bKey], [aVal, aKey])) {
  369. innerEq = true;
  370. }
  371. // Replace the global pairs list
  372. pairs = parentPairs;
  373. });
  374. if (!innerEq) {
  375. outerEq = false;
  376. }
  377. });
  378. return outerEq;
  379. },
  380. "object": function object(a, b) {
  381. var i,
  382. aProperties = [],
  383. bProperties = [];
  384. if (compareConstructors(a, b) === false) {
  385. return false;
  386. }
  387. // Be strict: don't ensure hasOwnProperty and go deep
  388. for (i in a) {
  389. // Collect a's properties
  390. aProperties.push(i);
  391. // Skip OOP methods that look the same
  392. if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) {
  393. continue;
  394. }
  395. // Compare non-containers; queue non-reference-equal containers
  396. if (!breadthFirstCompareChild(a[i], b[i])) {
  397. return false;
  398. }
  399. }
  400. for (i in b) {
  401. // Collect b's properties
  402. bProperties.push(i);
  403. }
  404. // Ensures identical properties name
  405. return typeEquiv(aProperties.sort(), bProperties.sort());
  406. }
  407. };
  408. function typeEquiv(a, b) {
  409. var type = objectType(a);
  410. // Callbacks for containers will append to the pairs queue to achieve breadth-first
  411. // search order. The pairs queue is also used to avoid reprocessing any pair of
  412. // containers that are reference-equal to a previously visited pair (a special case
  413. // this being recursion detection).
  414. //
  415. // Because of this approach, once typeEquiv returns a false value, it should not be
  416. // called again without clearing the pair queue else it may wrongly report a visited
  417. // pair as being equivalent.
  418. return objectType(b) === type && callbacks[type](a, b);
  419. }
  420. function innerEquiv(a, b) {
  421. var i, pair;
  422. // We're done when there's nothing more to compare
  423. if (arguments.length < 2) {
  424. return true;
  425. }
  426. // Clear the global pair queue and add the top-level values being compared
  427. pairs = [{ a: a, b: b }];
  428. for (i = 0; i < pairs.length; i++) {
  429. pair = pairs[i];
  430. // Perform type-specific comparison on any pairs that are not strictly
  431. // equal. For container types, that comparison will postpone comparison
  432. // of any sub-container pair to the end of the pair queue. This gives
  433. // breadth-first search order. It also avoids the reprocessing of
  434. // reference-equal siblings, cousins etc, which can have a significant speed
  435. // impact when comparing a container of small objects each of which has a
  436. // reference to the same (singleton) large object.
  437. if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) {
  438. return false;
  439. }
  440. }
  441. // ...across all consecutive argument pairs
  442. return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1));
  443. }
  444. return function () {
  445. var result = innerEquiv.apply(undefined, arguments);
  446. // Release any retained objects
  447. pairs.length = 0;
  448. return result;
  449. };
  450. })();
  451. /**
  452. * Config object: Maintain internal state
  453. * Later exposed as QUnit.config
  454. * `config` initialized at top of scope
  455. */
  456. var config = {
  457. // The queue of tests to run
  458. queue: [],
  459. // Block until document ready
  460. blocking: true,
  461. // By default, run previously failed tests first
  462. // very useful in combination with "Hide passed tests" checked
  463. reorder: true,
  464. // By default, modify document.title when suite is done
  465. altertitle: true,
  466. // HTML Reporter: collapse every test except the first failing test
  467. // If false, all failing tests will be expanded
  468. collapse: true,
  469. // By default, scroll to top of the page when suite is done
  470. scrolltop: true,
  471. // Depth up-to which object will be dumped
  472. maxDepth: 5,
  473. // When enabled, all tests must call expect()
  474. requireExpects: false,
  475. // Placeholder for user-configurable form-exposed URL parameters
  476. urlConfig: [],
  477. // Set of all modules.
  478. modules: [],
  479. // The first unnamed module
  480. currentModule: {
  481. name: "",
  482. tests: [],
  483. childModules: [],
  484. testsRun: 0,
  485. unskippedTestsRun: 0,
  486. hooks: {
  487. before: [],
  488. beforeEach: [],
  489. afterEach: [],
  490. after: []
  491. }
  492. },
  493. callbacks: {},
  494. // The storage module to use for reordering tests
  495. storage: localSessionStorage
  496. };
  497. // take a predefined QUnit.config and extend the defaults
  498. var globalConfig = window && window.QUnit && window.QUnit.config;
  499. // only extend the global config if there is no QUnit overload
  500. if (window && window.QUnit && !window.QUnit.version) {
  501. extend(config, globalConfig);
  502. }
  503. // Push a loose unnamed module to the modules collection
  504. config.modules.push(config.currentModule);
  505. // Based on jsDump by Ariel Flesler
  506. // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
  507. var dump = (function () {
  508. function quote(str) {
  509. return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
  510. }
  511. function literal(o) {
  512. return o + "";
  513. }
  514. function join(pre, arr, post) {
  515. var s = dump.separator(),
  516. base = dump.indent(),
  517. inner = dump.indent(1);
  518. if (arr.join) {
  519. arr = arr.join("," + s + inner);
  520. }
  521. if (!arr) {
  522. return pre + post;
  523. }
  524. return [pre, inner + arr, base + post].join(s);
  525. }
  526. function array(arr, stack) {
  527. var i = arr.length,
  528. ret = new Array(i);
  529. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  530. return "[object Array]";
  531. }
  532. this.up();
  533. while (i--) {
  534. ret[i] = this.parse(arr[i], undefined, stack);
  535. }
  536. this.down();
  537. return join("[", ret, "]");
  538. }
  539. function isArray(obj) {
  540. return (
  541. //Native Arrays
  542. toString.call(obj) === "[object Array]" ||
  543. // NodeList objects
  544. typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined)
  545. );
  546. }
  547. var reName = /^function (\w+)/,
  548. dump = {
  549. // The objType is used mostly internally, you can fix a (custom) type in advance
  550. parse: function parse(obj, objType, stack) {
  551. stack = stack || [];
  552. var res,
  553. parser,
  554. parserType,
  555. objIndex = stack.indexOf(obj);
  556. if (objIndex !== -1) {
  557. return "recursion(" + (objIndex - stack.length) + ")";
  558. }
  559. objType = objType || this.typeOf(obj);
  560. parser = this.parsers[objType];
  561. parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);
  562. if (parserType === "function") {
  563. stack.push(obj);
  564. res = parser.call(this, obj, stack);
  565. stack.pop();
  566. return res;
  567. }
  568. return parserType === "string" ? parser : this.parsers.error;
  569. },
  570. typeOf: function typeOf(obj) {
  571. var type;
  572. if (obj === null) {
  573. type = "null";
  574. } else if (typeof obj === "undefined") {
  575. type = "undefined";
  576. } else if (is("regexp", obj)) {
  577. type = "regexp";
  578. } else if (is("date", obj)) {
  579. type = "date";
  580. } else if (is("function", obj)) {
  581. type = "function";
  582. } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) {
  583. type = "window";
  584. } else if (obj.nodeType === 9) {
  585. type = "document";
  586. } else if (obj.nodeType) {
  587. type = "node";
  588. } else if (isArray(obj)) {
  589. type = "array";
  590. } else if (obj.constructor === Error.prototype.constructor) {
  591. type = "error";
  592. } else {
  593. type = typeof obj === "undefined" ? "undefined" : _typeof(obj);
  594. }
  595. return type;
  596. },
  597. separator: function separator() {
  598. if (this.multiline) {
  599. return this.HTML ? "<br />" : "\n";
  600. } else {
  601. return this.HTML ? "&#160;" : " ";
  602. }
  603. },
  604. // Extra can be a number, shortcut for increasing-calling-decreasing
  605. indent: function indent(extra) {
  606. if (!this.multiline) {
  607. return "";
  608. }
  609. var chr = this.indentChar;
  610. if (this.HTML) {
  611. chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;");
  612. }
  613. return new Array(this.depth + (extra || 0)).join(chr);
  614. },
  615. up: function up(a) {
  616. this.depth += a || 1;
  617. },
  618. down: function down(a) {
  619. this.depth -= a || 1;
  620. },
  621. setParser: function setParser(name, parser) {
  622. this.parsers[name] = parser;
  623. },
  624. // The next 3 are exposed so you can use them
  625. quote: quote,
  626. literal: literal,
  627. join: join,
  628. depth: 1,
  629. maxDepth: config.maxDepth,
  630. // This is the list of parsers, to modify them, use dump.setParser
  631. parsers: {
  632. window: "[Window]",
  633. document: "[Document]",
  634. error: function error(_error) {
  635. return "Error(\"" + _error.message + "\")";
  636. },
  637. unknown: "[Unknown]",
  638. "null": "null",
  639. "undefined": "undefined",
  640. "function": function _function(fn) {
  641. var ret = "function",
  642. // Functions never have name in IE
  643. name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
  644. if (name) {
  645. ret += " " + name;
  646. }
  647. ret += "(";
  648. ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
  649. return join(ret, dump.parse(fn, "functionCode"), "}");
  650. },
  651. array: array,
  652. nodelist: array,
  653. "arguments": array,
  654. object: function object(map, stack) {
  655. var keys,
  656. key,
  657. val,
  658. i,
  659. nonEnumerableProperties,
  660. ret = [];
  661. if (dump.maxDepth && dump.depth > dump.maxDepth) {
  662. return "[object Object]";
  663. }
  664. dump.up();
  665. keys = [];
  666. for (key in map) {
  667. keys.push(key);
  668. }
  669. // Some properties are not always enumerable on Error objects.
  670. nonEnumerableProperties = ["message", "name"];
  671. for (i in nonEnumerableProperties) {
  672. key = nonEnumerableProperties[i];
  673. if (key in map && !inArray(key, keys)) {
  674. keys.push(key);
  675. }
  676. }
  677. keys.sort();
  678. for (i = 0; i < keys.length; i++) {
  679. key = keys[i];
  680. val = map[key];
  681. ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack));
  682. }
  683. dump.down();
  684. return join("{", ret, "}");
  685. },
  686. node: function node(_node) {
  687. var len,
  688. i,
  689. val,
  690. open = dump.HTML ? "&lt;" : "<",
  691. close = dump.HTML ? "&gt;" : ">",
  692. tag = _node.nodeName.toLowerCase(),
  693. ret = open + tag,
  694. attrs = _node.attributes;
  695. if (attrs) {
  696. for (i = 0, len = attrs.length; i < len; i++) {
  697. val = attrs[i].nodeValue;
  698. // IE6 includes all attributes in .attributes, even ones not explicitly
  699. // set. Those have values like undefined, null, 0, false, "" or
  700. // "inherit".
  701. if (val && val !== "inherit") {
  702. ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute");
  703. }
  704. }
  705. }
  706. ret += close;
  707. // Show content of TextNode or CDATASection
  708. if (_node.nodeType === 3 || _node.nodeType === 4) {
  709. ret += _node.nodeValue;
  710. }
  711. return ret + open + "/" + tag + close;
  712. },
  713. // Function calls it internally, it's the arguments part of the function
  714. functionArgs: function functionArgs(fn) {
  715. var args,
  716. l = fn.length;
  717. if (!l) {
  718. return "";
  719. }
  720. args = new Array(l);
  721. while (l--) {
  722. // 97 is 'a'
  723. args[l] = String.fromCharCode(97 + l);
  724. }
  725. return " " + args.join(", ") + " ";
  726. },
  727. // Object calls it internally, the key part of an item in a map
  728. key: quote,
  729. // Function calls it internally, it's the content of the function
  730. functionCode: "[code]",
  731. // Node calls it internally, it's a html attribute value
  732. attribute: quote,
  733. string: quote,
  734. date: quote,
  735. regexp: literal,
  736. number: literal,
  737. "boolean": literal,
  738. symbol: function symbol(sym) {
  739. return sym.toString();
  740. }
  741. },
  742. // If true, entities are escaped ( <, >, \t, space and \n )
  743. HTML: false,
  744. // Indentation unit
  745. indentChar: " ",
  746. // If true, items in a collection, are separated by a \n, else just a space.
  747. multiline: true
  748. };
  749. return dump;
  750. })();
  751. var LISTENERS = Object.create(null);
  752. var SUPPORTED_EVENTS = ["runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"];
  753. /**
  754. * Emits an event with the specified data to all currently registered listeners.
  755. * Callbacks will fire in the order in which they are registered (FIFO). This
  756. * function is not exposed publicly; it is used by QUnit internals to emit
  757. * logging events.
  758. *
  759. * @private
  760. * @method emit
  761. * @param {String} eventName
  762. * @param {Object} data
  763. * @return {Void}
  764. */
  765. function emit(eventName, data) {
  766. if (objectType(eventName) !== "string") {
  767. throw new TypeError("eventName must be a string when emitting an event");
  768. }
  769. // Clone the callbacks in case one of them registers a new callback
  770. var originalCallbacks = LISTENERS[eventName];
  771. var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : [];
  772. for (var i = 0; i < callbacks.length; i++) {
  773. callbacks[i](data);
  774. }
  775. }
  776. /**
  777. * Registers a callback as a listener to the specified event.
  778. *
  779. * @public
  780. * @method on
  781. * @param {String} eventName
  782. * @param {Function} callback
  783. * @return {Void}
  784. */
  785. function on(eventName, callback) {
  786. if (objectType(eventName) !== "string") {
  787. throw new TypeError("eventName must be a string when registering a listener");
  788. } else if (!inArray(eventName, SUPPORTED_EVENTS)) {
  789. var events = SUPPORTED_EVENTS.join(", ");
  790. throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + ".");
  791. } else if (objectType(callback) !== "function") {
  792. throw new TypeError("callback must be a function when registering a listener");
  793. }
  794. if (!LISTENERS[eventName]) {
  795. LISTENERS[eventName] = [];
  796. }
  797. // Don't register the same callback more than once
  798. if (!inArray(callback, LISTENERS[eventName])) {
  799. LISTENERS[eventName].push(callback);
  800. }
  801. }
  802. // Register logging callbacks
  803. function registerLoggingCallbacks(obj) {
  804. var i,
  805. l,
  806. key,
  807. callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];
  808. function registerLoggingCallback(key) {
  809. var loggingCallback = function loggingCallback(callback) {
  810. if (objectType(callback) !== "function") {
  811. throw new Error("QUnit logging methods require a callback function as their first parameters.");
  812. }
  813. config.callbacks[key].push(callback);
  814. };
  815. return loggingCallback;
  816. }
  817. for (i = 0, l = callbackNames.length; i < l; i++) {
  818. key = callbackNames[i];
  819. // Initialize key collection of logging callback
  820. if (objectType(config.callbacks[key]) === "undefined") {
  821. config.callbacks[key] = [];
  822. }
  823. obj[key] = registerLoggingCallback(key);
  824. }
  825. }
  826. function runLoggingCallbacks(key, args) {
  827. var i, l, callbacks;
  828. callbacks = config.callbacks[key];
  829. for (i = 0, l = callbacks.length; i < l; i++) {
  830. callbacks[i](args);
  831. }
  832. }
  833. // Doesn't support IE9, it will return undefined on these browsers
  834. // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
  835. var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
  836. function extractStacktrace(e, offset) {
  837. offset = offset === undefined ? 4 : offset;
  838. var stack, include, i;
  839. if (e && e.stack) {
  840. stack = e.stack.split("\n");
  841. if (/^error$/i.test(stack[0])) {
  842. stack.shift();
  843. }
  844. if (fileName) {
  845. include = [];
  846. for (i = offset; i < stack.length; i++) {
  847. if (stack[i].indexOf(fileName) !== -1) {
  848. break;
  849. }
  850. include.push(stack[i]);
  851. }
  852. if (include.length) {
  853. return include.join("\n");
  854. }
  855. }
  856. return stack[offset];
  857. }
  858. }
  859. function sourceFromStacktrace(offset) {
  860. var error = new Error();
  861. // Support: Safari <=7 only, IE <=10 - 11 only
  862. // Not all browsers generate the `stack` property for `new Error()`, see also #636
  863. if (!error.stack) {
  864. try {
  865. throw error;
  866. } catch (err) {
  867. error = err;
  868. }
  869. }
  870. return extractStacktrace(error, offset);
  871. }
  872. var priorityCount = 0;
  873. var unitSampler = void 0;
  874. /**
  875. * Advances the ProcessingQueue to the next item if it is ready.
  876. * @param {Boolean} last
  877. */
  878. function advance() {
  879. var start = now();
  880. config.depth = (config.depth || 0) + 1;
  881. while (config.queue.length && !config.blocking) {
  882. var elapsedTime = now() - start;
  883. if (!defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate) {
  884. if (priorityCount > 0) {
  885. priorityCount--;
  886. }
  887. config.queue.shift()();
  888. } else {
  889. setTimeout(advance, 13);
  890. break;
  891. }
  892. }
  893. config.depth--;
  894. if (!config.blocking && !config.queue.length && config.depth === 0) {
  895. done();
  896. }
  897. }
  898. function addToQueueImmediate(callback) {
  899. if (objectType(callback) === "array") {
  900. while (callback.length) {
  901. addToQueueImmediate(callback.pop());
  902. }
  903. return;
  904. }
  905. config.queue.unshift(callback);
  906. priorityCount++;
  907. }
  908. /**
  909. * Adds a function to the ProcessingQueue for execution.
  910. * @param {Function|Array} callback
  911. * @param {Boolean} priority
  912. * @param {String} seed
  913. */
  914. function addToQueue(callback, prioritize, seed) {
  915. if (prioritize) {
  916. config.queue.splice(priorityCount++, 0, callback);
  917. } else if (seed) {
  918. if (!unitSampler) {
  919. unitSampler = unitSamplerGenerator(seed);
  920. }
  921. // Insert into a random position after all prioritized items
  922. var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1));
  923. config.queue.splice(priorityCount + index, 0, callback);
  924. } else {
  925. config.queue.push(callback);
  926. }
  927. }
  928. /**
  929. * Creates a seeded "sample" generator which is used for randomizing tests.
  930. */
  931. function unitSamplerGenerator(seed) {
  932. // 32-bit xorshift, requires only a nonzero seed
  933. // http://excamera.com/sphinx/article-xorshift.html
  934. var sample = parseInt(generateHash(seed), 16) || -1;
  935. return function () {
  936. sample ^= sample << 13;
  937. sample ^= sample >>> 17;
  938. sample ^= sample << 5;
  939. // ECMAScript has no unsigned number type
  940. if (sample < 0) {
  941. sample += 0x100000000;
  942. }
  943. return sample / 0x100000000;
  944. };
  945. }
  946. /**
  947. * This function is called when the ProcessingQueue is done processing all
  948. * items. It handles emitting the final run events.
  949. */
  950. function done() {
  951. var storage = config.storage;
  952. ProcessingQueue.finished = true;
  953. var runtime = now() - config.started;
  954. var passed = config.stats.all - config.stats.bad;
  955. emit("runEnd", globalSuite.end(true));
  956. runLoggingCallbacks("done", {
  957. passed: passed,
  958. failed: config.stats.bad,
  959. total: config.stats.all,
  960. runtime: runtime
  961. });
  962. // Clear own storage items if all tests passed
  963. if (storage && config.stats.bad === 0) {
  964. for (var i = storage.length - 1; i >= 0; i--) {
  965. var key = storage.key(i);
  966. if (key.indexOf("qunit-test-") === 0) {
  967. storage.removeItem(key);
  968. }
  969. }
  970. }
  971. }
  972. var ProcessingQueue = {
  973. finished: false,
  974. add: addToQueue,
  975. addImmediate: addToQueueImmediate,
  976. advance: advance
  977. };
  978. var TestReport = function () {
  979. function TestReport(name, suite, options) {
  980. classCallCheck(this, TestReport);
  981. this.name = name;
  982. this.suiteName = suite.name;
  983. this.fullName = suite.fullName.concat(name);
  984. this.runtime = 0;
  985. this.assertions = [];
  986. this.skipped = !!options.skip;
  987. this.todo = !!options.todo;
  988. this.valid = options.valid;
  989. this._startTime = 0;
  990. this._endTime = 0;
  991. suite.pushTest(this);
  992. }
  993. createClass(TestReport, [{
  994. key: "start",
  995. value: function start(recordTime) {
  996. if (recordTime) {
  997. this._startTime = Date.now();
  998. }
  999. return {
  1000. name: this.name,
  1001. suiteName: this.suiteName,
  1002. fullName: this.fullName.slice()
  1003. };
  1004. }
  1005. }, {
  1006. key: "end",
  1007. value: function end(recordTime) {
  1008. if (recordTime) {
  1009. this._endTime = Date.now();
  1010. }
  1011. return extend(this.start(), {
  1012. runtime: this.getRuntime(),
  1013. status: this.getStatus(),
  1014. errors: this.getFailedAssertions(),
  1015. assertions: this.getAssertions()
  1016. });
  1017. }
  1018. }, {
  1019. key: "pushAssertion",
  1020. value: function pushAssertion(assertion) {
  1021. this.assertions.push(assertion);
  1022. }
  1023. }, {
  1024. key: "getRuntime",
  1025. value: function getRuntime() {
  1026. return this._endTime - this._startTime;
  1027. }
  1028. }, {
  1029. key: "getStatus",
  1030. value: function getStatus() {
  1031. if (this.skipped) {
  1032. return "skipped";
  1033. }
  1034. var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo;
  1035. if (!testPassed) {
  1036. return "failed";
  1037. } else if (this.todo) {
  1038. return "todo";
  1039. } else {
  1040. return "passed";
  1041. }
  1042. }
  1043. }, {
  1044. key: "getFailedAssertions",
  1045. value: function getFailedAssertions() {
  1046. return this.assertions.filter(function (assertion) {
  1047. return !assertion.passed;
  1048. });
  1049. }
  1050. }, {
  1051. key: "getAssertions",
  1052. value: function getAssertions() {
  1053. return this.assertions.slice();
  1054. }
  1055. // Remove actual and expected values from assertions. This is to prevent
  1056. // leaking memory throughout a test suite.
  1057. }, {
  1058. key: "slimAssertions",
  1059. value: function slimAssertions() {
  1060. this.assertions = this.assertions.map(function (assertion) {
  1061. delete assertion.actual;
  1062. delete assertion.expected;
  1063. return assertion;
  1064. });
  1065. }
  1066. }]);
  1067. return TestReport;
  1068. }();
  1069. var focused$1 = false;
  1070. function Test(settings) {
  1071. var i, l;
  1072. ++Test.count;
  1073. this.expected = null;
  1074. this.assertions = [];
  1075. this.semaphore = 0;
  1076. this.module = config.currentModule;
  1077. this.stack = sourceFromStacktrace(3);
  1078. this.steps = [];
  1079. this.timeout = undefined;
  1080. // If a module is skipped, all its tests and the tests of the child suites
  1081. // should be treated as skipped even if they are defined as `only` or `todo`.
  1082. // As for `todo` module, all its tests will be treated as `todo` except for
  1083. // tests defined as `skip` which will be left intact.
  1084. //
  1085. // So, if a test is defined as `todo` and is inside a skipped module, we should
  1086. // then treat that test as if was defined as `skip`.
  1087. if (this.module.skip) {
  1088. settings.skip = true;
  1089. settings.todo = false;
  1090. // Skipped tests should be left intact
  1091. } else if (this.module.todo && !settings.skip) {
  1092. settings.todo = true;
  1093. }
  1094. extend(this, settings);
  1095. this.testReport = new TestReport(settings.testName, this.module.suiteReport, {
  1096. todo: settings.todo,
  1097. skip: settings.skip,
  1098. valid: this.valid()
  1099. });
  1100. // Register unique strings
  1101. for (i = 0, l = this.module.tests; i < l.length; i++) {
  1102. if (this.module.tests[i].name === this.testName) {
  1103. this.testName += " ";
  1104. }
  1105. }
  1106. this.testId = generateHash(this.module.name, this.testName);
  1107. this.module.tests.push({
  1108. name: this.testName,
  1109. testId: this.testId,
  1110. skip: !!settings.skip
  1111. });
  1112. if (settings.skip) {
  1113. // Skipped tests will fully ignore any sent callback
  1114. this.callback = function () {};
  1115. this.async = false;
  1116. this.expected = 0;
  1117. } else {
  1118. this.assert = new Assert(this);
  1119. }
  1120. }
  1121. Test.count = 0;
  1122. function getNotStartedModules(startModule) {
  1123. var module = startModule,
  1124. modules = [];
  1125. while (module && module.testsRun === 0) {
  1126. modules.push(module);
  1127. module = module.parentModule;
  1128. }
  1129. return modules;
  1130. }
  1131. Test.prototype = {
  1132. before: function before() {
  1133. var i,
  1134. startModule,
  1135. module = this.module,
  1136. notStartedModules = getNotStartedModules(module);
  1137. for (i = notStartedModules.length - 1; i >= 0; i--) {
  1138. startModule = notStartedModules[i];
  1139. startModule.stats = { all: 0, bad: 0, started: now() };
  1140. emit("suiteStart", startModule.suiteReport.start(true));
  1141. runLoggingCallbacks("moduleStart", {
  1142. name: startModule.name,
  1143. tests: startModule.tests
  1144. });
  1145. }
  1146. config.current = this;
  1147. this.testEnvironment = extend({}, module.testEnvironment);
  1148. this.started = now();
  1149. emit("testStart", this.testReport.start(true));
  1150. runLoggingCallbacks("testStart", {
  1151. name: this.testName,
  1152. module: module.name,
  1153. testId: this.testId,
  1154. previousFailure: this.previousFailure
  1155. });
  1156. if (!config.pollution) {
  1157. saveGlobal();
  1158. }
  1159. },
  1160. run: function run() {
  1161. var promise;
  1162. config.current = this;
  1163. this.callbackStarted = now();
  1164. if (config.notrycatch) {
  1165. runTest(this);
  1166. return;
  1167. }
  1168. try {
  1169. runTest(this);
  1170. } catch (e) {
  1171. this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0));
  1172. // Else next test will carry the responsibility
  1173. saveGlobal();
  1174. // Restart the tests if they're blocking
  1175. if (config.blocking) {
  1176. internalRecover(this);
  1177. }
  1178. }
  1179. function runTest(test) {
  1180. promise = test.callback.call(test.testEnvironment, test.assert);
  1181. test.resolvePromise(promise);
  1182. // If the test has a "lock" on it, but the timeout is 0, then we push a
  1183. // failure as the test should be synchronous.
  1184. if (test.timeout === 0 && test.semaphore !== 0) {
  1185. pushFailure("Test did not finish synchronously even though assert.timeout( 0 ) was used.", sourceFromStacktrace(2));
  1186. }
  1187. }
  1188. },
  1189. after: function after() {
  1190. checkPollution();
  1191. },
  1192. queueHook: function queueHook(hook, hookName, hookOwner) {
  1193. var _this = this;
  1194. var callHook = function callHook() {
  1195. var promise = hook.call(_this.testEnvironment, _this.assert);
  1196. _this.resolvePromise(promise, hookName);
  1197. };
  1198. var runHook = function runHook() {
  1199. if (hookName === "before") {
  1200. if (hookOwner.unskippedTestsRun !== 0) {
  1201. return;
  1202. }
  1203. _this.preserveEnvironment = true;
  1204. }
  1205. if (hookName === "after" && hookOwner.unskippedTestsRun !== numberOfUnskippedTests(hookOwner) - 1 && config.queue.length > 2) {
  1206. return;
  1207. }
  1208. config.current = _this;
  1209. if (config.notrycatch) {
  1210. callHook();
  1211. return;
  1212. }
  1213. try {
  1214. callHook();
  1215. } catch (error) {
  1216. _this.pushFailure(hookName + " failed on " + _this.testName + ": " + (error.message || error), extractStacktrace(error, 0));
  1217. }
  1218. };
  1219. return runHook;
  1220. },
  1221. // Currently only used for module level hooks, can be used to add global level ones
  1222. hooks: function hooks(handler) {
  1223. var hooks = [];
  1224. function processHooks(test, module) {
  1225. if (module.parentModule) {
  1226. processHooks(test, module.parentModule);
  1227. }
  1228. if (module.hooks[handler].length) {
  1229. for (var i = 0; i < module.hooks[handler].length; i++) {
  1230. hooks.push(test.queueHook(module.hooks[handler][i], handler, module));
  1231. }
  1232. }
  1233. }
  1234. // Hooks are ignored on skipped tests
  1235. if (!this.skip) {
  1236. processHooks(this, this.module);
  1237. }
  1238. return hooks;
  1239. },
  1240. finish: function finish() {
  1241. config.current = this;
  1242. if (config.requireExpects && this.expected === null) {
  1243. this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack);
  1244. } else if (this.expected !== null && this.expected !== this.assertions.length) {
  1245. this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack);
  1246. } else if (this.expected === null && !this.assertions.length) {
  1247. this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack);
  1248. }
  1249. var i,
  1250. module = this.module,
  1251. moduleName = module.name,
  1252. testName = this.testName,
  1253. skipped = !!this.skip,
  1254. todo = !!this.todo,
  1255. bad = 0,
  1256. storage = config.storage;
  1257. this.runtime = now() - this.started;
  1258. config.stats.all += this.assertions.length;
  1259. module.stats.all += this.assertions.length;
  1260. for (i = 0; i < this.assertions.length; i++) {
  1261. if (!this.assertions[i].result) {
  1262. bad++;
  1263. config.stats.bad++;
  1264. module.stats.bad++;
  1265. }
  1266. }
  1267. notifyTestsRan(module, skipped);
  1268. // Store result when possible
  1269. if (storage) {
  1270. if (bad) {
  1271. storage.setItem("qunit-test-" + moduleName + "-" + testName, bad);
  1272. } else {
  1273. storage.removeItem("qunit-test-" + moduleName + "-" + testName);
  1274. }
  1275. }
  1276. // After emitting the js-reporters event we cleanup the assertion data to
  1277. // avoid leaking it. It is not used by the legacy testDone callbacks.
  1278. emit("testEnd", this.testReport.end(true));
  1279. this.testReport.slimAssertions();
  1280. runLoggingCallbacks("testDone", {
  1281. name: testName,
  1282. module: moduleName,
  1283. skipped: skipped,
  1284. todo: todo,
  1285. failed: bad,
  1286. passed: this.assertions.length - bad,
  1287. total: this.assertions.length,
  1288. runtime: skipped ? 0 : this.runtime,
  1289. // HTML Reporter use
  1290. assertions: this.assertions,
  1291. testId: this.testId,
  1292. // Source of Test
  1293. source: this.stack
  1294. });
  1295. if (module.testsRun === numberOfTests(module)) {
  1296. logSuiteEnd(module);
  1297. // Check if the parent modules, iteratively, are done. If that the case,
  1298. // we emit the `suiteEnd` event and trigger `moduleDone` callback.
  1299. var parent = module.parentModule;
  1300. while (parent && parent.testsRun === numberOfTests(parent)) {
  1301. logSuiteEnd(parent);
  1302. parent = parent.parentModule;
  1303. }
  1304. }
  1305. config.current = undefined;
  1306. function logSuiteEnd(module) {
  1307. emit("suiteEnd", module.suiteReport.end(true));
  1308. runLoggingCallbacks("moduleDone", {
  1309. name: module.name,
  1310. tests: module.tests,
  1311. failed: module.stats.bad,
  1312. passed: module.stats.all - module.stats.bad,
  1313. total: module.stats.all,
  1314. runtime: now() - module.stats.started
  1315. });
  1316. }
  1317. },
  1318. preserveTestEnvironment: function preserveTestEnvironment() {
  1319. if (this.preserveEnvironment) {
  1320. this.module.testEnvironment = this.testEnvironment;
  1321. this.testEnvironment = extend({}, this.module.testEnvironment);
  1322. }
  1323. },
  1324. queue: function queue() {
  1325. var test = this;
  1326. if (!this.valid()) {
  1327. return;
  1328. }
  1329. function runTest() {
  1330. // Each of these can by async
  1331. ProcessingQueue.addImmediate([function () {
  1332. test.before();
  1333. }, test.hooks("before"), function () {
  1334. test.preserveTestEnvironment();
  1335. }, test.hooks("beforeEach"), function () {
  1336. test.run();
  1337. }, test.hooks("afterEach").reverse(), test.hooks("after").reverse(), function () {
  1338. test.after();
  1339. }, function () {
  1340. test.finish();
  1341. }]);
  1342. }
  1343. var previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName);
  1344. // Prioritize previously failed tests, detected from storage
  1345. var prioritize = config.reorder && !!previousFailCount;
  1346. this.previousFailure = !!previousFailCount;
  1347. ProcessingQueue.add(runTest, prioritize, config.seed);
  1348. // If the queue has already finished, we manually process the new test
  1349. if (ProcessingQueue.finished) {
  1350. ProcessingQueue.advance();
  1351. }
  1352. },
  1353. pushResult: function pushResult(resultInfo) {
  1354. if (this !== config.current) {
  1355. throw new Error("Assertion occured after test had finished.");
  1356. }
  1357. // Destructure of resultInfo = { result, actual, expected, message, negative }
  1358. var source,
  1359. details = {
  1360. module: this.module.name,
  1361. name: this.testName,
  1362. result: resultInfo.result,
  1363. message: resultInfo.message,
  1364. actual: resultInfo.actual,
  1365. expected: resultInfo.expected,
  1366. testId: this.testId,
  1367. negative: resultInfo.negative || false,
  1368. runtime: now() - this.started,
  1369. todo: !!this.todo
  1370. };
  1371. if (!resultInfo.result) {
  1372. source = resultInfo.source || sourceFromStacktrace();
  1373. if (source) {
  1374. details.source = source;
  1375. }
  1376. }
  1377. this.logAssertion(details);
  1378. this.assertions.push({
  1379. result: !!resultInfo.result,
  1380. message: resultInfo.message
  1381. });
  1382. },
  1383. pushFailure: function pushFailure(message, source, actual) {
  1384. if (!(this instanceof Test)) {
  1385. throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2));
  1386. }
  1387. this.pushResult({
  1388. result: false,
  1389. message: message || "error",
  1390. actual: actual || null,
  1391. expected: null,
  1392. source: source
  1393. });
  1394. },
  1395. /**
  1396. * Log assertion details using both the old QUnit.log interface and
  1397. * QUnit.on( "assertion" ) interface.
  1398. *
  1399. * @private
  1400. */
  1401. logAssertion: function logAssertion(details) {
  1402. runLoggingCallbacks("log", details);
  1403. var assertion = {
  1404. passed: details.result,
  1405. actual: details.actual,
  1406. expected: details.expected,
  1407. message: details.message,
  1408. stack: details.source,
  1409. todo: details.todo
  1410. };
  1411. this.testReport.pushAssertion(assertion);
  1412. emit("assertion", assertion);
  1413. },
  1414. resolvePromise: function resolvePromise(promise, phase) {
  1415. var then,
  1416. resume,
  1417. message,
  1418. test = this;
  1419. if (promise != null) {
  1420. then = promise.then;
  1421. if (objectType(then) === "function") {
  1422. resume = internalStop(test);
  1423. then.call(promise, function () {
  1424. resume();
  1425. }, function (error) {
  1426. message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error);
  1427. test.pushFailure(message, extractStacktrace(error, 0));
  1428. // Else next test will carry the responsibility
  1429. saveGlobal();
  1430. // Unblock
  1431. resume();
  1432. });
  1433. }
  1434. }
  1435. },
  1436. valid: function valid() {
  1437. var filter = config.filter,
  1438. regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter),
  1439. module = config.module && config.module.toLowerCase(),
  1440. fullName = this.module.name + ": " + this.testName;
  1441. function moduleChainNameMatch(testModule) {
  1442. var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
  1443. if (testModuleName === module) {
  1444. return true;
  1445. } else if (testModule.parentModule) {
  1446. return moduleChainNameMatch(testModule.parentModule);
  1447. } else {
  1448. return false;
  1449. }
  1450. }
  1451. function moduleChainIdMatch(testModule) {
  1452. return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule);
  1453. }
  1454. // Internally-generated tests are always valid
  1455. if (this.callback && this.callback.validTest) {
  1456. return true;
  1457. }
  1458. if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) {
  1459. return false;
  1460. }
  1461. if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) {
  1462. return false;
  1463. }
  1464. if (module && !moduleChainNameMatch(this.module)) {
  1465. return false;
  1466. }
  1467. if (!filter) {
  1468. return true;
  1469. }
  1470. return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName);
  1471. },
  1472. regexFilter: function regexFilter(exclude, pattern, flags, fullName) {
  1473. var regex = new RegExp(pattern, flags);
  1474. var match = regex.test(fullName);
  1475. return match !== exclude;
  1476. },
  1477. stringFilter: function stringFilter(filter, fullName) {
  1478. filter = filter.toLowerCase();
  1479. fullName = fullName.toLowerCase();
  1480. var include = filter.charAt(0) !== "!";
  1481. if (!include) {
  1482. filter = filter.slice(1);
  1483. }
  1484. // If the filter matches, we need to honour include
  1485. if (fullName.indexOf(filter) !== -1) {
  1486. return include;
  1487. }
  1488. // Otherwise, do the opposite
  1489. return !include;
  1490. }
  1491. };
  1492. function pushFailure() {
  1493. if (!config.current) {
  1494. throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2));
  1495. }
  1496. // Gets current test obj
  1497. var currentTest = config.current;
  1498. return currentTest.pushFailure.apply(currentTest, arguments);
  1499. }
  1500. function saveGlobal() {
  1501. config.pollution = [];
  1502. if (config.noglobals) {
  1503. for (var key in global$1) {
  1504. if (hasOwn.call(global$1, key)) {
  1505. // In Opera sometimes DOM element ids show up here, ignore them
  1506. if (/^qunit-test-output/.test(key)) {
  1507. continue;
  1508. }
  1509. config.pollution.push(key);
  1510. }
  1511. }
  1512. }
  1513. }
  1514. function checkPollution() {
  1515. var newGlobals,
  1516. deletedGlobals,
  1517. old = config.pollution;
  1518. saveGlobal();
  1519. newGlobals = diff(config.pollution, old);
  1520. if (newGlobals.length > 0) {
  1521. pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
  1522. }
  1523. deletedGlobals = diff(old, config.pollution);
  1524. if (deletedGlobals.length > 0) {
  1525. pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
  1526. }
  1527. }
  1528. // Will be exposed as QUnit.test
  1529. function test(testName, callback) {
  1530. if (focused$1) {
  1531. return;
  1532. }
  1533. var newTest = new Test({
  1534. testName: testName,
  1535. callback: callback
  1536. });
  1537. newTest.queue();
  1538. }
  1539. function todo(testName, callback) {
  1540. if (focused$1) {
  1541. return;
  1542. }
  1543. var newTest = new Test({
  1544. testName: testName,
  1545. callback: callback,
  1546. todo: true
  1547. });
  1548. newTest.queue();
  1549. }
  1550. // Will be exposed as QUnit.skip
  1551. function skip(testName) {
  1552. if (focused$1) {
  1553. return;
  1554. }
  1555. var test = new Test({
  1556. testName: testName,
  1557. skip: true
  1558. });
  1559. test.queue();
  1560. }
  1561. // Will be exposed as QUnit.only
  1562. function only(testName, callback) {
  1563. if (focused$1) {
  1564. return;
  1565. }
  1566. config.queue.length = 0;
  1567. focused$1 = true;
  1568. var newTest = new Test({
  1569. testName: testName,
  1570. callback: callback
  1571. });
  1572. newTest.queue();
  1573. }
  1574. // Put a hold on processing and return a function that will release it.
  1575. function internalStop(test) {
  1576. test.semaphore += 1;
  1577. config.blocking = true;
  1578. // Set a recovery timeout, if so configured.
  1579. if (defined.setTimeout) {
  1580. var timeoutDuration = void 0;
  1581. if (typeof test.timeout === "number") {
  1582. timeoutDuration = test.timeout;
  1583. } else if (typeof config.testTimeout === "number") {
  1584. timeoutDuration = config.testTimeout;
  1585. }
  1586. if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  1587. clearTimeout(config.timeout);
  1588. config.timeout = setTimeout(function () {
  1589. pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
  1590. internalRecover(test);
  1591. }, timeoutDuration);
  1592. }
  1593. }
  1594. var released = false;
  1595. return function resume() {
  1596. if (released) {
  1597. return;
  1598. }
  1599. released = true;
  1600. test.semaphore -= 1;
  1601. internalStart(test);
  1602. };
  1603. }
  1604. // Forcefully release all processing holds.
  1605. function internalRecover(test) {
  1606. test.semaphore = 0;
  1607. internalStart(test);
  1608. }
  1609. // Release a processing hold, scheduling a resumption attempt if no holds remain.
  1610. function internalStart(test) {
  1611. // If semaphore is non-numeric, throw error
  1612. if (isNaN(test.semaphore)) {
  1613. test.semaphore = 0;
  1614. pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
  1615. return;
  1616. }
  1617. // Don't start until equal number of stop-calls
  1618. if (test.semaphore > 0) {
  1619. return;
  1620. }
  1621. // Throw an Error if start is called more often than stop
  1622. if (test.semaphore < 0) {
  1623. test.semaphore = 0;
  1624. pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
  1625. return;
  1626. }
  1627. // Add a slight delay to allow more assertions etc.
  1628. if (defined.setTimeout) {
  1629. if (config.timeout) {
  1630. clearTimeout(config.timeout);
  1631. }
  1632. config.timeout = setTimeout(function () {
  1633. if (test.semaphore > 0) {
  1634. return;
  1635. }
  1636. if (config.timeout) {
  1637. clearTimeout(config.timeout);
  1638. }
  1639. begin();
  1640. }, 13);
  1641. } else {
  1642. begin();
  1643. }
  1644. }
  1645. function collectTests(module) {
  1646. var tests = [].concat(module.tests);
  1647. var modules = [].concat(toConsumableArray(module.childModules));
  1648. // Do a breadth-first traversal of the child modules
  1649. while (modules.length) {
  1650. var nextModule = modules.shift();
  1651. tests.push.apply(tests, nextModule.tests);
  1652. modules.push.apply(modules, toConsumableArray(nextModule.childModules));
  1653. }
  1654. return tests;
  1655. }
  1656. function numberOfTests(module) {
  1657. return collectTests(module).length;
  1658. }
  1659. function numberOfUnskippedTests(module) {
  1660. return collectTests(module).filter(function (test) {
  1661. return !test.skip;
  1662. }).length;
  1663. }
  1664. function notifyTestsRan(module, skipped) {
  1665. module.testsRun++;
  1666. if (!skipped) {
  1667. module.unskippedTestsRun++;
  1668. }
  1669. while (module = module.parentModule) {
  1670. module.testsRun++;
  1671. if (!skipped) {
  1672. module.unskippedTestsRun++;
  1673. }
  1674. }
  1675. }
  1676. /**
  1677. * Returns a function that proxies to the given method name on the globals
  1678. * console object. The proxy will also detect if the console doesn't exist and
  1679. * will appropriately no-op. This allows support for IE9, which doesn't have a
  1680. * console if the developer tools are not open.
  1681. */
  1682. function consoleProxy(method) {
  1683. return function () {
  1684. if (console) {
  1685. console[method].apply(console, arguments);
  1686. }
  1687. };
  1688. }
  1689. var Logger = {
  1690. warn: consoleProxy("warn")
  1691. };
  1692. var Assert = function () {
  1693. function Assert(testContext) {
  1694. classCallCheck(this, Assert);
  1695. this.test = testContext;
  1696. }
  1697. // Assert helpers
  1698. createClass(Assert, [{
  1699. key: "timeout",
  1700. value: function timeout(duration) {
  1701. if (typeof duration !== "number") {
  1702. throw new Error("You must pass a number as the duration to assert.timeout");
  1703. }
  1704. this.test.timeout = duration;
  1705. }
  1706. // Documents a "step", which is a string value, in a test as a passing assertion
  1707. }, {
  1708. key: "step",
  1709. value: function step(message) {
  1710. var result = !!message;
  1711. this.test.steps.push(message);
  1712. return this.pushResult({
  1713. result: result,
  1714. message: message || "You must provide a message to assert.step"
  1715. });
  1716. }
  1717. // Verifies the steps in a test match a given array of string values
  1718. }, {
  1719. key: "verifySteps",
  1720. value: function verifySteps(steps, message) {
  1721. this.deepEqual(this.test.steps, steps, message);
  1722. }
  1723. // Specify the number of expected assertions to guarantee that failed test
  1724. // (no assertions are run at all) don't slip through.
  1725. }, {
  1726. key: "expect",
  1727. value: function expect(asserts) {
  1728. if (arguments.length === 1) {
  1729. this.test.expected = asserts;
  1730. } else {
  1731. return this.test.expected;
  1732. }
  1733. }
  1734. // Put a hold on processing and return a function that will release it a maximum of once.
  1735. }, {
  1736. key: "async",
  1737. value: function async(count) {
  1738. var test$$1 = this.test;
  1739. var popped = false,
  1740. acceptCallCount = count;
  1741. if (typeof acceptCallCount === "undefined") {
  1742. acceptCallCount = 1;
  1743. }
  1744. var resume = internalStop(test$$1);
  1745. return function done() {
  1746. if (config.current !== test$$1) {
  1747. throw Error("assert.async callback called after test finished.");
  1748. }
  1749. if (popped) {
  1750. test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2));
  1751. return;
  1752. }
  1753. acceptCallCount -= 1;
  1754. if (acceptCallCount > 0) {
  1755. return;
  1756. }
  1757. popped = true;
  1758. resume();
  1759. };
  1760. }
  1761. // Exports test.push() to the user API
  1762. // Alias of pushResult.
  1763. }, {
  1764. key: "push",
  1765. value: function push(result, actual, expected, message, negative) {
  1766. Logger.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult).");
  1767. var currentAssert = this instanceof Assert ? this : config.current.assert;
  1768. return currentAssert.pushResult({
  1769. result: result,
  1770. actual: actual,
  1771. expected: expected,
  1772. message: message,
  1773. negative: negative
  1774. });
  1775. }
  1776. }, {
  1777. key: "pushResult",
  1778. value: function pushResult(resultInfo) {
  1779. // Destructure of resultInfo = { result, actual, expected, message, negative }
  1780. var assert = this;
  1781. var currentTest = assert instanceof Assert && assert.test || config.current;
  1782. // Backwards compatibility fix.
  1783. // Allows the direct use of global exported assertions and QUnit.assert.*
  1784. // Although, it's use is not recommended as it can leak assertions
  1785. // to other tests from async tests, because we only get a reference to the current test,
  1786. // not exactly the test where assertion were intended to be called.
  1787. if (!currentTest) {
  1788. throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
  1789. }
  1790. if (!(assert instanceof Assert)) {
  1791. assert = currentTest.assert;
  1792. }
  1793. return assert.test.pushResult(resultInfo);
  1794. }
  1795. }, {
  1796. key: "ok",
  1797. value: function ok(result, message) {
  1798. if (!message) {
  1799. message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result);
  1800. }
  1801. this.pushResult({
  1802. result: !!result,
  1803. actual: result,
  1804. expected: true,
  1805. message: message
  1806. });
  1807. }
  1808. }, {
  1809. key: "notOk",
  1810. value: function notOk(result, message) {
  1811. if (!message) {
  1812. message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result);
  1813. }
  1814. this.pushResult({
  1815. result: !result,
  1816. actual: result,
  1817. expected: false,
  1818. message: message
  1819. });
  1820. }
  1821. }, {
  1822. key: "equal",
  1823. value: function equal(actual, expected, message) {
  1824. // eslint-disable-next-line eqeqeq
  1825. var result = expected == actual;
  1826. this.pushResult({
  1827. result: result,
  1828. actual: actual,
  1829. expected: expected,
  1830. message: message
  1831. });
  1832. }
  1833. }, {
  1834. key: "notEqual",
  1835. value: function notEqual(actual, expected, message) {
  1836. // eslint-disable-next-line eqeqeq
  1837. var result = expected != actual;
  1838. this.pushResult({
  1839. result: result,
  1840. actual: actual,
  1841. expected: expected,
  1842. message: message,
  1843. negative: true
  1844. });
  1845. }
  1846. }, {
  1847. key: "propEqual",
  1848. value: function propEqual(actual, expected, message) {
  1849. actual = objectValues(actual);
  1850. expected = objectValues(expected);
  1851. this.pushResult({
  1852. result: equiv(actual, expected),
  1853. actual: actual,
  1854. expected: expected,
  1855. message: message
  1856. });
  1857. }
  1858. }, {
  1859. key: "notPropEqual",
  1860. value: function notPropEqual(actual, expected, message) {
  1861. actual = objectValues(actual);
  1862. expected = objectValues(expected);
  1863. this.pushResult({
  1864. result: !equiv(actual, expected),
  1865. actual: actual,
  1866. expected: expected,
  1867. message: message,
  1868. negative: true
  1869. });
  1870. }
  1871. }, {
  1872. key: "deepEqual",
  1873. value: function deepEqual(actual, expected, message) {
  1874. this.pushResult({
  1875. result: equiv(actual, expected),
  1876. actual: actual,
  1877. expected: expected,
  1878. message: message
  1879. });
  1880. }
  1881. }, {
  1882. key: "notDeepEqual",
  1883. value: function notDeepEqual(actual, expected, message) {
  1884. this.pushResult({
  1885. result: !equiv(actual, expected),
  1886. actual: actual,
  1887. expected: expected,
  1888. message: message,
  1889. negative: true
  1890. });
  1891. }
  1892. }, {
  1893. key: "strictEqual",
  1894. value: function strictEqual(actual, expected, message) {
  1895. this.pushResult({
  1896. result: expected === actual,
  1897. actual: actual,
  1898. expected: expected,
  1899. message: message
  1900. });
  1901. }
  1902. }, {
  1903. key: "notStrictEqual",
  1904. value: function notStrictEqual(actual, expected, message) {
  1905. this.pushResult({
  1906. result: expected !== actual,
  1907. actual: actual,
  1908. expected: expected,
  1909. message: message,
  1910. negative: true
  1911. });
  1912. }
  1913. }, {
  1914. key: "throws",
  1915. value: function throws(block, expected, message) {
  1916. var actual = void 0,
  1917. result = false;
  1918. var currentTest = this instanceof Assert && this.test || config.current;
  1919. // 'expected' is optional unless doing string comparison
  1920. if (objectType(expected) === "string") {
  1921. if (message == null) {
  1922. message = expected;
  1923. expected = null;
  1924. } else {
  1925. throw new Error("throws/raises does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. regExp) instead if it's necessary.");
  1926. }
  1927. }
  1928. currentTest.ignoreGlobalErrors = true;
  1929. try {
  1930. block.call(currentTest.testEnvironment);
  1931. } catch (e) {
  1932. actual = e;
  1933. }
  1934. currentTest.ignoreGlobalErrors = false;
  1935. if (actual) {
  1936. var expectedType = objectType(expected);
  1937. // We don't want to validate thrown error
  1938. if (!expected) {
  1939. result = true;
  1940. expected = null;
  1941. // Expected is a regexp
  1942. } else if (expectedType === "regexp") {
  1943. result = expected.test(errorString(actual));
  1944. // Expected is a constructor, maybe an Error constructor
  1945. } else if (expectedType === "function" && actual instanceof expected) {
  1946. result = true;
  1947. // Expected is an Error object
  1948. } else if (expectedType === "object") {
  1949. result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message;
  1950. // Expected is a validation function which returns true if validation passed
  1951. } else if (expectedType === "function" && expected.call({}, actual) === true) {
  1952. expected = null;
  1953. result = true;
  1954. }
  1955. }
  1956. currentTest.assert.pushResult({
  1957. result: result,
  1958. actual: actual,
  1959. expected: expected,
  1960. message: message
  1961. });
  1962. }
  1963. }]);
  1964. return Assert;
  1965. }();
  1966. // Provide an alternative to assert.throws(), for environments that consider throws a reserved word
  1967. // Known to us are: Closure Compiler, Narwhal
  1968. // eslint-disable-next-line dot-notation
  1969. Assert.prototype.raises = Assert.prototype["throws"];
  1970. /**
  1971. * Converts an error into a simple string for comparisons.
  1972. *
  1973. * @param {Error} error
  1974. * @return {String}
  1975. */
  1976. function errorString(error) {
  1977. var resultErrorString = error.toString();
  1978. if (resultErrorString.substring(0, 7) === "[object") {
  1979. var name = error.name ? error.name.toString() : "Error";
  1980. var message = error.message ? error.message.toString() : "";
  1981. if (name && message) {
  1982. return name + ": " + message;
  1983. } else if (name) {
  1984. return name;
  1985. } else if (message) {
  1986. return message;
  1987. } else {
  1988. return "Error";
  1989. }
  1990. } else {
  1991. return resultErrorString;
  1992. }
  1993. }
  1994. /* global module, exports, define */
  1995. function exportQUnit(QUnit) {
  1996. if (defined.document) {
  1997. // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined.
  1998. if (window.QUnit && window.QUnit.version) {
  1999. throw new Error("QUnit has already been defined.");
  2000. }
  2001. window.QUnit = QUnit;
  2002. }
  2003. // For nodejs
  2004. if (typeof module !== "undefined" && module && module.exports) {
  2005. module.exports = QUnit;
  2006. // For consistency with CommonJS environments' exports
  2007. module.exports.QUnit = QUnit;
  2008. }
  2009. // For CommonJS with exports, but without module.exports, like Rhino
  2010. if (typeof exports !== "undefined" && exports) {
  2011. exports.QUnit = QUnit;
  2012. }
  2013. if (typeof define === "function" && define.amd) {
  2014. define(function () {
  2015. return QUnit;
  2016. });
  2017. QUnit.config.autostart = false;
  2018. }
  2019. // For Web/Service Workers
  2020. if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) {
  2021. self$1.QUnit = QUnit;
  2022. }
  2023. }
  2024. var SuiteReport = function () {
  2025. function SuiteReport(name, parentSuite) {
  2026. classCallCheck(this, SuiteReport);
  2027. this.name = name;
  2028. this.fullName = parentSuite ? parentSuite.fullName.concat(name) : [];
  2029. this.tests = [];
  2030. this.childSuites = [];
  2031. if (parentSuite) {
  2032. parentSuite.pushChildSuite(this);
  2033. }
  2034. }
  2035. createClass(SuiteReport, [{
  2036. key: "start",
  2037. value: function start(recordTime) {
  2038. if (recordTime) {
  2039. this._startTime = Date.now();
  2040. }
  2041. return {
  2042. name: this.name,
  2043. fullName: this.fullName.slice(),
  2044. tests: this.tests.map(function (test) {
  2045. return test.start();
  2046. }),
  2047. childSuites: this.childSuites.map(function (suite) {
  2048. return suite.start();
  2049. }),
  2050. testCounts: {
  2051. total: this.getTestCounts().total
  2052. }
  2053. };
  2054. }
  2055. }, {
  2056. key: "end",
  2057. value: function end(recordTime) {
  2058. if (recordTime) {
  2059. this._endTime = Date.now();
  2060. }
  2061. return {
  2062. name: this.name,
  2063. fullName: this.fullName.slice(),
  2064. tests: this.tests.map(function (test) {
  2065. return test.end();
  2066. }),
  2067. childSuites: this.childSuites.map(function (suite) {
  2068. return suite.end();
  2069. }),
  2070. testCounts: this.getTestCounts(),
  2071. runtime: this.getRuntime(),
  2072. status: this.getStatus()
  2073. };
  2074. }
  2075. }, {
  2076. key: "pushChildSuite",
  2077. value: function pushChildSuite(suite) {
  2078. this.childSuites.push(suite);
  2079. }
  2080. }, {
  2081. key: "pushTest",
  2082. value: function pushTest(test) {
  2083. this.tests.push(test);
  2084. }
  2085. }, {
  2086. key: "getRuntime",
  2087. value: function getRuntime() {
  2088. return this._endTime - this._startTime;
  2089. }
  2090. }, {
  2091. key: "getTestCounts",
  2092. value: function getTestCounts() {
  2093. var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 };
  2094. counts = this.tests.reduce(function (counts, test) {
  2095. if (test.valid) {
  2096. counts[test.getStatus()]++;
  2097. counts.total++;
  2098. }
  2099. return counts;
  2100. }, counts);
  2101. return this.childSuites.reduce(function (counts, suite) {
  2102. return suite.getTestCounts(counts);
  2103. }, counts);
  2104. }
  2105. }, {
  2106. key: "getStatus",
  2107. value: function getStatus() {
  2108. var _getTestCounts = this.getTestCounts(),
  2109. total = _getTestCounts.total,
  2110. failed = _getTestCounts.failed,
  2111. skipped = _getTestCounts.skipped,
  2112. todo = _getTestCounts.todo;
  2113. if (failed) {
  2114. return "failed";
  2115. } else {
  2116. if (skipped === total) {
  2117. return "skipped";
  2118. } else if (todo === total) {
  2119. return "todo";
  2120. } else {
  2121. return "passed";
  2122. }
  2123. }
  2124. }
  2125. }]);
  2126. return SuiteReport;
  2127. }();
  2128. // Handle an unhandled exception. By convention, returns true if further
  2129. // error handling should be suppressed and false otherwise.
  2130. // In this case, we will only suppress further error handling if the
  2131. // "ignoreGlobalErrors" configuration option is enabled.
  2132. function onError(error) {
  2133. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  2134. args[_key - 1] = arguments[_key];
  2135. }
  2136. if (config.current) {
  2137. if (config.current.ignoreGlobalErrors) {
  2138. return true;
  2139. }
  2140. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2141. } else {
  2142. test("global failure", extend(function () {
  2143. pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args));
  2144. }, { validTest: true }));
  2145. }
  2146. return false;
  2147. }
  2148. var focused = false;
  2149. var QUnit = {};
  2150. var globalSuite = new SuiteReport();
  2151. // The initial "currentModule" represents the global (or top-level) module that
  2152. // is not explicitly defined by the user, therefore we add the "globalSuite" to
  2153. // it since each module has a suiteReport associated with it.
  2154. config.currentModule.suiteReport = globalSuite;
  2155. var moduleStack = [];
  2156. var globalStartCalled = false;
  2157. var runStarted = false;
  2158. // Figure out if we're running the tests from a server or not
  2159. QUnit.isLocal = !(defined.document && window.location.protocol !== "file:");
  2160. // Expose the current QUnit version
  2161. QUnit.version = "2.4.0";
  2162. function createModule(name, testEnvironment, modifiers) {
  2163. var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null;
  2164. var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name;
  2165. var parentSuite = parentModule ? parentModule.suiteReport : globalSuite;
  2166. var skip$$1 = parentModule !== null && parentModule.skip || modifiers.skip;
  2167. var todo$$1 = parentModule !== null && parentModule.todo || modifiers.todo;
  2168. var module = {
  2169. name: moduleName,
  2170. parentModule: parentModule,
  2171. tests: [],
  2172. moduleId: generateHash(moduleName),
  2173. testsRun: 0,
  2174. unskippedTestsRun: 0,
  2175. childModules: [],
  2176. suiteReport: new SuiteReport(name, parentSuite),
  2177. // Pass along `skip` and `todo` properties from parent module, in case
  2178. // there is one, to childs. And use own otherwise.
  2179. // This property will be used to mark own tests and tests of child suites
  2180. // as either `skipped` or `todo`.
  2181. skip: skip$$1,
  2182. todo: skip$$1 ? false : todo$$1
  2183. };
  2184. var env = {};
  2185. if (parentModule) {
  2186. parentModule.childModules.push(module);
  2187. extend(env, parentModule.testEnvironment);
  2188. }
  2189. extend(env, testEnvironment);
  2190. module.testEnvironment = env;
  2191. config.modules.push(module);
  2192. return module;
  2193. }
  2194. function processModule(name, options, executeNow) {
  2195. var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  2196. var module = createModule(name, options, modifiers);
  2197. // Move any hooks to a 'hooks' object
  2198. var testEnvironment = module.testEnvironment;
  2199. var hooks = module.hooks = {};
  2200. setHookFromEnvironment(hooks, testEnvironment, "before");
  2201. setHookFromEnvironment(hooks, testEnvironment, "beforeEach");
  2202. setHookFromEnvironment(hooks, testEnvironment, "afterEach");
  2203. setHookFromEnvironment(hooks, testEnvironment, "after");
  2204. function setHookFromEnvironment(hooks, environment, name) {
  2205. var potentialHook = environment[name];
  2206. hooks[name] = typeof potentialHook === "function" ? [potentialHook] : [];
  2207. delete environment[name];
  2208. }
  2209. var moduleFns = {
  2210. before: setHookFunction(module, "before"),
  2211. beforeEach: setHookFunction(module, "beforeEach"),
  2212. afterEach: setHookFunction(module, "afterEach"),
  2213. after: setHookFunction(module, "after")
  2214. };
  2215. var currentModule = config.currentModule;
  2216. if (objectType(executeNow) === "function") {
  2217. moduleStack.push(module);
  2218. config.currentModule = module;
  2219. executeNow.call(module.testEnvironment, moduleFns);
  2220. moduleStack.pop();
  2221. module = module.parentModule || currentModule;
  2222. }
  2223. config.currentModule = module;
  2224. }
  2225. // TODO: extract this to a new file alongside its related functions
  2226. function module$1(name, options, executeNow) {
  2227. if (focused) {
  2228. return;
  2229. }
  2230. if (arguments.length === 2) {
  2231. if (objectType(options) === "function") {
  2232. executeNow = options;
  2233. options = undefined;
  2234. }
  2235. }
  2236. processModule(name, options, executeNow);
  2237. }
  2238. module$1.only = function () {
  2239. if (focused) {
  2240. return;
  2241. }
  2242. config.modules.length = 0;
  2243. config.queue.length = 0;
  2244. module$1.apply(undefined, arguments);
  2245. focused = true;
  2246. };
  2247. module$1.skip = function (name, options, executeNow) {
  2248. if (focused) {
  2249. return;
  2250. }
  2251. if (arguments.length === 2) {
  2252. if (objectType(options) === "function") {
  2253. executeNow = options;
  2254. options = undefined;
  2255. }
  2256. }
  2257. processModule(name, options, executeNow, { skip: true });
  2258. };
  2259. module$1.todo = function (name, options, executeNow) {
  2260. if (focused) {
  2261. return;
  2262. }
  2263. if (arguments.length === 2) {
  2264. if (objectType(options) === "function") {
  2265. executeNow = options;
  2266. options = undefined;
  2267. }
  2268. }
  2269. processModule(name, options, executeNow, { todo: true });
  2270. };
  2271. extend(QUnit, {
  2272. on: on,
  2273. module: module$1,
  2274. test: test,
  2275. todo: todo,
  2276. skip: skip,
  2277. only: only,
  2278. start: function start(count) {
  2279. var globalStartAlreadyCalled = globalStartCalled;
  2280. if (!config.current) {
  2281. globalStartCalled = true;
  2282. if (runStarted) {
  2283. throw new Error("Called start() while test already started running");
  2284. } else if (globalStartAlreadyCalled || count > 1) {
  2285. throw new Error("Called start() outside of a test context too many times");
  2286. } else if (config.autostart) {
  2287. throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true");
  2288. } else if (!config.pageLoaded) {
  2289. // The page isn't completely loaded yet, so we set autostart and then
  2290. // load if we're in Node or wait for the browser's load event.
  2291. config.autostart = true;
  2292. // Starts from Node even if .load was not previously called. We still return
  2293. // early otherwise we'll wind up "beginning" twice.
  2294. if (!defined.document) {
  2295. QUnit.load();
  2296. }
  2297. return;
  2298. }
  2299. } else {
  2300. throw new Error("QUnit.start cannot be called inside a test context.");
  2301. }
  2302. scheduleBegin();
  2303. },
  2304. config: config,
  2305. is: is,
  2306. objectType: objectType,
  2307. extend: extend,
  2308. load: function load() {
  2309. config.pageLoaded = true;
  2310. // Initialize the configuration options
  2311. extend(config, {
  2312. stats: { all: 0, bad: 0 },
  2313. started: 0,
  2314. updateRate: 1000,
  2315. autostart: true,
  2316. filter: ""
  2317. }, true);
  2318. if (!runStarted) {
  2319. config.blocking = false;
  2320. if (config.autostart) {
  2321. scheduleBegin();
  2322. }
  2323. }
  2324. },
  2325. stack: function stack(offset) {
  2326. offset = (offset || 0) + 2;
  2327. return sourceFromStacktrace(offset);
  2328. },
  2329. onError: onError
  2330. });
  2331. QUnit.pushFailure = pushFailure;
  2332. QUnit.assert = Assert.prototype;
  2333. QUnit.equiv = equiv;
  2334. QUnit.dump = dump;
  2335. registerLoggingCallbacks(QUnit);
  2336. function scheduleBegin() {
  2337. runStarted = true;
  2338. // Add a slight delay to allow definition of more modules and tests.
  2339. if (defined.setTimeout) {
  2340. setTimeout(function () {
  2341. begin();
  2342. }, 13);
  2343. } else {
  2344. begin();
  2345. }
  2346. }
  2347. function begin() {
  2348. var i,
  2349. l,
  2350. modulesLog = [];
  2351. // If the test run hasn't officially begun yet
  2352. if (!config.started) {
  2353. // Record the time of the test run's beginning
  2354. config.started = now();
  2355. // Delete the loose unnamed module if unused.
  2356. if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
  2357. config.modules.shift();
  2358. }
  2359. // Avoid unnecessary information by not logging modules' test environments
  2360. for (i = 0, l = config.modules.length; i < l; i++) {
  2361. modulesLog.push({
  2362. name: config.modules[i].name,
  2363. tests: config.modules[i].tests
  2364. });
  2365. }
  2366. // The test run is officially beginning now
  2367. emit("runStart", globalSuite.start(true));
  2368. runLoggingCallbacks("begin", {
  2369. totalTests: Test.count,
  2370. modules: modulesLog
  2371. });
  2372. }
  2373. config.blocking = false;
  2374. ProcessingQueue.advance();
  2375. }
  2376. function setHookFunction(module, hookName) {
  2377. return function setHook(callback) {
  2378. module.hooks[hookName].push(callback);
  2379. };
  2380. }
  2381. exportQUnit(QUnit);
  2382. (function () {
  2383. if (typeof window === "undefined" || typeof document === "undefined") {
  2384. return;
  2385. }
  2386. var config = QUnit.config,
  2387. hasOwn = Object.prototype.hasOwnProperty;
  2388. // Stores fixture HTML for resetting later
  2389. function storeFixture() {
  2390. // Avoid overwriting user-defined values
  2391. if (hasOwn.call(config, "fixture")) {
  2392. return;
  2393. }
  2394. var fixture = document.getElementById("qunit-fixture");
  2395. if (fixture) {
  2396. config.fixture = fixture.innerHTML;
  2397. }
  2398. }
  2399. QUnit.begin(storeFixture);
  2400. // Resets the fixture DOM element if available.
  2401. function resetFixture() {
  2402. if (config.fixture == null) {
  2403. return;
  2404. }
  2405. var fixture = document.getElementById("qunit-fixture");
  2406. if (fixture) {
  2407. fixture.innerHTML = config.fixture;
  2408. }
  2409. }
  2410. QUnit.testStart(resetFixture);
  2411. })();
  2412. (function () {
  2413. // Only interact with URLs via window.location
  2414. var location = typeof window !== "undefined" && window.location;
  2415. if (!location) {
  2416. return;
  2417. }
  2418. var urlParams = getUrlParams();
  2419. QUnit.urlParams = urlParams;
  2420. // Match module/test by inclusion in an array
  2421. QUnit.config.moduleId = [].concat(urlParams.moduleId || []);
  2422. QUnit.config.testId = [].concat(urlParams.testId || []);
  2423. // Exact case-insensitive match of the module name
  2424. QUnit.config.module = urlParams.module;
  2425. // Regular expression or case-insenstive substring match against "moduleName: testName"
  2426. QUnit.config.filter = urlParams.filter;
  2427. // Test order randomization
  2428. if (urlParams.seed === true) {
  2429. // Generate a random seed if the option is specified without a value
  2430. QUnit.config.seed = Math.random().toString(36).slice(2);
  2431. } else if (urlParams.seed) {
  2432. QUnit.config.seed = urlParams.seed;
  2433. }
  2434. // Add URL-parameter-mapped config values with UI form rendering data
  2435. QUnit.config.urlConfig.push({
  2436. id: "hidepassed",
  2437. label: "Hide passed tests",
  2438. tooltip: "Only show tests and assertions that fail. Stored as query-strings."
  2439. }, {
  2440. id: "noglobals",
  2441. label: "Check for Globals",
  2442. tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings."
  2443. }, {
  2444. id: "notrycatch",
  2445. label: "No try-catch",
  2446. tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings."
  2447. });
  2448. QUnit.begin(function () {
  2449. var i,
  2450. option,
  2451. urlConfig = QUnit.config.urlConfig;
  2452. for (i = 0; i < urlConfig.length; i++) {
  2453. // Options can be either strings or objects with nonempty "id" properties
  2454. option = QUnit.config.urlConfig[i];
  2455. if (typeof option !== "string") {
  2456. option = option.id;
  2457. }
  2458. if (QUnit.config[option] === undefined) {
  2459. QUnit.config[option] = urlParams[option];
  2460. }
  2461. }
  2462. });
  2463. function getUrlParams() {
  2464. var i, param, name, value;
  2465. var urlParams = Object.create(null);
  2466. var params = location.search.slice(1).split("&");
  2467. var length = params.length;
  2468. for (i = 0; i < length; i++) {
  2469. if (params[i]) {
  2470. param = params[i].split("=");
  2471. name = decodeQueryParam(param[0]);
  2472. // Allow just a key to turn on a flag, e.g., test.html?noglobals
  2473. value = param.length === 1 || decodeQueryParam(param.slice(1).join("="));
  2474. if (name in urlParams) {
  2475. urlParams[name] = [].concat(urlParams[name], value);
  2476. } else {
  2477. urlParams[name] = value;
  2478. }
  2479. }
  2480. }
  2481. return urlParams;
  2482. }
  2483. function decodeQueryParam(param) {
  2484. return decodeURIComponent(param.replace(/\+/g, "%20"));
  2485. }
  2486. })();
  2487. var stats = {
  2488. passedTests: 0,
  2489. failedTests: 0,
  2490. skippedTests: 0,
  2491. todoTests: 0
  2492. };
  2493. // Escape text for attribute or text content.
  2494. function escapeText(s) {
  2495. if (!s) {
  2496. return "";
  2497. }
  2498. s = s + "";
  2499. // Both single quotes and double quotes (for attributes)
  2500. return s.replace(/['"<>&]/g, function (s) {
  2501. switch (s) {
  2502. case "'":
  2503. return "&#039;";
  2504. case "\"":
  2505. return "&quot;";
  2506. case "<":
  2507. return "&lt;";
  2508. case ">":
  2509. return "&gt;";
  2510. case "&":
  2511. return "&amp;";
  2512. }
  2513. });
  2514. }
  2515. (function () {
  2516. // Don't load the HTML Reporter on non-browser environments
  2517. if (typeof window === "undefined" || !window.document) {
  2518. return;
  2519. }
  2520. var config = QUnit.config,
  2521. document$$1 = window.document,
  2522. collapseNext = false,
  2523. hasOwn = Object.prototype.hasOwnProperty,
  2524. unfilteredUrl = setUrl({ filter: undefined, module: undefined,
  2525. moduleId: undefined, testId: undefined }),
  2526. modulesList = [];
  2527. function addEvent(elem, type, fn) {
  2528. elem.addEventListener(type, fn, false);
  2529. }
  2530. function removeEvent(elem, type, fn) {
  2531. elem.removeEventListener(type, fn, false);
  2532. }
  2533. function addEvents(elems, type, fn) {
  2534. var i = elems.length;
  2535. while (i--) {
  2536. addEvent(elems[i], type, fn);
  2537. }
  2538. }
  2539. function hasClass(elem, name) {
  2540. return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0;
  2541. }
  2542. function addClass(elem, name) {
  2543. if (!hasClass(elem, name)) {
  2544. elem.className += (elem.className ? " " : "") + name;
  2545. }
  2546. }
  2547. function toggleClass(elem, name, force) {
  2548. if (force || typeof force === "undefined" && !hasClass(elem, name)) {
  2549. addClass(elem, name);
  2550. } else {
  2551. removeClass(elem, name);
  2552. }
  2553. }
  2554. function removeClass(elem, name) {
  2555. var set = " " + elem.className + " ";
  2556. // Class name may appear multiple times
  2557. while (set.indexOf(" " + name + " ") >= 0) {
  2558. set = set.replace(" " + name + " ", " ");
  2559. }
  2560. // Trim for prettiness
  2561. elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
  2562. }
  2563. function id(name) {
  2564. return document$$1.getElementById && document$$1.getElementById(name);
  2565. }
  2566. function abortTests() {
  2567. var abortButton = id("qunit-abort-tests-button");
  2568. if (abortButton) {
  2569. abortButton.disabled = true;
  2570. abortButton.innerHTML = "Aborting...";
  2571. }
  2572. QUnit.config.queue.length = 0;
  2573. return false;
  2574. }
  2575. function interceptNavigation(ev) {
  2576. applyUrlParams();
  2577. if (ev && ev.preventDefault) {
  2578. ev.preventDefault();
  2579. }
  2580. return false;
  2581. }
  2582. function getUrlConfigHtml() {
  2583. var i,
  2584. j,
  2585. val,
  2586. escaped,
  2587. escapedTooltip,
  2588. selection = false,
  2589. urlConfig = config.urlConfig,
  2590. urlConfigHtml = "";
  2591. for (i = 0; i < urlConfig.length; i++) {
  2592. // Options can be either strings or objects with nonempty "id" properties
  2593. val = config.urlConfig[i];
  2594. if (typeof val === "string") {
  2595. val = {
  2596. id: val,
  2597. label: val
  2598. };
  2599. }
  2600. escaped = escapeText(val.id);
  2601. escapedTooltip = escapeText(val.tooltip);
  2602. if (!val.value || typeof val.value === "string") {
  2603. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'><input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + (val.value ? " value='" + escapeText(val.value) + "'" : "") + (config[val.id] ? " checked='checked'" : "") + " title='" + escapedTooltip + "' />" + escapeText(val.label) + "</label>";
  2604. } else {
  2605. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
  2606. if (QUnit.is("array", val.value)) {
  2607. for (j = 0; j < val.value.length; j++) {
  2608. escaped = escapeText(val.value[j]);
  2609. urlConfigHtml += "<option value='" + escaped + "'" + (config[val.id] === val.value[j] ? (selection = true) && " selected='selected'" : "") + ">" + escaped + "</option>";
  2610. }
  2611. } else {
  2612. for (j in val.value) {
  2613. if (hasOwn.call(val.value, j)) {
  2614. urlConfigHtml += "<option value='" + escapeText(j) + "'" + (config[val.id] === j ? (selection = true) && " selected='selected'" : "") + ">" + escapeText(val.value[j]) + "</option>";
  2615. }
  2616. }
  2617. }
  2618. if (config[val.id] && !selection) {
  2619. escaped = escapeText(config[val.id]);
  2620. urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>";
  2621. }
  2622. urlConfigHtml += "</select>";
  2623. }
  2624. }
  2625. return urlConfigHtml;
  2626. }
  2627. // Handle "click" events on toolbar checkboxes and "change" for select menus.
  2628. // Updates the URL with the new state of `config.urlConfig` values.
  2629. function toolbarChanged() {
  2630. var updatedUrl,
  2631. value,
  2632. tests,
  2633. field = this,
  2634. params = {};
  2635. // Detect if field is a select menu or a checkbox
  2636. if ("selectedIndex" in field) {
  2637. value = field.options[field.selectedIndex].value || undefined;
  2638. } else {
  2639. value = field.checked ? field.defaultValue || true : undefined;
  2640. }
  2641. params[field.name] = value;
  2642. updatedUrl = setUrl(params);
  2643. // Check if we can apply the change without a page refresh
  2644. if ("hidepassed" === field.name && "replaceState" in window.history) {
  2645. QUnit.urlParams[field.name] = value;
  2646. config[field.name] = value || false;
  2647. tests = id("qunit-tests");
  2648. if (tests) {
  2649. toggleClass(tests, "hidepass", value || false);
  2650. }
  2651. window.history.replaceState(null, "", updatedUrl);
  2652. } else {
  2653. window.location = updatedUrl;
  2654. }
  2655. }
  2656. function setUrl(params) {
  2657. var key,
  2658. arrValue,
  2659. i,
  2660. querystring = "?",
  2661. location = window.location;
  2662. params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
  2663. for (key in params) {
  2664. // Skip inherited or undefined properties
  2665. if (hasOwn.call(params, key) && params[key] !== undefined) {
  2666. // Output a parameter for each value of this key (but usually just one)
  2667. arrValue = [].concat(params[key]);
  2668. for (i = 0; i < arrValue.length; i++) {
  2669. querystring += encodeURIComponent(key);
  2670. if (arrValue[i] !== true) {
  2671. querystring += "=" + encodeURIComponent(arrValue[i]);
  2672. }
  2673. querystring += "&";
  2674. }
  2675. }
  2676. }
  2677. return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1);
  2678. }
  2679. function applyUrlParams() {
  2680. var i,
  2681. selectedModules = [],
  2682. modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"),
  2683. filter = id("qunit-filter-input").value;
  2684. for (i = 0; i < modulesList.length; i++) {
  2685. if (modulesList[i].checked) {
  2686. selectedModules.push(modulesList[i].value);
  2687. }
  2688. }
  2689. window.location = setUrl({
  2690. filter: filter === "" ? undefined : filter,
  2691. moduleId: selectedModules.length === 0 ? undefined : selectedModules,
  2692. // Remove module and testId filter
  2693. module: undefined,
  2694. testId: undefined
  2695. });
  2696. }
  2697. function toolbarUrlConfigContainer() {
  2698. var urlConfigContainer = document$$1.createElement("span");
  2699. urlConfigContainer.innerHTML = getUrlConfigHtml();
  2700. addClass(urlConfigContainer, "qunit-url-config");
  2701. addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged);
  2702. addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
  2703. return urlConfigContainer;
  2704. }
  2705. function abortTestsButton() {
  2706. var button = document$$1.createElement("button");
  2707. button.id = "qunit-abort-tests-button";
  2708. button.innerHTML = "Abort";
  2709. addEvent(button, "click", abortTests);
  2710. return button;
  2711. }
  2712. function toolbarLooseFilter() {
  2713. var filter = document$$1.createElement("form"),
  2714. label = document$$1.createElement("label"),
  2715. input = document$$1.createElement("input"),
  2716. button = document$$1.createElement("button");
  2717. addClass(filter, "qunit-filter");
  2718. label.innerHTML = "Filter: ";
  2719. input.type = "text";
  2720. input.value = config.filter || "";
  2721. input.name = "filter";
  2722. input.id = "qunit-filter-input";
  2723. button.innerHTML = "Go";
  2724. label.appendChild(input);
  2725. filter.appendChild(label);
  2726. filter.appendChild(document$$1.createTextNode(" "));
  2727. filter.appendChild(button);
  2728. addEvent(filter, "submit", interceptNavigation);
  2729. return filter;
  2730. }
  2731. function moduleListHtml() {
  2732. var i,
  2733. checked,
  2734. html = "";
  2735. for (i = 0; i < config.modules.length; i++) {
  2736. if (config.modules[i].name !== "") {
  2737. checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1;
  2738. html += "<li><label class='clickable" + (checked ? " checked" : "") + "'><input type='checkbox' " + "value='" + config.modules[i].moduleId + "'" + (checked ? " checked='checked'" : "") + " />" + escapeText(config.modules[i].name) + "</label></li>";
  2739. }
  2740. }
  2741. return html;
  2742. }
  2743. function toolbarModuleFilter() {
  2744. var allCheckbox,
  2745. commit,
  2746. reset,
  2747. moduleFilter = document$$1.createElement("form"),
  2748. label = document$$1.createElement("label"),
  2749. moduleSearch = document$$1.createElement("input"),
  2750. dropDown = document$$1.createElement("div"),
  2751. actions = document$$1.createElement("span"),
  2752. dropDownList = document$$1.createElement("ul"),
  2753. dirty = false;
  2754. moduleSearch.id = "qunit-modulefilter-search";
  2755. addEvent(moduleSearch, "input", searchInput);
  2756. addEvent(moduleSearch, "input", searchFocus);
  2757. addEvent(moduleSearch, "focus", searchFocus);
  2758. addEvent(moduleSearch, "click", searchFocus);
  2759. label.id = "qunit-modulefilter-search-container";
  2760. label.innerHTML = "Module: ";
  2761. label.appendChild(moduleSearch);
  2762. actions.id = "qunit-modulefilter-actions";
  2763. actions.innerHTML = "<button style='display:none'>Apply</button>" + "<button type='reset' style='display:none'>Reset</button>" + "<label class='clickable" + (config.moduleId.length ? "" : " checked") + "'><input type='checkbox'" + (config.moduleId.length ? "" : " checked='checked'") + ">All modules</label>";
  2764. allCheckbox = actions.lastChild.firstChild;
  2765. commit = actions.firstChild;
  2766. reset = commit.nextSibling;
  2767. addEvent(commit, "click", applyUrlParams);
  2768. dropDownList.id = "qunit-modulefilter-dropdown-list";
  2769. dropDownList.innerHTML = moduleListHtml();
  2770. dropDown.id = "qunit-modulefilter-dropdown";
  2771. dropDown.style.display = "none";
  2772. dropDown.appendChild(actions);
  2773. dropDown.appendChild(dropDownList);
  2774. addEvent(dropDown, "change", selectionChange);
  2775. selectionChange();
  2776. moduleFilter.id = "qunit-modulefilter";
  2777. moduleFilter.appendChild(label);
  2778. moduleFilter.appendChild(dropDown);
  2779. addEvent(moduleFilter, "submit", interceptNavigation);
  2780. addEvent(moduleFilter, "reset", function () {
  2781. // Let the reset happen, then update styles
  2782. window.setTimeout(selectionChange);
  2783. });
  2784. // Enables show/hide for the dropdown
  2785. function searchFocus() {
  2786. if (dropDown.style.display !== "none") {
  2787. return;
  2788. }
  2789. dropDown.style.display = "block";
  2790. addEvent(document$$1, "click", hideHandler);
  2791. addEvent(document$$1, "keydown", hideHandler);
  2792. // Hide on Escape keydown or outside-container click
  2793. function hideHandler(e) {
  2794. var inContainer = moduleFilter.contains(e.target);
  2795. if (e.keyCode === 27 || !inContainer) {
  2796. if (e.keyCode === 27 && inContainer) {
  2797. moduleSearch.focus();
  2798. }
  2799. dropDown.style.display = "none";
  2800. removeEvent(document$$1, "click", hideHandler);
  2801. removeEvent(document$$1, "keydown", hideHandler);
  2802. moduleSearch.value = "";
  2803. searchInput();
  2804. }
  2805. }
  2806. }
  2807. // Processes module search box input
  2808. function searchInput() {
  2809. var i,
  2810. item,
  2811. searchText = moduleSearch.value.toLowerCase(),
  2812. listItems = dropDownList.children;
  2813. for (i = 0; i < listItems.length; i++) {
  2814. item = listItems[i];
  2815. if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) {
  2816. item.style.display = "";
  2817. } else {
  2818. item.style.display = "none";
  2819. }
  2820. }
  2821. }
  2822. // Processes selection changes
  2823. function selectionChange(evt) {
  2824. var i,
  2825. item,
  2826. checkbox = evt && evt.target || allCheckbox,
  2827. modulesList = dropDownList.getElementsByTagName("input"),
  2828. selectedNames = [];
  2829. toggleClass(checkbox.parentNode, "checked", checkbox.checked);
  2830. dirty = false;
  2831. if (checkbox.checked && checkbox !== allCheckbox) {
  2832. allCheckbox.checked = false;
  2833. removeClass(allCheckbox.parentNode, "checked");
  2834. }
  2835. for (i = 0; i < modulesList.length; i++) {
  2836. item = modulesList[i];
  2837. if (!evt) {
  2838. toggleClass(item.parentNode, "checked", item.checked);
  2839. } else if (checkbox === allCheckbox && checkbox.checked) {
  2840. item.checked = false;
  2841. removeClass(item.parentNode, "checked");
  2842. }
  2843. dirty = dirty || item.checked !== item.defaultChecked;
  2844. if (item.checked) {
  2845. selectedNames.push(item.parentNode.textContent);
  2846. }
  2847. }
  2848. commit.style.display = reset.style.display = dirty ? "" : "none";
  2849. moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent;
  2850. moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent);
  2851. }
  2852. return moduleFilter;
  2853. }
  2854. function appendToolbar() {
  2855. var toolbar = id("qunit-testrunner-toolbar");
  2856. if (toolbar) {
  2857. toolbar.appendChild(toolbarUrlConfigContainer());
  2858. toolbar.appendChild(toolbarModuleFilter());
  2859. toolbar.appendChild(toolbarLooseFilter());
  2860. toolbar.appendChild(document$$1.createElement("div")).className = "clearfix";
  2861. }
  2862. }
  2863. function appendHeader() {
  2864. var header = id("qunit-header");
  2865. if (header) {
  2866. header.innerHTML = "<a href='" + escapeText(unfilteredUrl) + "'>" + header.innerHTML + "</a> ";
  2867. }
  2868. }
  2869. function appendBanner() {
  2870. var banner = id("qunit-banner");
  2871. if (banner) {
  2872. banner.className = "";
  2873. }
  2874. }
  2875. function appendTestResults() {
  2876. var tests = id("qunit-tests"),
  2877. result = id("qunit-testresult"),
  2878. controls;
  2879. if (result) {
  2880. result.parentNode.removeChild(result);
  2881. }
  2882. if (tests) {
  2883. tests.innerHTML = "";
  2884. result = document$$1.createElement("p");
  2885. result.id = "qunit-testresult";
  2886. result.className = "result";
  2887. tests.parentNode.insertBefore(result, tests);
  2888. result.innerHTML = "<div id=\"qunit-testresult-display\">Running...<br />&#160;</div>" + "<div id=\"qunit-testresult-controls\"></div>" + "<div class=\"clearfix\"></div>";
  2889. controls = id("qunit-testresult-controls");
  2890. }
  2891. if (controls) {
  2892. controls.appendChild(abortTestsButton());
  2893. }
  2894. }
  2895. function appendFilteredTest() {
  2896. var testId = QUnit.config.testId;
  2897. if (!testId || testId.length <= 0) {
  2898. return "";
  2899. }
  2900. return "<div id='qunit-filteredTest'>Rerunning selected tests: " + escapeText(testId.join(", ")) + " <a id='qunit-clearFilter' href='" + escapeText(unfilteredUrl) + "'>Run all tests</a></div>";
  2901. }
  2902. function appendUserAgent() {
  2903. var userAgent = id("qunit-userAgent");
  2904. if (userAgent) {
  2905. userAgent.innerHTML = "";
  2906. userAgent.appendChild(document$$1.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent));
  2907. }
  2908. }
  2909. function appendInterface() {
  2910. var qunit = id("qunit");
  2911. if (qunit) {
  2912. qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText(document$$1.title) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + appendFilteredTest() + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>";
  2913. }
  2914. appendHeader();
  2915. appendBanner();
  2916. appendTestResults();
  2917. appendUserAgent();
  2918. appendToolbar();
  2919. }
  2920. function appendTestsList(modules) {
  2921. var i, l, x, z, test, moduleObj;
  2922. for (i = 0, l = modules.length; i < l; i++) {
  2923. moduleObj = modules[i];
  2924. for (x = 0, z = moduleObj.tests.length; x < z; x++) {
  2925. test = moduleObj.tests[x];
  2926. appendTest(test.name, test.testId, moduleObj.name);
  2927. }
  2928. }
  2929. }
  2930. function appendTest(name, testId, moduleName) {
  2931. var title,
  2932. rerunTrigger,
  2933. testBlock,
  2934. assertList,
  2935. tests = id("qunit-tests");
  2936. if (!tests) {
  2937. return;
  2938. }
  2939. title = document$$1.createElement("strong");
  2940. title.innerHTML = getNameHtml(name, moduleName);
  2941. rerunTrigger = document$$1.createElement("a");
  2942. rerunTrigger.innerHTML = "Rerun";
  2943. rerunTrigger.href = setUrl({ testId: testId });
  2944. testBlock = document$$1.createElement("li");
  2945. testBlock.appendChild(title);
  2946. testBlock.appendChild(rerunTrigger);
  2947. testBlock.id = "qunit-test-output-" + testId;
  2948. assertList = document$$1.createElement("ol");
  2949. assertList.className = "qunit-assert-list";
  2950. testBlock.appendChild(assertList);
  2951. tests.appendChild(testBlock);
  2952. }
  2953. // HTML Reporter initialization and load
  2954. QUnit.begin(function (details) {
  2955. var i, moduleObj, tests;
  2956. // Sort modules by name for the picker
  2957. for (i = 0; i < details.modules.length; i++) {
  2958. moduleObj = details.modules[i];
  2959. if (moduleObj.name) {
  2960. modulesList.push(moduleObj.name);
  2961. }
  2962. }
  2963. modulesList.sort(function (a, b) {
  2964. return a.localeCompare(b);
  2965. });
  2966. // Initialize QUnit elements
  2967. appendInterface();
  2968. appendTestsList(details.modules);
  2969. tests = id("qunit-tests");
  2970. if (tests && config.hidepassed) {
  2971. addClass(tests, "hidepass");
  2972. }
  2973. });
  2974. QUnit.done(function (details) {
  2975. var banner = id("qunit-banner"),
  2976. tests = id("qunit-tests"),
  2977. abortButton = id("qunit-abort-tests-button"),
  2978. totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests,
  2979. html = [totalTests, " tests completed in ", details.runtime, " milliseconds, with ", stats.failedTests, " failed, ", stats.skippedTests, " skipped, and ", stats.todoTests, " todo.<br />", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed."].join(""),
  2980. test,
  2981. assertLi,
  2982. assertList;
  2983. // Update remaing tests to aborted
  2984. if (abortButton && abortButton.disabled) {
  2985. html = "Tests aborted after " + details.runtime + " milliseconds.";
  2986. for (var i = 0; i < tests.children.length; i++) {
  2987. test = tests.children[i];
  2988. if (test.className === "" || test.className === "running") {
  2989. test.className = "aborted";
  2990. assertList = test.getElementsByTagName("ol")[0];
  2991. assertLi = document$$1.createElement("li");
  2992. assertLi.className = "fail";
  2993. assertLi.innerHTML = "Test aborted.";
  2994. assertList.appendChild(assertLi);
  2995. }
  2996. }
  2997. }
  2998. if (banner && (!abortButton || abortButton.disabled === false)) {
  2999. banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass";
  3000. }
  3001. if (abortButton) {
  3002. abortButton.parentNode.removeChild(abortButton);
  3003. }
  3004. if (tests) {
  3005. id("qunit-testresult-display").innerHTML = html;
  3006. }
  3007. if (config.altertitle && document$$1.title) {
  3008. // Show ✖ for good, ✔ for bad suite result in title
  3009. // use escape sequences in case file gets loaded with non-utf-8-charset
  3010. document$$1.title = [stats.failedTests ? "\u2716" : "\u2714", document$$1.title.replace(/^[\u2714\u2716] /i, "")].join(" ");
  3011. }
  3012. // Scroll back to top to show results
  3013. if (config.scrolltop && window.scrollTo) {
  3014. window.scrollTo(0, 0);
  3015. }
  3016. });
  3017. function getNameHtml(name, module) {
  3018. var nameHtml = "";
  3019. if (module) {
  3020. nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
  3021. }
  3022. nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
  3023. return nameHtml;
  3024. }
  3025. QUnit.testStart(function (details) {
  3026. var running, testBlock, bad;
  3027. testBlock = id("qunit-test-output-" + details.testId);
  3028. if (testBlock) {
  3029. testBlock.className = "running";
  3030. } else {
  3031. // Report later registered tests
  3032. appendTest(details.name, details.testId, details.module);
  3033. }
  3034. running = id("qunit-testresult-display");
  3035. if (running) {
  3036. bad = QUnit.config.reorder && details.previousFailure;
  3037. running.innerHTML = (bad ? "Rerunning previously failed test: <br />" : "Running: <br />") + getNameHtml(details.name, details.module);
  3038. }
  3039. });
  3040. function stripHtml(string) {
  3041. // Strip tags, html entity and whitespaces
  3042. return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\&quot;/g, "").replace(/\s+/g, "");
  3043. }
  3044. QUnit.log(function (details) {
  3045. var assertList,
  3046. assertLi,
  3047. message,
  3048. expected,
  3049. actual,
  3050. diff,
  3051. showDiff = false,
  3052. testItem = id("qunit-test-output-" + details.testId);
  3053. if (!testItem) {
  3054. return;
  3055. }
  3056. message = escapeText(details.message) || (details.result ? "okay" : "failed");
  3057. message = "<span class='test-message'>" + message + "</span>";
  3058. message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
  3059. // The pushFailure doesn't provide details.expected
  3060. // when it calls, it's implicit to also not show expected and diff stuff
  3061. // Also, we need to check details.expected existence, as it can exist and be undefined
  3062. if (!details.result && hasOwn.call(details, "expected")) {
  3063. if (details.negative) {
  3064. expected = "NOT " + QUnit.dump.parse(details.expected);
  3065. } else {
  3066. expected = QUnit.dump.parse(details.expected);
  3067. }
  3068. actual = QUnit.dump.parse(details.actual);
  3069. message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + escapeText(expected) + "</pre></td></tr>";
  3070. if (actual !== expected) {
  3071. message += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText(actual) + "</pre></td></tr>";
  3072. if (typeof details.actual === "number" && typeof details.expected === "number") {
  3073. if (!isNaN(details.actual) && !isNaN(details.expected)) {
  3074. showDiff = true;
  3075. diff = details.actual - details.expected;
  3076. diff = (diff > 0 ? "+" : "") + diff;
  3077. }
  3078. } else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") {
  3079. diff = QUnit.diff(expected, actual);
  3080. // don't show diff if there is zero overlap
  3081. showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length;
  3082. }
  3083. if (showDiff) {
  3084. message += "<tr class='test-diff'><th>Diff: </th><td><pre>" + diff + "</pre></td></tr>";
  3085. }
  3086. } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) {
  3087. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the depth of object is more than current max depth (" + QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " + " run with a higher max depth or <a href='" + escapeText(setUrl({ maxDepth: -1 })) + "'>" + "Rerun</a> without max depth.</p></td></tr>";
  3088. } else {
  3089. message += "<tr class='test-message'><th>Message: </th><td>" + "Diff suppressed as the expected and actual results have an equivalent" + " serialization</td></tr>";
  3090. }
  3091. if (details.source) {
  3092. message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>";
  3093. }
  3094. message += "</table>";
  3095. // This occurs when pushFailure is set and we have an extracted stack trace
  3096. } else if (!details.result && details.source) {
  3097. message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText(details.source) + "</pre></td></tr>" + "</table>";
  3098. }
  3099. assertList = testItem.getElementsByTagName("ol")[0];
  3100. assertLi = document$$1.createElement("li");
  3101. assertLi.className = details.result ? "pass" : "fail";
  3102. assertLi.innerHTML = message;
  3103. assertList.appendChild(assertLi);
  3104. });
  3105. QUnit.testDone(function (details) {
  3106. var testTitle,
  3107. time,
  3108. testItem,
  3109. assertList,
  3110. good,
  3111. bad,
  3112. testCounts,
  3113. skipped,
  3114. sourceName,
  3115. tests = id("qunit-tests");
  3116. if (!tests) {
  3117. return;
  3118. }
  3119. testItem = id("qunit-test-output-" + details.testId);
  3120. assertList = testItem.getElementsByTagName("ol")[0];
  3121. good = details.passed;
  3122. bad = details.failed;
  3123. // This test passed if it has no unexpected failed assertions
  3124. var testPassed = details.failed > 0 ? details.todo : !details.todo;
  3125. if (testPassed) {
  3126. // Collapse the passing tests
  3127. addClass(assertList, "qunit-collapsed");
  3128. } else if (config.collapse) {
  3129. if (!collapseNext) {
  3130. // Skip collapsing the first failing test
  3131. collapseNext = true;
  3132. } else {
  3133. // Collapse remaining tests
  3134. addClass(assertList, "qunit-collapsed");
  3135. }
  3136. }
  3137. // The testItem.firstChild is the test name
  3138. testTitle = testItem.firstChild;
  3139. testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : "";
  3140. testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>";
  3141. if (details.skipped) {
  3142. stats.skippedTests++;
  3143. testItem.className = "skipped";
  3144. skipped = document$$1.createElement("em");
  3145. skipped.className = "qunit-skipped-label";
  3146. skipped.innerHTML = "skipped";
  3147. testItem.insertBefore(skipped, testTitle);
  3148. } else {
  3149. addEvent(testTitle, "click", function () {
  3150. toggleClass(assertList, "qunit-collapsed");
  3151. });
  3152. testItem.className = testPassed ? "pass" : "fail";
  3153. if (details.todo) {
  3154. var todoLabel = document$$1.createElement("em");
  3155. todoLabel.className = "qunit-todo-label";
  3156. todoLabel.innerHTML = "todo";
  3157. testItem.className += " todo";
  3158. testItem.insertBefore(todoLabel, testTitle);
  3159. }
  3160. time = document$$1.createElement("span");
  3161. time.className = "runtime";
  3162. time.innerHTML = details.runtime + " ms";
  3163. testItem.insertBefore(time, assertList);
  3164. if (!testPassed) {
  3165. stats.failedTests++;
  3166. } else if (details.todo) {
  3167. stats.todoTests++;
  3168. } else {
  3169. stats.passedTests++;
  3170. }
  3171. }
  3172. // Show the source of the test when showing assertions
  3173. if (details.source) {
  3174. sourceName = document$$1.createElement("p");
  3175. sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
  3176. addClass(sourceName, "qunit-source");
  3177. if (testPassed) {
  3178. addClass(sourceName, "qunit-collapsed");
  3179. }
  3180. addEvent(testTitle, "click", function () {
  3181. toggleClass(sourceName, "qunit-collapsed");
  3182. });
  3183. testItem.appendChild(sourceName);
  3184. }
  3185. });
  3186. // Avoid readyState issue with phantomjs
  3187. // Ref: #818
  3188. var notPhantom = function (p) {
  3189. return !(p && p.version && p.version.major > 0);
  3190. }(window.phantom);
  3191. if (notPhantom && document$$1.readyState === "complete") {
  3192. QUnit.load();
  3193. } else {
  3194. addEvent(window, "load", QUnit.load);
  3195. }
  3196. // Wrap window.onerror. We will call the original window.onerror to see if
  3197. // the existing handler fully handles the error; if not, we will call the
  3198. // QUnit.onError function.
  3199. var originalWindowOnError = window.onerror;
  3200. // Cover uncaught exceptions
  3201. // Returning true will suppress the default browser handler,
  3202. // returning false will let it run.
  3203. window.onerror = function (message, fileName, lineNumber) {
  3204. var ret = false;
  3205. if (originalWindowOnError) {
  3206. for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  3207. args[_key - 3] = arguments[_key];
  3208. }
  3209. ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber].concat(args));
  3210. }
  3211. // Treat return value as window.onerror itself does,
  3212. // Only do our handling if not suppressed.
  3213. if (ret !== true) {
  3214. var error = {
  3215. message: message,
  3216. fileName: fileName,
  3217. lineNumber: lineNumber
  3218. };
  3219. ret = QUnit.onError(error);
  3220. }
  3221. return ret;
  3222. };
  3223. })();
  3224. /*
  3225. * This file is a modified version of google-diff-match-patch's JavaScript implementation
  3226. * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
  3227. * modifications are licensed as more fully set forth in LICENSE.txt.
  3228. *
  3229. * The original source of google-diff-match-patch is attributable and licensed as follows:
  3230. *
  3231. * Copyright 2006 Google Inc.
  3232. * https://code.google.com/p/google-diff-match-patch/
  3233. *
  3234. * Licensed under the Apache License, Version 2.0 (the "License");
  3235. * you may not use this file except in compliance with the License.
  3236. * You may obtain a copy of the License at
  3237. *
  3238. * https://www.apache.org/licenses/LICENSE-2.0
  3239. *
  3240. * Unless required by applicable law or agreed to in writing, software
  3241. * distributed under the License is distributed on an "AS IS" BASIS,
  3242. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3243. * See the License for the specific language governing permissions and
  3244. * limitations under the License.
  3245. *
  3246. * More Info:
  3247. * https://code.google.com/p/google-diff-match-patch/
  3248. *
  3249. * Usage: QUnit.diff(expected, actual)
  3250. *
  3251. */
  3252. QUnit.diff = function () {
  3253. function DiffMatchPatch() {}
  3254. // DIFF FUNCTIONS
  3255. /**
  3256. * The data structure representing a diff is an array of tuples:
  3257. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  3258. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  3259. */
  3260. var DIFF_DELETE = -1,
  3261. DIFF_INSERT = 1,
  3262. DIFF_EQUAL = 0;
  3263. /**
  3264. * Find the differences between two texts. Simplifies the problem by stripping
  3265. * any common prefix or suffix off the texts before diffing.
  3266. * @param {string} text1 Old string to be diffed.
  3267. * @param {string} text2 New string to be diffed.
  3268. * @param {boolean=} optChecklines Optional speedup flag. If present and false,
  3269. * then don't run a line-level diff first to identify the changed areas.
  3270. * Defaults to true, which does a faster, slightly less optimal diff.
  3271. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3272. */
  3273. DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
  3274. var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs;
  3275. // The diff must be complete in up to 1 second.
  3276. deadline = new Date().getTime() + 1000;
  3277. // Check for null inputs.
  3278. if (text1 === null || text2 === null) {
  3279. throw new Error("Null input. (DiffMain)");
  3280. }
  3281. // Check for equality (speedup).
  3282. if (text1 === text2) {
  3283. if (text1) {
  3284. return [[DIFF_EQUAL, text1]];
  3285. }
  3286. return [];
  3287. }
  3288. if (typeof optChecklines === "undefined") {
  3289. optChecklines = true;
  3290. }
  3291. checklines = optChecklines;
  3292. // Trim off common prefix (speedup).
  3293. commonlength = this.diffCommonPrefix(text1, text2);
  3294. commonprefix = text1.substring(0, commonlength);
  3295. text1 = text1.substring(commonlength);
  3296. text2 = text2.substring(commonlength);
  3297. // Trim off common suffix (speedup).
  3298. commonlength = this.diffCommonSuffix(text1, text2);
  3299. commonsuffix = text1.substring(text1.length - commonlength);
  3300. text1 = text1.substring(0, text1.length - commonlength);
  3301. text2 = text2.substring(0, text2.length - commonlength);
  3302. // Compute the diff on the middle block.
  3303. diffs = this.diffCompute(text1, text2, checklines, deadline);
  3304. // Restore the prefix and suffix.
  3305. if (commonprefix) {
  3306. diffs.unshift([DIFF_EQUAL, commonprefix]);
  3307. }
  3308. if (commonsuffix) {
  3309. diffs.push([DIFF_EQUAL, commonsuffix]);
  3310. }
  3311. this.diffCleanupMerge(diffs);
  3312. return diffs;
  3313. };
  3314. /**
  3315. * Reduce the number of edits by eliminating operationally trivial equalities.
  3316. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3317. */
  3318. DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
  3319. var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel;
  3320. changes = false;
  3321. equalities = []; // Stack of indices where equalities are found.
  3322. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3323. /** @type {?string} */
  3324. lastequality = null;
  3325. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3326. pointer = 0; // Index of current position.
  3327. // Is there an insertion operation before the last equality.
  3328. preIns = false;
  3329. // Is there a deletion operation before the last equality.
  3330. preDel = false;
  3331. // Is there an insertion operation after the last equality.
  3332. postIns = false;
  3333. // Is there a deletion operation after the last equality.
  3334. postDel = false;
  3335. while (pointer < diffs.length) {
  3336. // Equality found.
  3337. if (diffs[pointer][0] === DIFF_EQUAL) {
  3338. if (diffs[pointer][1].length < 4 && (postIns || postDel)) {
  3339. // Candidate found.
  3340. equalities[equalitiesLength++] = pointer;
  3341. preIns = postIns;
  3342. preDel = postDel;
  3343. lastequality = diffs[pointer][1];
  3344. } else {
  3345. // Not a candidate, and can never become one.
  3346. equalitiesLength = 0;
  3347. lastequality = null;
  3348. }
  3349. postIns = postDel = false;
  3350. // An insertion or deletion.
  3351. } else {
  3352. if (diffs[pointer][0] === DIFF_DELETE) {
  3353. postDel = true;
  3354. } else {
  3355. postIns = true;
  3356. }
  3357. /*
  3358. * Five types to be split:
  3359. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  3360. * <ins>A</ins>X<ins>C</ins><del>D</del>
  3361. * <ins>A</ins><del>B</del>X<ins>C</ins>
  3362. * <ins>A</del>X<ins>C</ins><del>D</del>
  3363. * <ins>A</ins><del>B</del>X<del>C</del>
  3364. */
  3365. if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) {
  3366. // Duplicate record.
  3367. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3368. // Change second copy to insert.
  3369. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3370. equalitiesLength--; // Throw away the equality we just deleted;
  3371. lastequality = null;
  3372. if (preIns && preDel) {
  3373. // No changes made which could affect previous entry, keep going.
  3374. postIns = postDel = true;
  3375. equalitiesLength = 0;
  3376. } else {
  3377. equalitiesLength--; // Throw away the previous equality.
  3378. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3379. postIns = postDel = false;
  3380. }
  3381. changes = true;
  3382. }
  3383. }
  3384. pointer++;
  3385. }
  3386. if (changes) {
  3387. this.diffCleanupMerge(diffs);
  3388. }
  3389. };
  3390. /**
  3391. * Convert a diff array into a pretty HTML report.
  3392. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3393. * @param {integer} string to be beautified.
  3394. * @return {string} HTML representation.
  3395. */
  3396. DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
  3397. var op,
  3398. data,
  3399. x,
  3400. html = [];
  3401. for (x = 0; x < diffs.length; x++) {
  3402. op = diffs[x][0]; // Operation (insert, delete, equal)
  3403. data = diffs[x][1]; // Text of change.
  3404. switch (op) {
  3405. case DIFF_INSERT:
  3406. html[x] = "<ins>" + escapeText(data) + "</ins>";
  3407. break;
  3408. case DIFF_DELETE:
  3409. html[x] = "<del>" + escapeText(data) + "</del>";
  3410. break;
  3411. case DIFF_EQUAL:
  3412. html[x] = "<span>" + escapeText(data) + "</span>";
  3413. break;
  3414. }
  3415. }
  3416. return html.join("");
  3417. };
  3418. /**
  3419. * Determine the common prefix of two strings.
  3420. * @param {string} text1 First string.
  3421. * @param {string} text2 Second string.
  3422. * @return {number} The number of characters common to the start of each
  3423. * string.
  3424. */
  3425. DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
  3426. var pointermid, pointermax, pointermin, pointerstart;
  3427. // Quick check for common null cases.
  3428. if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
  3429. return 0;
  3430. }
  3431. // Binary search.
  3432. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3433. pointermin = 0;
  3434. pointermax = Math.min(text1.length, text2.length);
  3435. pointermid = pointermax;
  3436. pointerstart = 0;
  3437. while (pointermin < pointermid) {
  3438. if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) {
  3439. pointermin = pointermid;
  3440. pointerstart = pointermin;
  3441. } else {
  3442. pointermax = pointermid;
  3443. }
  3444. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3445. }
  3446. return pointermid;
  3447. };
  3448. /**
  3449. * Determine the common suffix of two strings.
  3450. * @param {string} text1 First string.
  3451. * @param {string} text2 Second string.
  3452. * @return {number} The number of characters common to the end of each string.
  3453. */
  3454. DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
  3455. var pointermid, pointermax, pointermin, pointerend;
  3456. // Quick check for common null cases.
  3457. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
  3458. return 0;
  3459. }
  3460. // Binary search.
  3461. // Performance analysis: https://neil.fraser.name/news/2007/10/09/
  3462. pointermin = 0;
  3463. pointermax = Math.min(text1.length, text2.length);
  3464. pointermid = pointermax;
  3465. pointerend = 0;
  3466. while (pointermin < pointermid) {
  3467. if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) {
  3468. pointermin = pointermid;
  3469. pointerend = pointermin;
  3470. } else {
  3471. pointermax = pointermid;
  3472. }
  3473. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
  3474. }
  3475. return pointermid;
  3476. };
  3477. /**
  3478. * Find the differences between two texts. Assumes that the texts do not
  3479. * have any common prefix or suffix.
  3480. * @param {string} text1 Old string to be diffed.
  3481. * @param {string} text2 New string to be diffed.
  3482. * @param {boolean} checklines Speedup flag. If false, then don't run a
  3483. * line-level diff first to identify the changed areas.
  3484. * If true, then run a faster, slightly less optimal diff.
  3485. * @param {number} deadline Time when the diff should be complete by.
  3486. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3487. * @private
  3488. */
  3489. DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
  3490. var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB;
  3491. if (!text1) {
  3492. // Just add some text (speedup).
  3493. return [[DIFF_INSERT, text2]];
  3494. }
  3495. if (!text2) {
  3496. // Just delete some text (speedup).
  3497. return [[DIFF_DELETE, text1]];
  3498. }
  3499. longtext = text1.length > text2.length ? text1 : text2;
  3500. shorttext = text1.length > text2.length ? text2 : text1;
  3501. i = longtext.indexOf(shorttext);
  3502. if (i !== -1) {
  3503. // Shorter text is inside the longer text (speedup).
  3504. diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
  3505. // Swap insertions for deletions if diff is reversed.
  3506. if (text1.length > text2.length) {
  3507. diffs[0][0] = diffs[2][0] = DIFF_DELETE;
  3508. }
  3509. return diffs;
  3510. }
  3511. if (shorttext.length === 1) {
  3512. // Single character string.
  3513. // After the previous speedup, the character can't be an equality.
  3514. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3515. }
  3516. // Check to see if the problem can be split in two.
  3517. hm = this.diffHalfMatch(text1, text2);
  3518. if (hm) {
  3519. // A half-match was found, sort out the return data.
  3520. text1A = hm[0];
  3521. text1B = hm[1];
  3522. text2A = hm[2];
  3523. text2B = hm[3];
  3524. midCommon = hm[4];
  3525. // Send both pairs off for separate processing.
  3526. diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
  3527. diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
  3528. // Merge the results.
  3529. return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
  3530. }
  3531. if (checklines && text1.length > 100 && text2.length > 100) {
  3532. return this.diffLineMode(text1, text2, deadline);
  3533. }
  3534. return this.diffBisect(text1, text2, deadline);
  3535. };
  3536. /**
  3537. * Do the two texts share a substring which is at least half the length of the
  3538. * longer text?
  3539. * This speedup can produce non-minimal diffs.
  3540. * @param {string} text1 First string.
  3541. * @param {string} text2 Second string.
  3542. * @return {Array.<string>} Five element Array, containing the prefix of
  3543. * text1, the suffix of text1, the prefix of text2, the suffix of
  3544. * text2 and the common middle. Or null if there was no match.
  3545. * @private
  3546. */
  3547. DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
  3548. var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm;
  3549. longtext = text1.length > text2.length ? text1 : text2;
  3550. shorttext = text1.length > text2.length ? text2 : text1;
  3551. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  3552. return null; // Pointless.
  3553. }
  3554. dmp = this; // 'this' becomes 'window' in a closure.
  3555. /**
  3556. * Does a substring of shorttext exist within longtext such that the substring
  3557. * is at least half the length of longtext?
  3558. * Closure, but does not reference any external variables.
  3559. * @param {string} longtext Longer string.
  3560. * @param {string} shorttext Shorter string.
  3561. * @param {number} i Start index of quarter length substring within longtext.
  3562. * @return {Array.<string>} Five element Array, containing the prefix of
  3563. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  3564. * of shorttext and the common middle. Or null if there was no match.
  3565. * @private
  3566. */
  3567. function diffHalfMatchI(longtext, shorttext, i) {
  3568. var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
  3569. // Start with a 1/4 length substring at position i as a seed.
  3570. seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
  3571. j = -1;
  3572. bestCommon = "";
  3573. while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
  3574. prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j));
  3575. suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j));
  3576. if (bestCommon.length < suffixLength + prefixLength) {
  3577. bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
  3578. bestLongtextA = longtext.substring(0, i - suffixLength);
  3579. bestLongtextB = longtext.substring(i + prefixLength);
  3580. bestShorttextA = shorttext.substring(0, j - suffixLength);
  3581. bestShorttextB = shorttext.substring(j + prefixLength);
  3582. }
  3583. }
  3584. if (bestCommon.length * 2 >= longtext.length) {
  3585. return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon];
  3586. } else {
  3587. return null;
  3588. }
  3589. }
  3590. // First check if the second quarter is the seed for a half-match.
  3591. hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4));
  3592. // Check again based on the third quarter.
  3593. hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2));
  3594. if (!hm1 && !hm2) {
  3595. return null;
  3596. } else if (!hm2) {
  3597. hm = hm1;
  3598. } else if (!hm1) {
  3599. hm = hm2;
  3600. } else {
  3601. // Both matched. Select the longest.
  3602. hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
  3603. }
  3604. // A half-match was found, sort out the return data.
  3605. if (text1.length > text2.length) {
  3606. text1A = hm[0];
  3607. text1B = hm[1];
  3608. text2A = hm[2];
  3609. text2B = hm[3];
  3610. } else {
  3611. text2A = hm[0];
  3612. text2B = hm[1];
  3613. text1A = hm[2];
  3614. text1B = hm[3];
  3615. }
  3616. midCommon = hm[4];
  3617. return [text1A, text1B, text2A, text2B, midCommon];
  3618. };
  3619. /**
  3620. * Do a quick line-level diff on both strings, then rediff the parts for
  3621. * greater accuracy.
  3622. * This speedup can produce non-minimal diffs.
  3623. * @param {string} text1 Old string to be diffed.
  3624. * @param {string} text2 New string to be diffed.
  3625. * @param {number} deadline Time when the diff should be complete by.
  3626. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3627. * @private
  3628. */
  3629. DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
  3630. var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j;
  3631. // Scan the text on a line-by-line basis first.
  3632. a = this.diffLinesToChars(text1, text2);
  3633. text1 = a.chars1;
  3634. text2 = a.chars2;
  3635. linearray = a.lineArray;
  3636. diffs = this.DiffMain(text1, text2, false, deadline);
  3637. // Convert the diff back to original text.
  3638. this.diffCharsToLines(diffs, linearray);
  3639. // Eliminate freak matches (e.g. blank lines)
  3640. this.diffCleanupSemantic(diffs);
  3641. // Rediff any replacement blocks, this time character-by-character.
  3642. // Add a dummy entry at the end.
  3643. diffs.push([DIFF_EQUAL, ""]);
  3644. pointer = 0;
  3645. countDelete = 0;
  3646. countInsert = 0;
  3647. textDelete = "";
  3648. textInsert = "";
  3649. while (pointer < diffs.length) {
  3650. switch (diffs[pointer][0]) {
  3651. case DIFF_INSERT:
  3652. countInsert++;
  3653. textInsert += diffs[pointer][1];
  3654. break;
  3655. case DIFF_DELETE:
  3656. countDelete++;
  3657. textDelete += diffs[pointer][1];
  3658. break;
  3659. case DIFF_EQUAL:
  3660. // Upon reaching an equality, check for prior redundancies.
  3661. if (countDelete >= 1 && countInsert >= 1) {
  3662. // Delete the offending records and add the merged ones.
  3663. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);
  3664. pointer = pointer - countDelete - countInsert;
  3665. a = this.DiffMain(textDelete, textInsert, false, deadline);
  3666. for (j = a.length - 1; j >= 0; j--) {
  3667. diffs.splice(pointer, 0, a[j]);
  3668. }
  3669. pointer = pointer + a.length;
  3670. }
  3671. countInsert = 0;
  3672. countDelete = 0;
  3673. textDelete = "";
  3674. textInsert = "";
  3675. break;
  3676. }
  3677. pointer++;
  3678. }
  3679. diffs.pop(); // Remove the dummy entry at the end.
  3680. return diffs;
  3681. };
  3682. /**
  3683. * Find the 'middle snake' of a diff, split the problem in two
  3684. * and return the recursively constructed diff.
  3685. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  3686. * @param {string} text1 Old string to be diffed.
  3687. * @param {string} text2 New string to be diffed.
  3688. * @param {number} deadline Time at which to bail if not yet complete.
  3689. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3690. * @private
  3691. */
  3692. DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
  3693. var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
  3694. // Cache the text lengths to prevent multiple calls.
  3695. text1Length = text1.length;
  3696. text2Length = text2.length;
  3697. maxD = Math.ceil((text1Length + text2Length) / 2);
  3698. vOffset = maxD;
  3699. vLength = 2 * maxD;
  3700. v1 = new Array(vLength);
  3701. v2 = new Array(vLength);
  3702. // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  3703. // integers and undefined.
  3704. for (x = 0; x < vLength; x++) {
  3705. v1[x] = -1;
  3706. v2[x] = -1;
  3707. }
  3708. v1[vOffset + 1] = 0;
  3709. v2[vOffset + 1] = 0;
  3710. delta = text1Length - text2Length;
  3711. // If the total number of characters is odd, then the front path will collide
  3712. // with the reverse path.
  3713. front = delta % 2 !== 0;
  3714. // Offsets for start and end of k loop.
  3715. // Prevents mapping of space beyond the grid.
  3716. k1start = 0;
  3717. k1end = 0;
  3718. k2start = 0;
  3719. k2end = 0;
  3720. for (d = 0; d < maxD; d++) {
  3721. // Bail out if deadline is reached.
  3722. if (new Date().getTime() > deadline) {
  3723. break;
  3724. }
  3725. // Walk the front path one step.
  3726. for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  3727. k1Offset = vOffset + k1;
  3728. if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {
  3729. x1 = v1[k1Offset + 1];
  3730. } else {
  3731. x1 = v1[k1Offset - 1] + 1;
  3732. }
  3733. y1 = x1 - k1;
  3734. while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {
  3735. x1++;
  3736. y1++;
  3737. }
  3738. v1[k1Offset] = x1;
  3739. if (x1 > text1Length) {
  3740. // Ran off the right of the graph.
  3741. k1end += 2;
  3742. } else if (y1 > text2Length) {
  3743. // Ran off the bottom of the graph.
  3744. k1start += 2;
  3745. } else if (front) {
  3746. k2Offset = vOffset + delta - k1;
  3747. if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
  3748. // Mirror x2 onto top-left coordinate system.
  3749. x2 = text1Length - v2[k2Offset];
  3750. if (x1 >= x2) {
  3751. // Overlap detected.
  3752. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3753. }
  3754. }
  3755. }
  3756. }
  3757. // Walk the reverse path one step.
  3758. for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  3759. k2Offset = vOffset + k2;
  3760. if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {
  3761. x2 = v2[k2Offset + 1];
  3762. } else {
  3763. x2 = v2[k2Offset - 1] + 1;
  3764. }
  3765. y2 = x2 - k2;
  3766. while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {
  3767. x2++;
  3768. y2++;
  3769. }
  3770. v2[k2Offset] = x2;
  3771. if (x2 > text1Length) {
  3772. // Ran off the left of the graph.
  3773. k2end += 2;
  3774. } else if (y2 > text2Length) {
  3775. // Ran off the top of the graph.
  3776. k2start += 2;
  3777. } else if (!front) {
  3778. k1Offset = vOffset + delta - k2;
  3779. if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
  3780. x1 = v1[k1Offset];
  3781. y1 = vOffset + x1 - k1Offset;
  3782. // Mirror x2 onto top-left coordinate system.
  3783. x2 = text1Length - x2;
  3784. if (x1 >= x2) {
  3785. // Overlap detected.
  3786. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  3787. }
  3788. }
  3789. }
  3790. }
  3791. }
  3792. // Diff took too long and hit the deadline or
  3793. // number of diffs equals number of characters, no commonality at all.
  3794. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
  3795. };
  3796. /**
  3797. * Given the location of the 'middle snake', split the diff in two parts
  3798. * and recurse.
  3799. * @param {string} text1 Old string to be diffed.
  3800. * @param {string} text2 New string to be diffed.
  3801. * @param {number} x Index of split point in text1.
  3802. * @param {number} y Index of split point in text2.
  3803. * @param {number} deadline Time at which to bail if not yet complete.
  3804. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  3805. * @private
  3806. */
  3807. DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
  3808. var text1a, text1b, text2a, text2b, diffs, diffsb;
  3809. text1a = text1.substring(0, x);
  3810. text2a = text2.substring(0, y);
  3811. text1b = text1.substring(x);
  3812. text2b = text2.substring(y);
  3813. // Compute both diffs serially.
  3814. diffs = this.DiffMain(text1a, text2a, false, deadline);
  3815. diffsb = this.DiffMain(text1b, text2b, false, deadline);
  3816. return diffs.concat(diffsb);
  3817. };
  3818. /**
  3819. * Reduce the number of edits by eliminating semantically trivial equalities.
  3820. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  3821. */
  3822. DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
  3823. var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
  3824. changes = false;
  3825. equalities = []; // Stack of indices where equalities are found.
  3826. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  3827. /** @type {?string} */
  3828. lastequality = null;
  3829. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  3830. pointer = 0; // Index of current position.
  3831. // Number of characters that changed prior to the equality.
  3832. lengthInsertions1 = 0;
  3833. lengthDeletions1 = 0;
  3834. // Number of characters that changed after the equality.
  3835. lengthInsertions2 = 0;
  3836. lengthDeletions2 = 0;
  3837. while (pointer < diffs.length) {
  3838. if (diffs[pointer][0] === DIFF_EQUAL) {
  3839. // Equality found.
  3840. equalities[equalitiesLength++] = pointer;
  3841. lengthInsertions1 = lengthInsertions2;
  3842. lengthDeletions1 = lengthDeletions2;
  3843. lengthInsertions2 = 0;
  3844. lengthDeletions2 = 0;
  3845. lastequality = diffs[pointer][1];
  3846. } else {
  3847. // An insertion or deletion.
  3848. if (diffs[pointer][0] === DIFF_INSERT) {
  3849. lengthInsertions2 += diffs[pointer][1].length;
  3850. } else {
  3851. lengthDeletions2 += diffs[pointer][1].length;
  3852. }
  3853. // Eliminate an equality that is smaller or equal to the edits on both
  3854. // sides of it.
  3855. if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {
  3856. // Duplicate record.
  3857. diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]);
  3858. // Change second copy to insert.
  3859. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  3860. // Throw away the equality we just deleted.
  3861. equalitiesLength--;
  3862. // Throw away the previous equality (it needs to be reevaluated).
  3863. equalitiesLength--;
  3864. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  3865. // Reset the counters.
  3866. lengthInsertions1 = 0;
  3867. lengthDeletions1 = 0;
  3868. lengthInsertions2 = 0;
  3869. lengthDeletions2 = 0;
  3870. lastequality = null;
  3871. changes = true;
  3872. }
  3873. }
  3874. pointer++;
  3875. }
  3876. // Normalize the diff.
  3877. if (changes) {
  3878. this.diffCleanupMerge(diffs);
  3879. }
  3880. // Find any overlaps between deletions and insertions.
  3881. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  3882. // -> <del>abc</del>xxx<ins>def</ins>
  3883. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  3884. // -> <ins>def</ins>xxx<del>abc</del>
  3885. // Only extract an overlap if it is as big as the edit ahead or behind it.
  3886. pointer = 1;
  3887. while (pointer < diffs.length) {
  3888. if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
  3889. deletion = diffs[pointer - 1][1];
  3890. insertion = diffs[pointer][1];
  3891. overlapLength1 = this.diffCommonOverlap(deletion, insertion);
  3892. overlapLength2 = this.diffCommonOverlap(insertion, deletion);
  3893. if (overlapLength1 >= overlapLength2) {
  3894. if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {
  3895. // Overlap found. Insert an equality and trim the surrounding edits.
  3896. diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);
  3897. diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);
  3898. diffs[pointer + 1][1] = insertion.substring(overlapLength1);
  3899. pointer++;
  3900. }
  3901. } else {
  3902. if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {
  3903. // Reverse overlap found.
  3904. // Insert an equality and swap and trim the surrounding edits.
  3905. diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);
  3906. diffs[pointer - 1][0] = DIFF_INSERT;
  3907. diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);
  3908. diffs[pointer + 1][0] = DIFF_DELETE;
  3909. diffs[pointer + 1][1] = deletion.substring(overlapLength2);
  3910. pointer++;
  3911. }
  3912. }
  3913. pointer++;
  3914. }
  3915. pointer++;
  3916. }
  3917. };
  3918. /**
  3919. * Determine if the suffix of one string is the prefix of another.
  3920. * @param {string} text1 First string.
  3921. * @param {string} text2 Second string.
  3922. * @return {number} The number of characters common to the end of the first
  3923. * string and the start of the second string.
  3924. * @private
  3925. */
  3926. DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
  3927. var text1Length, text2Length, textLength, best, length, pattern, found;
  3928. // Cache the text lengths to prevent multiple calls.
  3929. text1Length = text1.length;
  3930. text2Length = text2.length;
  3931. // Eliminate the null case.
  3932. if (text1Length === 0 || text2Length === 0) {
  3933. return 0;
  3934. }
  3935. // Truncate the longer string.
  3936. if (text1Length > text2Length) {
  3937. text1 = text1.substring(text1Length - text2Length);
  3938. } else if (text1Length < text2Length) {
  3939. text2 = text2.substring(0, text1Length);
  3940. }
  3941. textLength = Math.min(text1Length, text2Length);
  3942. // Quick check for the worst case.
  3943. if (text1 === text2) {
  3944. return textLength;
  3945. }
  3946. // Start by looking for a single character match
  3947. // and increase length until no match is found.
  3948. // Performance analysis: https://neil.fraser.name/news/2010/11/04/
  3949. best = 0;
  3950. length = 1;
  3951. while (true) {
  3952. pattern = text1.substring(textLength - length);
  3953. found = text2.indexOf(pattern);
  3954. if (found === -1) {
  3955. return best;
  3956. }
  3957. length += found;
  3958. if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {
  3959. best = length;
  3960. length++;
  3961. }
  3962. }
  3963. };
  3964. /**
  3965. * Split two texts into an array of strings. Reduce the texts to a string of
  3966. * hashes where each Unicode character represents one line.
  3967. * @param {string} text1 First string.
  3968. * @param {string} text2 Second string.
  3969. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  3970. * An object containing the encoded text1, the encoded text2 and
  3971. * the array of unique strings.
  3972. * The zeroth element of the array of unique strings is intentionally blank.
  3973. * @private
  3974. */
  3975. DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
  3976. var lineArray, lineHash, chars1, chars2;
  3977. lineArray = []; // E.g. lineArray[4] === 'Hello\n'
  3978. lineHash = {}; // E.g. lineHash['Hello\n'] === 4
  3979. // '\x00' is a valid character, but various debuggers don't like it.
  3980. // So we'll insert a junk entry to avoid generating a null character.
  3981. lineArray[0] = "";
  3982. /**
  3983. * Split a text into an array of strings. Reduce the texts to a string of
  3984. * hashes where each Unicode character represents one line.
  3985. * Modifies linearray and linehash through being a closure.
  3986. * @param {string} text String to encode.
  3987. * @return {string} Encoded string.
  3988. * @private
  3989. */
  3990. function diffLinesToCharsMunge(text) {
  3991. var chars, lineStart, lineEnd, lineArrayLength, line;
  3992. chars = "";
  3993. // Walk the text, pulling out a substring for each line.
  3994. // text.split('\n') would would temporarily double our memory footprint.
  3995. // Modifying text would create many large strings to garbage collect.
  3996. lineStart = 0;
  3997. lineEnd = -1;
  3998. // Keeping our own length variable is faster than looking it up.
  3999. lineArrayLength = lineArray.length;
  4000. while (lineEnd < text.length - 1) {
  4001. lineEnd = text.indexOf("\n", lineStart);
  4002. if (lineEnd === -1) {
  4003. lineEnd = text.length - 1;
  4004. }
  4005. line = text.substring(lineStart, lineEnd + 1);
  4006. lineStart = lineEnd + 1;
  4007. if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined) {
  4008. chars += String.fromCharCode(lineHash[line]);
  4009. } else {
  4010. chars += String.fromCharCode(lineArrayLength);
  4011. lineHash[line] = lineArrayLength;
  4012. lineArray[lineArrayLength++] = line;
  4013. }
  4014. }
  4015. return chars;
  4016. }
  4017. chars1 = diffLinesToCharsMunge(text1);
  4018. chars2 = diffLinesToCharsMunge(text2);
  4019. return {
  4020. chars1: chars1,
  4021. chars2: chars2,
  4022. lineArray: lineArray
  4023. };
  4024. };
  4025. /**
  4026. * Rehydrate the text in a diff from a string of line hashes to real lines of
  4027. * text.
  4028. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4029. * @param {!Array.<string>} lineArray Array of unique strings.
  4030. * @private
  4031. */
  4032. DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
  4033. var x, chars, text, y;
  4034. for (x = 0; x < diffs.length; x++) {
  4035. chars = diffs[x][1];
  4036. text = [];
  4037. for (y = 0; y < chars.length; y++) {
  4038. text[y] = lineArray[chars.charCodeAt(y)];
  4039. }
  4040. diffs[x][1] = text.join("");
  4041. }
  4042. };
  4043. /**
  4044. * Reorder and merge like edit sections. Merge equalities.
  4045. * Any edit section can move as long as it doesn't cross an equality.
  4046. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  4047. */
  4048. DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
  4049. var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position;
  4050. diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
  4051. pointer = 0;
  4052. countDelete = 0;
  4053. countInsert = 0;
  4054. textDelete = "";
  4055. textInsert = "";
  4056. while (pointer < diffs.length) {
  4057. switch (diffs[pointer][0]) {
  4058. case DIFF_INSERT:
  4059. countInsert++;
  4060. textInsert += diffs[pointer][1];
  4061. pointer++;
  4062. break;
  4063. case DIFF_DELETE:
  4064. countDelete++;
  4065. textDelete += diffs[pointer][1];
  4066. pointer++;
  4067. break;
  4068. case DIFF_EQUAL:
  4069. // Upon reaching an equality, check for prior redundancies.
  4070. if (countDelete + countInsert > 1) {
  4071. if (countDelete !== 0 && countInsert !== 0) {
  4072. // Factor out any common prefixes.
  4073. commonlength = this.diffCommonPrefix(textInsert, textDelete);
  4074. if (commonlength !== 0) {
  4075. if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {
  4076. diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);
  4077. } else {
  4078. diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);
  4079. pointer++;
  4080. }
  4081. textInsert = textInsert.substring(commonlength);
  4082. textDelete = textDelete.substring(commonlength);
  4083. }
  4084. // Factor out any common suffixies.
  4085. commonlength = this.diffCommonSuffix(textInsert, textDelete);
  4086. if (commonlength !== 0) {
  4087. diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];
  4088. textInsert = textInsert.substring(0, textInsert.length - commonlength);
  4089. textDelete = textDelete.substring(0, textDelete.length - commonlength);
  4090. }
  4091. }
  4092. // Delete the offending records and add the merged ones.
  4093. if (countDelete === 0) {
  4094. diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]);
  4095. } else if (countInsert === 0) {
  4096. diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]);
  4097. } else {
  4098. diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]);
  4099. }
  4100. pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
  4101. } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
  4102. // Merge this equality with the previous one.
  4103. diffs[pointer - 1][1] += diffs[pointer][1];
  4104. diffs.splice(pointer, 1);
  4105. } else {
  4106. pointer++;
  4107. }
  4108. countInsert = 0;
  4109. countDelete = 0;
  4110. textDelete = "";
  4111. textInsert = "";
  4112. break;
  4113. }
  4114. }
  4115. if (diffs[diffs.length - 1][1] === "") {
  4116. diffs.pop(); // Remove the dummy entry at the end.
  4117. }
  4118. // Second pass: look for single edits surrounded on both sides by equalities
  4119. // which can be shifted sideways to eliminate an equality.
  4120. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  4121. changes = false;
  4122. pointer = 1;
  4123. // Intentionally ignore the first and last element (don't need checking).
  4124. while (pointer < diffs.length - 1) {
  4125. if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
  4126. diffPointer = diffs[pointer][1];
  4127. position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length);
  4128. // This is a single edit surrounded by equalities.
  4129. if (position === diffs[pointer - 1][1]) {
  4130. // Shift the edit over the previous equality.
  4131. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);
  4132. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
  4133. diffs.splice(pointer - 1, 1);
  4134. changes = true;
  4135. } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {
  4136. // Shift the edit over the next equality.
  4137. diffs[pointer - 1][1] += diffs[pointer + 1][1];
  4138. diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];
  4139. diffs.splice(pointer + 1, 1);
  4140. changes = true;
  4141. }
  4142. }
  4143. pointer++;
  4144. }
  4145. // If shifts were made, the diff needs reordering and another shift sweep.
  4146. if (changes) {
  4147. this.diffCleanupMerge(diffs);
  4148. }
  4149. };
  4150. return function (o, n) {
  4151. var diff, output, text;
  4152. diff = new DiffMatchPatch();
  4153. output = diff.DiffMain(o, n);
  4154. diff.diffCleanupEfficiency(output);
  4155. text = diff.diffPrettyHtml(output);
  4156. return text;
  4157. };
  4158. }();
  4159. }((function() { return this; }())));