qunit-1.23.1.js 112 KB

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