2
0

qunit.js 113 KB

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