qunit-1.18.0.js 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829
  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: 0,
  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é <[email protected]>
  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. return;
  1400. stack.push( obj );
  1401. res = parser.call( this, obj, stack );
  1402. stack.pop();
  1403. return res;
  1404. }
  1405. return ( parserType === "string" ) ? parser : this.parsers.error;
  1406. },
  1407. typeOf: function( obj ) {
  1408. var type;
  1409. if ( obj === null ) {
  1410. type = "null";
  1411. } else if ( typeof obj === "undefined" ) {
  1412. type = "undefined";
  1413. } else if ( QUnit.is( "regexp", obj ) ) {
  1414. type = "regexp";
  1415. } else if ( QUnit.is( "date", obj ) ) {
  1416. type = "date";
  1417. } else if ( QUnit.is( "function", obj ) ) {
  1418. type = "function";
  1419. } else if ( obj.setInterval !== undefined &&
  1420. obj.document !== undefined &&
  1421. obj.nodeType === undefined ) {
  1422. type = "window";
  1423. } else if ( obj.nodeType === 9 ) {
  1424. type = "document";
  1425. } else if ( obj.nodeType ) {
  1426. type = "node";
  1427. } else if (
  1428. // native arrays
  1429. toString.call( obj ) === "[object Array]" ||
  1430. // NodeList objects
  1431. ( typeof obj.length === "number" && obj.item !== undefined &&
  1432. ( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null &&
  1433. obj[ 0 ] === undefined ) ) )
  1434. ) {
  1435. type = "array";
  1436. } else if ( obj.constructor === Error.prototype.constructor ) {
  1437. type = "error";
  1438. } else {
  1439. type = typeof obj;
  1440. }
  1441. return type;
  1442. },
  1443. separator: function() {
  1444. return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? "&#160;" : " ";
  1445. },
  1446. // extra can be a number, shortcut for increasing-calling-decreasing
  1447. indent: function( extra ) {
  1448. if ( !this.multiline ) {
  1449. return "";
  1450. }
  1451. var chr = this.indentChar;
  1452. if ( this.HTML ) {
  1453. chr = chr.replace( /\t/g, " " ).replace( / /g, "&#160;" );
  1454. }
  1455. return new Array( this.depth + ( extra || 0 ) ).join( chr );
  1456. },
  1457. up: function( a ) {
  1458. this.depth += a || 1;
  1459. },
  1460. down: function( a ) {
  1461. this.depth -= a || 1;
  1462. },
  1463. setParser: function( name, parser ) {
  1464. this.parsers[ name ] = parser;
  1465. },
  1466. // The next 3 are exposed so you can use them
  1467. quote: quote,
  1468. literal: literal,
  1469. join: join,
  1470. //
  1471. depth: 1,
  1472. maxDepth: QUnit.config.maxDepth,
  1473. // This is the list of parsers, to modify them, use dump.setParser
  1474. parsers: {
  1475. window: "[Window]",
  1476. document: "[Document]",
  1477. error: function( error ) {
  1478. return "Error(\"" + error.message + "\")";
  1479. },
  1480. unknown: "[Unknown]",
  1481. "null": "null",
  1482. "undefined": "undefined",
  1483. "function": function( fn ) {
  1484. var ret = "function",
  1485. // functions never have name in IE
  1486. name = "name" in fn ? fn.name : ( reName.exec( fn ) || [] )[ 1 ];
  1487. if ( name ) {
  1488. ret += " " + name;
  1489. }
  1490. ret += "( ";
  1491. ret = [ ret, dump.parse( fn, "functionArgs" ), "){" ].join( "" );
  1492. return join( ret, dump.parse( fn, "functionCode" ), "}" );
  1493. },
  1494. array: array,
  1495. nodelist: array,
  1496. "arguments": array,
  1497. object: function( map, stack ) {
  1498. var keys, key, val, i, nonEnumerableProperties,
  1499. ret = [];
  1500. if ( dump.maxDepth && dump.depth > dump.maxDepth ) {
  1501. return "[object Object]";
  1502. }
  1503. dump.up();
  1504. keys = [];
  1505. for ( key in map ) {
  1506. keys.push( key );
  1507. }
  1508. // Some properties are not always enumerable on Error objects.
  1509. nonEnumerableProperties = [ "message", "name" ];
  1510. for ( i in nonEnumerableProperties ) {
  1511. key = nonEnumerableProperties[ i ];
  1512. if ( key in map && inArray( key, keys ) < 0 ) {
  1513. keys.push( key );
  1514. }
  1515. }
  1516. keys.sort();
  1517. for ( i = 0; i < keys.length; i++ ) {
  1518. key = keys[ i ];
  1519. val = map[ key ];
  1520. ret.push( dump.parse( key, "key" ) + ": " +
  1521. dump.parse( val, undefined, stack ) );
  1522. }
  1523. dump.down();
  1524. return join( "{", ret, "}" );
  1525. },
  1526. node: function( node ) {
  1527. var len, i, val,
  1528. open = dump.HTML ? "&lt;" : "<",
  1529. close = dump.HTML ? "&gt;" : ">",
  1530. tag = node.nodeName.toLowerCase(),
  1531. ret = open + tag,
  1532. attrs = node.attributes;
  1533. if ( attrs ) {
  1534. for ( i = 0, len = attrs.length; i < len; i++ ) {
  1535. val = attrs[ i ].nodeValue;
  1536. // IE6 includes all attributes in .attributes, even ones not explicitly
  1537. // set. Those have values like undefined, null, 0, false, "" or
  1538. // "inherit".
  1539. if ( val && val !== "inherit" ) {
  1540. ret += " " + attrs[ i ].nodeName + "=" +
  1541. dump.parse( val, "attribute" );
  1542. }
  1543. }
  1544. }
  1545. ret += close;
  1546. // Show content of TextNode or CDATASection
  1547. if ( node.nodeType === 3 || node.nodeType === 4 ) {
  1548. ret += node.nodeValue;
  1549. }
  1550. return ret + open + "/" + tag + close;
  1551. },
  1552. // function calls it internally, it's the arguments part of the function
  1553. functionArgs: function( fn ) {
  1554. var args,
  1555. l = fn.length;
  1556. if ( !l ) {
  1557. return "";
  1558. }
  1559. args = new Array( l );
  1560. while ( l-- ) {
  1561. // 97 is 'a'
  1562. args[ l ] = String.fromCharCode( 97 + l );
  1563. }
  1564. return " " + args.join( ", " ) + " ";
  1565. },
  1566. // object calls it internally, the key part of an item in a map
  1567. key: quote,
  1568. // function calls it internally, it's the content of the function
  1569. functionCode: "[code]",
  1570. // node calls it internally, it's an html attribute value
  1571. attribute: quote,
  1572. string: quote,
  1573. date: quote,
  1574. regexp: literal,
  1575. number: literal,
  1576. "boolean": literal
  1577. },
  1578. // if true, entities are escaped ( <, >, \t, space and \n )
  1579. HTML: false,
  1580. // indentation unit
  1581. indentChar: " ",
  1582. // if true, items in a collection, are separated by a \n, else just a space.
  1583. multiline: true
  1584. };
  1585. return dump;
  1586. }());
  1587. // back compat
  1588. QUnit.jsDump = QUnit.dump;
  1589. // For browser, export only select globals
  1590. if ( typeof window !== "undefined" ) {
  1591. // Deprecated
  1592. // Extend assert methods to QUnit and Global scope through Backwards compatibility
  1593. (function() {
  1594. var i,
  1595. assertions = Assert.prototype;
  1596. function applyCurrent( current ) {
  1597. return function() {
  1598. var assert = new Assert( QUnit.config.current );
  1599. current.apply( assert, arguments );
  1600. };
  1601. }
  1602. for ( i in assertions ) {
  1603. QUnit[ i ] = applyCurrent( assertions[ i ] );
  1604. }
  1605. })();
  1606. (function() {
  1607. var i, l,
  1608. keys = [
  1609. "test",
  1610. "module",
  1611. "expect",
  1612. "asyncTest",
  1613. "start",
  1614. "stop",
  1615. "ok",
  1616. "notOk",
  1617. "equal",
  1618. "notEqual",
  1619. "propEqual",
  1620. "notPropEqual",
  1621. "deepEqual",
  1622. "notDeepEqual",
  1623. "strictEqual",
  1624. "notStrictEqual",
  1625. "throws"
  1626. ];
  1627. for ( i = 0, l = keys.length; i < l; i++ ) {
  1628. window[ keys[ i ] ] = QUnit[ keys[ i ] ];
  1629. }
  1630. })();
  1631. window.QUnit = QUnit;
  1632. }
  1633. // For nodejs
  1634. if ( typeof module !== "undefined" && module && module.exports ) {
  1635. module.exports = QUnit;
  1636. // For consistency with CommonJS environments' exports
  1637. module.exports.QUnit = QUnit;
  1638. }
  1639. // For CommonJS with exports, but without module.exports, like Rhino
  1640. if ( typeof exports !== "undefined" && exports ) {
  1641. exports.QUnit = QUnit;
  1642. }
  1643. if ( typeof define === "function" && define.amd ) {
  1644. define( function() {
  1645. return QUnit;
  1646. } );
  1647. QUnit.config.autostart = false;
  1648. }
  1649. // Get a reference to the global object, like window in browsers
  1650. }( (function() {
  1651. return this;
  1652. })() ));
  1653. /*istanbul ignore next */
  1654. // jscs:disable maximumLineLength
  1655. /*
  1656. * This file is a modified version of google-diff-match-patch's JavaScript implementation
  1657. * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
  1658. * modifications are licensed as more fully set forth in LICENSE.txt.
  1659. *
  1660. * The original source of google-diff-match-patch is attributable and licensed as follows:
  1661. *
  1662. * Copyright 2006 Google Inc.
  1663. * http://code.google.com/p/google-diff-match-patch/
  1664. *
  1665. * Licensed under the Apache License, Version 2.0 (the "License");
  1666. * you may not use this file except in compliance with the License.
  1667. * You may obtain a copy of the License at
  1668. *
  1669. * http://www.apache.org/licenses/LICENSE-2.0
  1670. *
  1671. * Unless required by applicable law or agreed to in writing, software
  1672. * distributed under the License is distributed on an "AS IS" BASIS,
  1673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1674. * See the License for the specific language governing permissions and
  1675. * limitations under the License.
  1676. *
  1677. * More Info:
  1678. * https://code.google.com/p/google-diff-match-patch/
  1679. *
  1680. * Usage: QUnit.diff(expected, actual)
  1681. *
  1682. * 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"
  1683. */
  1684. QUnit.diff = (function() {
  1685. function DiffMatchPatch() {
  1686. // Defaults.
  1687. // Redefine these in your program to override the defaults.
  1688. // Number of seconds to map a diff before giving up (0 for infinity).
  1689. this.DiffTimeout = 1.0;
  1690. // Cost of an empty edit operation in terms of edit characters.
  1691. this.DiffEditCost = 4;
  1692. }
  1693. // DIFF FUNCTIONS
  1694. /**
  1695. * The data structure representing a diff is an array of tuples:
  1696. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  1697. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  1698. */
  1699. var DIFF_DELETE = -1,
  1700. DIFF_INSERT = 1,
  1701. DIFF_EQUAL = 0;
  1702. /**
  1703. * Find the differences between two texts. Simplifies the problem by stripping
  1704. * any common prefix or suffix off the texts before diffing.
  1705. * @param {string} text1 Old string to be diffed.
  1706. * @param {string} text2 New string to be diffed.
  1707. * @param {boolean=} optChecklines Optional speedup flag. If present and false,
  1708. * then don't run a line-level diff first to identify the changed areas.
  1709. * Defaults to true, which does a faster, slightly less optimal diff.
  1710. * @param {number} optDeadline Optional time when the diff should be complete
  1711. * by. Used internally for recursive calls. Users should set DiffTimeout
  1712. * instead.
  1713. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  1714. */
  1715. DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines, optDeadline ) {
  1716. var deadline, checklines, commonlength,
  1717. commonprefix, commonsuffix, diffs;
  1718. // Set a deadline by which time the diff must be complete.
  1719. if ( typeof optDeadline === "undefined" ) {
  1720. if ( this.DiffTimeout <= 0 ) {
  1721. optDeadline = Number.MAX_VALUE;
  1722. } else {
  1723. optDeadline = ( new Date() ).getTime() + this.DiffTimeout * 1000;
  1724. }
  1725. }
  1726. deadline = optDeadline;
  1727. // Check for null inputs.
  1728. if ( text1 === null || text2 === null ) {
  1729. throw new Error( "Null input. (DiffMain)" );
  1730. }
  1731. // Check for equality (speedup).
  1732. if ( text1 === text2 ) {
  1733. if ( text1 ) {
  1734. return [
  1735. [ DIFF_EQUAL, text1 ]
  1736. ];
  1737. }
  1738. return [];
  1739. }
  1740. if ( typeof optChecklines === "undefined" ) {
  1741. optChecklines = true;
  1742. }
  1743. checklines = optChecklines;
  1744. // Trim off common prefix (speedup).
  1745. commonlength = this.diffCommonPrefix( text1, text2 );
  1746. commonprefix = text1.substring( 0, commonlength );
  1747. text1 = text1.substring( commonlength );
  1748. text2 = text2.substring( commonlength );
  1749. // Trim off common suffix (speedup).
  1750. /////////
  1751. commonlength = this.diffCommonSuffix( text1, text2 );
  1752. commonsuffix = text1.substring( text1.length - commonlength );
  1753. text1 = text1.substring( 0, text1.length - commonlength );
  1754. text2 = text2.substring( 0, text2.length - commonlength );
  1755. // Compute the diff on the middle block.
  1756. diffs = this.diffCompute( text1, text2, checklines, deadline );
  1757. // Restore the prefix and suffix.
  1758. if ( commonprefix ) {
  1759. diffs.unshift( [ DIFF_EQUAL, commonprefix ] );
  1760. }
  1761. if ( commonsuffix ) {
  1762. diffs.push( [ DIFF_EQUAL, commonsuffix ] );
  1763. }
  1764. this.diffCleanupMerge( diffs );
  1765. return diffs;
  1766. };
  1767. /**
  1768. * Reduce the number of edits by eliminating operationally trivial equalities.
  1769. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  1770. */
  1771. DiffMatchPatch.prototype.diffCleanupEfficiency = function( diffs ) {
  1772. var changes, equalities, equalitiesLength, lastequality,
  1773. pointer, preIns, preDel, postIns, postDel;
  1774. changes = false;
  1775. equalities = []; // Stack of indices where equalities are found.
  1776. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  1777. /** @type {?string} */
  1778. lastequality = null;
  1779. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  1780. pointer = 0; // Index of current position.
  1781. // Is there an insertion operation before the last equality.
  1782. preIns = false;
  1783. // Is there a deletion operation before the last equality.
  1784. preDel = false;
  1785. // Is there an insertion operation after the last equality.
  1786. postIns = false;
  1787. // Is there a deletion operation after the last equality.
  1788. postDel = false;
  1789. while ( pointer < diffs.length ) {
  1790. if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) { // Equality found.
  1791. if ( diffs[ pointer ][ 1 ].length < this.DiffEditCost && ( postIns || postDel ) ) {
  1792. // Candidate found.
  1793. equalities[ equalitiesLength++ ] = pointer;
  1794. preIns = postIns;
  1795. preDel = postDel;
  1796. lastequality = diffs[ pointer ][ 1 ];
  1797. } else {
  1798. // Not a candidate, and can never become one.
  1799. equalitiesLength = 0;
  1800. lastequality = null;
  1801. }
  1802. postIns = postDel = false;
  1803. } else { // An insertion or deletion.
  1804. if ( diffs[ pointer ][ 0 ] === DIFF_DELETE ) {
  1805. postDel = true;
  1806. } else {
  1807. postIns = true;
  1808. }
  1809. /*
  1810. * Five types to be split:
  1811. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  1812. * <ins>A</ins>X<ins>C</ins><del>D</del>
  1813. * <ins>A</ins><del>B</del>X<ins>C</ins>
  1814. * <ins>A</del>X<ins>C</ins><del>D</del>
  1815. * <ins>A</ins><del>B</del>X<del>C</del>
  1816. */
  1817. if ( lastequality && ( ( preIns && preDel && postIns && postDel ) ||
  1818. ( ( lastequality.length < this.DiffEditCost / 2 ) &&
  1819. ( preIns + preDel + postIns + postDel ) === 3 ) ) ) {
  1820. // Duplicate record.
  1821. diffs.splice( equalities[equalitiesLength - 1], 0, [ DIFF_DELETE, lastequality ] );
  1822. // Change second copy to insert.
  1823. diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
  1824. equalitiesLength--; // Throw away the equality we just deleted;
  1825. lastequality = null;
  1826. if (preIns && preDel) {
  1827. // No changes made which could affect previous entry, keep going.
  1828. postIns = postDel = true;
  1829. equalitiesLength = 0;
  1830. } else {
  1831. equalitiesLength--; // Throw away the previous equality.
  1832. pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
  1833. postIns = postDel = false;
  1834. }
  1835. changes = true;
  1836. }
  1837. }
  1838. pointer++;
  1839. }
  1840. if ( changes ) {
  1841. this.diffCleanupMerge( diffs );
  1842. }
  1843. };
  1844. /**
  1845. * Convert a diff array into a pretty HTML report.
  1846. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  1847. * @param {integer} string to be beautified.
  1848. * @return {string} HTML representation.
  1849. */
  1850. DiffMatchPatch.prototype.diffPrettyHtml = function( diffs ) {
  1851. var op, data, x, html = [];
  1852. for ( x = 0; x < diffs.length; x++ ) {
  1853. op = diffs[x][0]; // Operation (insert, delete, equal)
  1854. data = diffs[x][1]; // Text of change.
  1855. switch ( op ) {
  1856. case DIFF_INSERT:
  1857. html[x] = "<ins>" + data + "</ins>";
  1858. break;
  1859. case DIFF_DELETE:
  1860. html[x] = "<del>" + data + "</del>";
  1861. break;
  1862. case DIFF_EQUAL:
  1863. html[x] = "<span>" + data + "</span>";
  1864. break;
  1865. }
  1866. }
  1867. return html.join("");
  1868. };
  1869. /**
  1870. * Determine the common prefix of two strings.
  1871. * @param {string} text1 First string.
  1872. * @param {string} text2 Second string.
  1873. * @return {number} The number of characters common to the start of each
  1874. * string.
  1875. */
  1876. DiffMatchPatch.prototype.diffCommonPrefix = function( text1, text2 ) {
  1877. var pointermid, pointermax, pointermin, pointerstart;
  1878. // Quick check for common null cases.
  1879. if ( !text1 || !text2 || text1.charAt(0) !== text2.charAt(0) ) {
  1880. return 0;
  1881. }
  1882. // Binary search.
  1883. // Performance analysis: http://neil.fraser.name/news/2007/10/09/
  1884. pointermin = 0;
  1885. pointermax = Math.min( text1.length, text2.length );
  1886. pointermid = pointermax;
  1887. pointerstart = 0;
  1888. while ( pointermin < pointermid ) {
  1889. if ( text1.substring( pointerstart, pointermid ) === text2.substring( pointerstart, pointermid ) ) {
  1890. pointermin = pointermid;
  1891. pointerstart = pointermin;
  1892. } else {
  1893. pointermax = pointermid;
  1894. }
  1895. pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
  1896. }
  1897. return pointermid;
  1898. };
  1899. /**
  1900. * Determine the common suffix of two strings.
  1901. * @param {string} text1 First string.
  1902. * @param {string} text2 Second string.
  1903. * @return {number} The number of characters common to the end of each string.
  1904. */
  1905. DiffMatchPatch.prototype.diffCommonSuffix = function( text1, text2 ) {
  1906. var pointermid, pointermax, pointermin, pointerend;
  1907. // Quick check for common null cases.
  1908. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
  1909. return 0;
  1910. }
  1911. // Binary search.
  1912. // Performance analysis: http://neil.fraser.name/news/2007/10/09/
  1913. pointermin = 0;
  1914. pointermax = Math.min(text1.length, text2.length);
  1915. pointermid = pointermax;
  1916. pointerend = 0;
  1917. while ( pointermin < pointermid ) {
  1918. if (text1.substring( text1.length - pointermid, text1.length - pointerend ) ===
  1919. text2.substring( text2.length - pointermid, text2.length - pointerend ) ) {
  1920. pointermin = pointermid;
  1921. pointerend = pointermin;
  1922. } else {
  1923. pointermax = pointermid;
  1924. }
  1925. pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
  1926. }
  1927. return pointermid;
  1928. };
  1929. /**
  1930. * Find the differences between two texts. Assumes that the texts do not
  1931. * have any common prefix or suffix.
  1932. * @param {string} text1 Old string to be diffed.
  1933. * @param {string} text2 New string to be diffed.
  1934. * @param {boolean} checklines Speedup flag. If false, then don't run a
  1935. * line-level diff first to identify the changed areas.
  1936. * If true, then run a faster, slightly less optimal diff.
  1937. * @param {number} deadline Time when the diff should be complete by.
  1938. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  1939. * @private
  1940. */
  1941. DiffMatchPatch.prototype.diffCompute = function( text1, text2, checklines, deadline ) {
  1942. var diffs, longtext, shorttext, i, hm,
  1943. text1A, text2A, text1B, text2B,
  1944. midCommon, diffsA, diffsB;
  1945. if ( !text1 ) {
  1946. // Just add some text (speedup).
  1947. return [
  1948. [ DIFF_INSERT, text2 ]
  1949. ];
  1950. }
  1951. if (!text2) {
  1952. // Just delete some text (speedup).
  1953. return [
  1954. [ DIFF_DELETE, text1 ]
  1955. ];
  1956. }
  1957. longtext = text1.length > text2.length ? text1 : text2;
  1958. shorttext = text1.length > text2.length ? text2 : text1;
  1959. i = longtext.indexOf( shorttext );
  1960. if ( i !== -1 ) {
  1961. // Shorter text is inside the longer text (speedup).
  1962. diffs = [
  1963. [ DIFF_INSERT, longtext.substring( 0, i ) ],
  1964. [ DIFF_EQUAL, shorttext ],
  1965. [ DIFF_INSERT, longtext.substring( i + shorttext.length ) ]
  1966. ];
  1967. // Swap insertions for deletions if diff is reversed.
  1968. if ( text1.length > text2.length ) {
  1969. diffs[0][0] = diffs[2][0] = DIFF_DELETE;
  1970. }
  1971. return diffs;
  1972. }
  1973. if ( shorttext.length === 1 ) {
  1974. // Single character string.
  1975. // After the previous speedup, the character can't be an equality.
  1976. return [
  1977. [ DIFF_DELETE, text1 ],
  1978. [ DIFF_INSERT, text2 ]
  1979. ];
  1980. }
  1981. // Check to see if the problem can be split in two.
  1982. hm = this.diffHalfMatch(text1, text2);
  1983. if (hm) {
  1984. // A half-match was found, sort out the return data.
  1985. text1A = hm[0];
  1986. text1B = hm[1];
  1987. text2A = hm[2];
  1988. text2B = hm[3];
  1989. midCommon = hm[4];
  1990. // Send both pairs off for separate processing.
  1991. diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
  1992. diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
  1993. // Merge the results.
  1994. return diffsA.concat([
  1995. [ DIFF_EQUAL, midCommon ]
  1996. ], diffsB);
  1997. }
  1998. if (checklines && text1.length > 100 && text2.length > 100) {
  1999. return this.diffLineMode(text1, text2, deadline);
  2000. }
  2001. return this.diffBisect(text1, text2, deadline);
  2002. };
  2003. /**
  2004. * Do the two texts share a substring which is at least half the length of the
  2005. * longer text?
  2006. * This speedup can produce non-minimal diffs.
  2007. * @param {string} text1 First string.
  2008. * @param {string} text2 Second string.
  2009. * @return {Array.<string>} Five element Array, containing the prefix of
  2010. * text1, the suffix of text1, the prefix of text2, the suffix of
  2011. * text2 and the common middle. Or null if there was no match.
  2012. * @private
  2013. */
  2014. DiffMatchPatch.prototype.diffHalfMatch = function(text1, text2) {
  2015. var longtext, shorttext, dmp,
  2016. text1A, text2B, text2A, text1B, midCommon,
  2017. hm1, hm2, hm;
  2018. if (this.DiffTimeout <= 0) {
  2019. // Don't risk returning a non-optimal diff if we have unlimited time.
  2020. return null;
  2021. }
  2022. longtext = text1.length > text2.length ? text1 : text2;
  2023. shorttext = text1.length > text2.length ? text2 : text1;
  2024. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  2025. return null; // Pointless.
  2026. }
  2027. dmp = this; // 'this' becomes 'window' in a closure.
  2028. /**
  2029. * Does a substring of shorttext exist within longtext such that the substring
  2030. * is at least half the length of longtext?
  2031. * Closure, but does not reference any external variables.
  2032. * @param {string} longtext Longer string.
  2033. * @param {string} shorttext Shorter string.
  2034. * @param {number} i Start index of quarter length substring within longtext.
  2035. * @return {Array.<string>} Five element Array, containing the prefix of
  2036. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  2037. * of shorttext and the common middle. Or null if there was no match.
  2038. * @private
  2039. */
  2040. function diffHalfMatchI(longtext, shorttext, i) {
  2041. var seed, j, bestCommon, prefixLength, suffixLength,
  2042. bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
  2043. // Start with a 1/4 length substring at position i as a seed.
  2044. seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
  2045. j = -1;
  2046. bestCommon = "";
  2047. while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
  2048. prefixLength = dmp.diffCommonPrefix(longtext.substring(i),
  2049. shorttext.substring(j));
  2050. suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i),
  2051. shorttext.substring(0, j));
  2052. if (bestCommon.length < suffixLength + prefixLength) {
  2053. bestCommon = shorttext.substring(j - suffixLength, j) +
  2054. shorttext.substring(j, j + prefixLength);
  2055. bestLongtextA = longtext.substring(0, i - suffixLength);
  2056. bestLongtextB = longtext.substring(i + prefixLength);
  2057. bestShorttextA = shorttext.substring(0, j - suffixLength);
  2058. bestShorttextB = shorttext.substring(j + prefixLength);
  2059. }
  2060. }
  2061. if (bestCommon.length * 2 >= longtext.length) {
  2062. return [ bestLongtextA, bestLongtextB,
  2063. bestShorttextA, bestShorttextB, bestCommon
  2064. ];
  2065. } else {
  2066. return null;
  2067. }
  2068. }
  2069. // First check if the second quarter is the seed for a half-match.
  2070. hm1 = diffHalfMatchI(longtext, shorttext,
  2071. Math.ceil(longtext.length / 4));
  2072. // Check again based on the third quarter.
  2073. hm2 = diffHalfMatchI(longtext, shorttext,
  2074. Math.ceil(longtext.length / 2));
  2075. if (!hm1 && !hm2) {
  2076. return null;
  2077. } else if (!hm2) {
  2078. hm = hm1;
  2079. } else if (!hm1) {
  2080. hm = hm2;
  2081. } else {
  2082. // Both matched. Select the longest.
  2083. hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
  2084. }
  2085. // A half-match was found, sort out the return data.
  2086. text1A, text1B, text2A, text2B;
  2087. if (text1.length > text2.length) {
  2088. text1A = hm[0];
  2089. text1B = hm[1];
  2090. text2A = hm[2];
  2091. text2B = hm[3];
  2092. } else {
  2093. text2A = hm[0];
  2094. text2B = hm[1];
  2095. text1A = hm[2];
  2096. text1B = hm[3];
  2097. }
  2098. midCommon = hm[4];
  2099. return [ text1A, text1B, text2A, text2B, midCommon ];
  2100. };
  2101. /**
  2102. * Do a quick line-level diff on both strings, then rediff the parts for
  2103. * greater accuracy.
  2104. * This speedup can produce non-minimal diffs.
  2105. * @param {string} text1 Old string to be diffed.
  2106. * @param {string} text2 New string to be diffed.
  2107. * @param {number} deadline Time when the diff should be complete by.
  2108. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  2109. * @private
  2110. */
  2111. DiffMatchPatch.prototype.diffLineMode = function(text1, text2, deadline) {
  2112. var a, diffs, linearray, pointer, countInsert,
  2113. countDelete, textInsert, textDelete, j;
  2114. // Scan the text on a line-by-line basis first.
  2115. a = this.diffLinesToChars(text1, text2);
  2116. text1 = a.chars1;
  2117. text2 = a.chars2;
  2118. linearray = a.lineArray;
  2119. diffs = this.DiffMain(text1, text2, false, deadline);
  2120. // Convert the diff back to original text.
  2121. this.diffCharsToLines(diffs, linearray);
  2122. // Eliminate freak matches (e.g. blank lines)
  2123. this.diffCleanupSemantic(diffs);
  2124. // Rediff any replacement blocks, this time character-by-character.
  2125. // Add a dummy entry at the end.
  2126. diffs.push( [ DIFF_EQUAL, "" ] );
  2127. pointer = 0;
  2128. countDelete = 0;
  2129. countInsert = 0;
  2130. textDelete = "";
  2131. textInsert = "";
  2132. while (pointer < diffs.length) {
  2133. switch ( diffs[pointer][0] ) {
  2134. case DIFF_INSERT:
  2135. countInsert++;
  2136. textInsert += diffs[pointer][1];
  2137. break;
  2138. case DIFF_DELETE:
  2139. countDelete++;
  2140. textDelete += diffs[pointer][1];
  2141. break;
  2142. case DIFF_EQUAL:
  2143. // Upon reaching an equality, check for prior redundancies.
  2144. if (countDelete >= 1 && countInsert >= 1) {
  2145. // Delete the offending records and add the merged ones.
  2146. diffs.splice(pointer - countDelete - countInsert,
  2147. countDelete + countInsert);
  2148. pointer = pointer - countDelete - countInsert;
  2149. a = this.DiffMain(textDelete, textInsert, false, deadline);
  2150. for (j = a.length - 1; j >= 0; j--) {
  2151. diffs.splice( pointer, 0, a[j] );
  2152. }
  2153. pointer = pointer + a.length;
  2154. }
  2155. countInsert = 0;
  2156. countDelete = 0;
  2157. textDelete = "";
  2158. textInsert = "";
  2159. break;
  2160. }
  2161. pointer++;
  2162. }
  2163. diffs.pop(); // Remove the dummy entry at the end.
  2164. return diffs;
  2165. };
  2166. /**
  2167. * Find the 'middle snake' of a diff, split the problem in two
  2168. * and return the recursively constructed diff.
  2169. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  2170. * @param {string} text1 Old string to be diffed.
  2171. * @param {string} text2 New string to be diffed.
  2172. * @param {number} deadline Time at which to bail if not yet complete.
  2173. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  2174. * @private
  2175. */
  2176. DiffMatchPatch.prototype.diffBisect = function(text1, text2, deadline) {
  2177. var text1Length, text2Length, maxD, vOffset, vLength,
  2178. v1, v2, x, delta, front, k1start, k1end, k2start,
  2179. k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
  2180. // Cache the text lengths to prevent multiple calls.
  2181. text1Length = text1.length;
  2182. text2Length = text2.length;
  2183. maxD = Math.ceil((text1Length + text2Length) / 2);
  2184. vOffset = maxD;
  2185. vLength = 2 * maxD;
  2186. v1 = new Array(vLength);
  2187. v2 = new Array(vLength);
  2188. // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  2189. // integers and undefined.
  2190. for (x = 0; x < vLength; x++) {
  2191. v1[x] = -1;
  2192. v2[x] = -1;
  2193. }
  2194. v1[vOffset + 1] = 0;
  2195. v2[vOffset + 1] = 0;
  2196. delta = text1Length - text2Length;
  2197. // If the total number of characters is odd, then the front path will collide
  2198. // with the reverse path.
  2199. front = (delta % 2 !== 0);
  2200. // Offsets for start and end of k loop.
  2201. // Prevents mapping of space beyond the grid.
  2202. k1start = 0;
  2203. k1end = 0;
  2204. k2start = 0;
  2205. k2end = 0;
  2206. for (d = 0; d < maxD; d++) {
  2207. // Bail out if deadline is reached.
  2208. if ((new Date()).getTime() > deadline) {
  2209. break;
  2210. }
  2211. // Walk the front path one step.
  2212. for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  2213. k1Offset = vOffset + k1;
  2214. if ( k1 === -d || ( k1 !== d && v1[ k1Offset - 1 ] < v1[ k1Offset + 1 ] ) ) {
  2215. x1 = v1[k1Offset + 1];
  2216. } else {
  2217. x1 = v1[k1Offset - 1] + 1;
  2218. }
  2219. y1 = x1 - k1;
  2220. while (x1 < text1Length && y1 < text2Length &&
  2221. text1.charAt(x1) === text2.charAt(y1)) {
  2222. x1++;
  2223. y1++;
  2224. }
  2225. v1[k1Offset] = x1;
  2226. if (x1 > text1Length) {
  2227. // Ran off the right of the graph.
  2228. k1end += 2;
  2229. } else if (y1 > text2Length) {
  2230. // Ran off the bottom of the graph.
  2231. k1start += 2;
  2232. } else if (front) {
  2233. k2Offset = vOffset + delta - k1;
  2234. if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
  2235. // Mirror x2 onto top-left coordinate system.
  2236. x2 = text1Length - v2[k2Offset];
  2237. if (x1 >= x2) {
  2238. // Overlap detected.
  2239. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  2240. }
  2241. }
  2242. }
  2243. }
  2244. // Walk the reverse path one step.
  2245. for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  2246. k2Offset = vOffset + k2;
  2247. if ( k2 === -d || (k2 !== d && v2[ k2Offset - 1 ] < v2[ k2Offset + 1 ] ) ) {
  2248. x2 = v2[k2Offset + 1];
  2249. } else {
  2250. x2 = v2[k2Offset - 1] + 1;
  2251. }
  2252. y2 = x2 - k2;
  2253. while (x2 < text1Length && y2 < text2Length &&
  2254. text1.charAt(text1Length - x2 - 1) ===
  2255. text2.charAt(text2Length - y2 - 1)) {
  2256. x2++;
  2257. y2++;
  2258. }
  2259. v2[k2Offset] = x2;
  2260. if (x2 > text1Length) {
  2261. // Ran off the left of the graph.
  2262. k2end += 2;
  2263. } else if (y2 > text2Length) {
  2264. // Ran off the top of the graph.
  2265. k2start += 2;
  2266. } else if (!front) {
  2267. k1Offset = vOffset + delta - k2;
  2268. if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
  2269. x1 = v1[k1Offset];
  2270. y1 = vOffset + x1 - k1Offset;
  2271. // Mirror x2 onto top-left coordinate system.
  2272. x2 = text1Length - x2;
  2273. if (x1 >= x2) {
  2274. // Overlap detected.
  2275. return this.diffBisectSplit(text1, text2, x1, y1, deadline);
  2276. }
  2277. }
  2278. }
  2279. }
  2280. }
  2281. // Diff took too long and hit the deadline or
  2282. // number of diffs equals number of characters, no commonality at all.
  2283. return [
  2284. [ DIFF_DELETE, text1 ],
  2285. [ DIFF_INSERT, text2 ]
  2286. ];
  2287. };
  2288. /**
  2289. * Given the location of the 'middle snake', split the diff in two parts
  2290. * and recurse.
  2291. * @param {string} text1 Old string to be diffed.
  2292. * @param {string} text2 New string to be diffed.
  2293. * @param {number} x Index of split point in text1.
  2294. * @param {number} y Index of split point in text2.
  2295. * @param {number} deadline Time at which to bail if not yet complete.
  2296. * @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
  2297. * @private
  2298. */
  2299. DiffMatchPatch.prototype.diffBisectSplit = function( text1, text2, x, y, deadline ) {
  2300. var text1a, text1b, text2a, text2b, diffs, diffsb;
  2301. text1a = text1.substring(0, x);
  2302. text2a = text2.substring(0, y);
  2303. text1b = text1.substring(x);
  2304. text2b = text2.substring(y);
  2305. // Compute both diffs serially.
  2306. diffs = this.DiffMain(text1a, text2a, false, deadline);
  2307. diffsb = this.DiffMain(text1b, text2b, false, deadline);
  2308. return diffs.concat(diffsb);
  2309. };
  2310. /**
  2311. * Reduce the number of edits by eliminating semantically trivial equalities.
  2312. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  2313. */
  2314. DiffMatchPatch.prototype.diffCleanupSemantic = function(diffs) {
  2315. var changes, equalities, equalitiesLength, lastequality,
  2316. pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1,
  2317. lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
  2318. changes = false;
  2319. equalities = []; // Stack of indices where equalities are found.
  2320. equalitiesLength = 0; // Keeping our own length var is faster in JS.
  2321. /** @type {?string} */
  2322. lastequality = null;
  2323. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  2324. pointer = 0; // Index of current position.
  2325. // Number of characters that changed prior to the equality.
  2326. lengthInsertions1 = 0;
  2327. lengthDeletions1 = 0;
  2328. // Number of characters that changed after the equality.
  2329. lengthInsertions2 = 0;
  2330. lengthDeletions2 = 0;
  2331. while (pointer < diffs.length) {
  2332. if (diffs[pointer][0] === DIFF_EQUAL) { // Equality found.
  2333. equalities[equalitiesLength++] = pointer;
  2334. lengthInsertions1 = lengthInsertions2;
  2335. lengthDeletions1 = lengthDeletions2;
  2336. lengthInsertions2 = 0;
  2337. lengthDeletions2 = 0;
  2338. lastequality = diffs[pointer][1];
  2339. } else { // An insertion or deletion.
  2340. if (diffs[pointer][0] === DIFF_INSERT) {
  2341. lengthInsertions2 += diffs[pointer][1].length;
  2342. } else {
  2343. lengthDeletions2 += diffs[pointer][1].length;
  2344. }
  2345. // Eliminate an equality that is smaller or equal to the edits on both
  2346. // sides of it.
  2347. if (lastequality && (lastequality.length <=
  2348. Math.max(lengthInsertions1, lengthDeletions1)) &&
  2349. (lastequality.length <= Math.max(lengthInsertions2,
  2350. lengthDeletions2))) {
  2351. // Duplicate record.
  2352. diffs.splice( equalities[ equalitiesLength - 1 ], 0, [ DIFF_DELETE, lastequality ] );
  2353. // Change second copy to insert.
  2354. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
  2355. // Throw away the equality we just deleted.
  2356. equalitiesLength--;
  2357. // Throw away the previous equality (it needs to be reevaluated).
  2358. equalitiesLength--;
  2359. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
  2360. lengthInsertions1 = 0; // Reset the counters.
  2361. lengthDeletions1 = 0;
  2362. lengthInsertions2 = 0;
  2363. lengthDeletions2 = 0;
  2364. lastequality = null;
  2365. changes = true;
  2366. }
  2367. }
  2368. pointer++;
  2369. }
  2370. // Normalize the diff.
  2371. if (changes) {
  2372. this.diffCleanupMerge(diffs);
  2373. }
  2374. // Find any overlaps between deletions and insertions.
  2375. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  2376. // -> <del>abc</del>xxx<ins>def</ins>
  2377. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  2378. // -> <ins>def</ins>xxx<del>abc</del>
  2379. // Only extract an overlap if it is as big as the edit ahead or behind it.
  2380. pointer = 1;
  2381. while (pointer < diffs.length) {
  2382. if (diffs[pointer - 1][0] === DIFF_DELETE &&
  2383. diffs[pointer][0] === DIFF_INSERT) {
  2384. deletion = diffs[pointer - 1][1];
  2385. insertion = diffs[pointer][1];
  2386. overlapLength1 = this.diffCommonOverlap(deletion, insertion);
  2387. overlapLength2 = this.diffCommonOverlap(insertion, deletion);
  2388. if (overlapLength1 >= overlapLength2) {
  2389. if (overlapLength1 >= deletion.length / 2 ||
  2390. overlapLength1 >= insertion.length / 2) {
  2391. // Overlap found. Insert an equality and trim the surrounding edits.
  2392. diffs.splice( pointer, 0, [ DIFF_EQUAL, insertion.substring( 0, overlapLength1 ) ] );
  2393. diffs[pointer - 1][1] =
  2394. deletion.substring(0, deletion.length - overlapLength1);
  2395. diffs[pointer + 1][1] = insertion.substring(overlapLength1);
  2396. pointer++;
  2397. }
  2398. } else {
  2399. if (overlapLength2 >= deletion.length / 2 ||
  2400. overlapLength2 >= insertion.length / 2) {
  2401. // Reverse overlap found.
  2402. // Insert an equality and swap and trim the surrounding edits.
  2403. diffs.splice( pointer, 0, [ DIFF_EQUAL, deletion.substring( 0, overlapLength2 ) ] );
  2404. diffs[pointer - 1][0] = DIFF_INSERT;
  2405. diffs[pointer - 1][1] =
  2406. insertion.substring(0, insertion.length - overlapLength2);
  2407. diffs[pointer + 1][0] = DIFF_DELETE;
  2408. diffs[pointer + 1][1] =
  2409. deletion.substring(overlapLength2);
  2410. pointer++;
  2411. }
  2412. }
  2413. pointer++;
  2414. }
  2415. pointer++;
  2416. }
  2417. };
  2418. /**
  2419. * Determine if the suffix of one string is the prefix of another.
  2420. * @param {string} text1 First string.
  2421. * @param {string} text2 Second string.
  2422. * @return {number} The number of characters common to the end of the first
  2423. * string and the start of the second string.
  2424. * @private
  2425. */
  2426. DiffMatchPatch.prototype.diffCommonOverlap = function(text1, text2) {
  2427. var text1Length, text2Length, textLength,
  2428. best, length, pattern, found;
  2429. // Cache the text lengths to prevent multiple calls.
  2430. text1Length = text1.length;
  2431. text2Length = text2.length;
  2432. // Eliminate the null case.
  2433. if (text1Length === 0 || text2Length === 0) {
  2434. return 0;
  2435. }
  2436. // Truncate the longer string.
  2437. if (text1Length > text2Length) {
  2438. text1 = text1.substring(text1Length - text2Length);
  2439. } else if (text1Length < text2Length) {
  2440. text2 = text2.substring(0, text1Length);
  2441. }
  2442. textLength = Math.min(text1Length, text2Length);
  2443. // Quick check for the worst case.
  2444. if (text1 === text2) {
  2445. return textLength;
  2446. }
  2447. // Start by looking for a single character match
  2448. // and increase length until no match is found.
  2449. // Performance analysis: http://neil.fraser.name/news/2010/11/04/
  2450. best = 0;
  2451. length = 1;
  2452. while (true) {
  2453. pattern = text1.substring(textLength - length);
  2454. found = text2.indexOf(pattern);
  2455. if (found === -1) {
  2456. return best;
  2457. }
  2458. length += found;
  2459. if (found === 0 || text1.substring(textLength - length) ===
  2460. text2.substring(0, length)) {
  2461. best = length;
  2462. length++;
  2463. }
  2464. }
  2465. };
  2466. /**
  2467. * Split two texts into an array of strings. Reduce the texts to a string of
  2468. * hashes where each Unicode character represents one line.
  2469. * @param {string} text1 First string.
  2470. * @param {string} text2 Second string.
  2471. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  2472. * An object containing the encoded text1, the encoded text2 and
  2473. * the array of unique strings.
  2474. * The zeroth element of the array of unique strings is intentionally blank.
  2475. * @private
  2476. */
  2477. DiffMatchPatch.prototype.diffLinesToChars = function(text1, text2) {
  2478. var lineArray, lineHash, chars1, chars2;
  2479. lineArray = []; // e.g. lineArray[4] === 'Hello\n'
  2480. lineHash = {}; // e.g. lineHash['Hello\n'] === 4
  2481. // '\x00' is a valid character, but various debuggers don't like it.
  2482. // So we'll insert a junk entry to avoid generating a null character.
  2483. lineArray[0] = "";
  2484. /**
  2485. * Split a text into an array of strings. Reduce the texts to a string of
  2486. * hashes where each Unicode character represents one line.
  2487. * Modifies linearray and linehash through being a closure.
  2488. * @param {string} text String to encode.
  2489. * @return {string} Encoded string.
  2490. * @private
  2491. */
  2492. function diffLinesToCharsMunge(text) {
  2493. var chars, lineStart, lineEnd, lineArrayLength, line;
  2494. chars = "";
  2495. // Walk the text, pulling out a substring for each line.
  2496. // text.split('\n') would would temporarily double our memory footprint.
  2497. // Modifying text would create many large strings to garbage collect.
  2498. lineStart = 0;
  2499. lineEnd = -1;
  2500. // Keeping our own length variable is faster than looking it up.
  2501. lineArrayLength = lineArray.length;
  2502. while (lineEnd < text.length - 1) {
  2503. lineEnd = text.indexOf("\n", lineStart);
  2504. if (lineEnd === -1) {
  2505. lineEnd = text.length - 1;
  2506. }
  2507. line = text.substring(lineStart, lineEnd + 1);
  2508. lineStart = lineEnd + 1;
  2509. if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
  2510. (lineHash[line] !== undefined)) {
  2511. chars += String.fromCharCode( lineHash[ line ] );
  2512. } else {
  2513. chars += String.fromCharCode(lineArrayLength);
  2514. lineHash[line] = lineArrayLength;
  2515. lineArray[lineArrayLength++] = line;
  2516. }
  2517. }
  2518. return chars;
  2519. }
  2520. chars1 = diffLinesToCharsMunge(text1);
  2521. chars2 = diffLinesToCharsMunge(text2);
  2522. return {
  2523. chars1: chars1,
  2524. chars2: chars2,
  2525. lineArray: lineArray
  2526. };
  2527. };
  2528. /**
  2529. * Rehydrate the text in a diff from a string of line hashes to real lines of
  2530. * text.
  2531. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  2532. * @param {!Array.<string>} lineArray Array of unique strings.
  2533. * @private
  2534. */
  2535. DiffMatchPatch.prototype.diffCharsToLines = function( diffs, lineArray ) {
  2536. var x, chars, text, y;
  2537. for ( x = 0; x < diffs.length; x++ ) {
  2538. chars = diffs[x][1];
  2539. text = [];
  2540. for ( y = 0; y < chars.length; y++ ) {
  2541. text[y] = lineArray[chars.charCodeAt(y)];
  2542. }
  2543. diffs[x][1] = text.join("");
  2544. }
  2545. };
  2546. /**
  2547. * Reorder and merge like edit sections. Merge equalities.
  2548. * Any edit section can move as long as it doesn't cross an equality.
  2549. * @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
  2550. */
  2551. DiffMatchPatch.prototype.diffCleanupMerge = function(diffs) {
  2552. var pointer, countDelete, countInsert, textInsert, textDelete,
  2553. commonlength, changes;
  2554. diffs.push( [ DIFF_EQUAL, "" ] ); // Add a dummy entry at the end.
  2555. pointer = 0;
  2556. countDelete = 0;
  2557. countInsert = 0;
  2558. textDelete = "";
  2559. textInsert = "";
  2560. commonlength;
  2561. while (pointer < diffs.length) {
  2562. switch ( diffs[ pointer ][ 0 ] ) {
  2563. case DIFF_INSERT:
  2564. countInsert++;
  2565. textInsert += diffs[pointer][1];
  2566. pointer++;
  2567. break;
  2568. case DIFF_DELETE:
  2569. countDelete++;
  2570. textDelete += diffs[pointer][1];
  2571. pointer++;
  2572. break;
  2573. case DIFF_EQUAL:
  2574. // Upon reaching an equality, check for prior redundancies.
  2575. if (countDelete + countInsert > 1) {
  2576. if (countDelete !== 0 && countInsert !== 0) {
  2577. // Factor out any common prefixies.
  2578. commonlength = this.diffCommonPrefix(textInsert, textDelete);
  2579. if (commonlength !== 0) {
  2580. if ((pointer - countDelete - countInsert) > 0 &&
  2581. diffs[pointer - countDelete - countInsert - 1][0] ===
  2582. DIFF_EQUAL) {
  2583. diffs[pointer - countDelete - countInsert - 1][1] +=
  2584. textInsert.substring(0, commonlength);
  2585. } else {
  2586. diffs.splice( 0, 0, [ DIFF_EQUAL,
  2587. textInsert.substring( 0, commonlength )
  2588. ] );
  2589. pointer++;
  2590. }
  2591. textInsert = textInsert.substring(commonlength);
  2592. textDelete = textDelete.substring(commonlength);
  2593. }
  2594. // Factor out any common suffixies.
  2595. commonlength = this.diffCommonSuffix(textInsert, textDelete);
  2596. if (commonlength !== 0) {
  2597. diffs[pointer][1] = textInsert.substring(textInsert.length -
  2598. commonlength) + diffs[pointer][1];
  2599. textInsert = textInsert.substring(0, textInsert.length -
  2600. commonlength);
  2601. textDelete = textDelete.substring(0, textDelete.length -
  2602. commonlength);
  2603. }
  2604. }
  2605. // Delete the offending records and add the merged ones.
  2606. if (countDelete === 0) {
  2607. diffs.splice( pointer - countInsert,
  2608. countDelete + countInsert, [ DIFF_INSERT, textInsert ] );
  2609. } else if (countInsert === 0) {
  2610. diffs.splice( pointer - countDelete,
  2611. countDelete + countInsert, [ DIFF_DELETE, textDelete ] );
  2612. } else {
  2613. diffs.splice( pointer - countDelete - countInsert,
  2614. countDelete + countInsert, [ DIFF_DELETE, textDelete ], [ DIFF_INSERT, textInsert ] );
  2615. }
  2616. pointer = pointer - countDelete - countInsert +
  2617. (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
  2618. } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
  2619. // Merge this equality with the previous one.
  2620. diffs[pointer - 1][1] += diffs[pointer][1];
  2621. diffs.splice(pointer, 1);
  2622. } else {
  2623. pointer++;
  2624. }
  2625. countInsert = 0;
  2626. countDelete = 0;
  2627. textDelete = "";
  2628. textInsert = "";
  2629. break;
  2630. }
  2631. }
  2632. if (diffs[diffs.length - 1][1] === "") {
  2633. diffs.pop(); // Remove the dummy entry at the end.
  2634. }
  2635. // Second pass: look for single edits surrounded on both sides by equalities
  2636. // which can be shifted sideways to eliminate an equality.
  2637. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  2638. changes = false;
  2639. pointer = 1;
  2640. // Intentionally ignore the first and last element (don't need checking).
  2641. while (pointer < diffs.length - 1) {
  2642. if (diffs[pointer - 1][0] === DIFF_EQUAL &&
  2643. diffs[pointer + 1][0] === DIFF_EQUAL) {
  2644. // This is a single edit surrounded by equalities.
  2645. if ( diffs[ pointer ][ 1 ].substring( diffs[ pointer ][ 1 ].length -
  2646. diffs[ pointer - 1 ][ 1 ].length ) === diffs[ pointer - 1 ][ 1 ] ) {
  2647. // Shift the edit over the previous equality.
  2648. diffs[pointer][1] = diffs[pointer - 1][1] +
  2649. diffs[pointer][1].substring(0, diffs[pointer][1].length -
  2650. diffs[pointer - 1][1].length);
  2651. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
  2652. diffs.splice(pointer - 1, 1);
  2653. changes = true;
  2654. } else if ( diffs[ pointer ][ 1 ].substring( 0, diffs[ pointer + 1 ][ 1 ].length ) ===
  2655. diffs[ pointer + 1 ][ 1 ] ) {
  2656. // Shift the edit over the next equality.
  2657. diffs[pointer - 1][1] += diffs[pointer + 1][1];
  2658. diffs[pointer][1] =
  2659. diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
  2660. diffs[pointer + 1][1];
  2661. diffs.splice(pointer + 1, 1);
  2662. changes = true;
  2663. }
  2664. }
  2665. pointer++;
  2666. }
  2667. // If shifts were made, the diff needs reordering and another shift sweep.
  2668. if (changes) {
  2669. this.diffCleanupMerge(diffs);
  2670. }
  2671. };
  2672. return function(o, n) {
  2673. var diff, output, text;
  2674. diff = new DiffMatchPatch();
  2675. output = diff.DiffMain(o, n);
  2676. //console.log(output);
  2677. diff.diffCleanupEfficiency(output);
  2678. text = diff.diffPrettyHtml(output);
  2679. return text;
  2680. };
  2681. }());
  2682. // jscs:enable
  2683. (function() {
  2684. // Deprecated QUnit.init - Ref #530
  2685. // Re-initialize the configuration options
  2686. QUnit.init = function() {
  2687. var tests, banner, result, qunit,
  2688. config = QUnit.config;
  2689. config.stats = { all: 0, bad: 0 };
  2690. config.moduleStats = { all: 0, bad: 0 };
  2691. config.started = 0;
  2692. config.updateRate = 1000;
  2693. config.blocking = false;
  2694. config.autostart = true;
  2695. config.autorun = false;
  2696. config.filter = "";
  2697. config.queue = [];
  2698. // Return on non-browser environments
  2699. // This is necessary to not break on node tests
  2700. if ( typeof window === "undefined" ) {
  2701. return;
  2702. }
  2703. qunit = id( "qunit" );
  2704. if ( qunit ) {
  2705. qunit.innerHTML =
  2706. "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" +
  2707. "<h2 id='qunit-banner'></h2>" +
  2708. "<div id='qunit-testrunner-toolbar'></div>" +
  2709. "<h2 id='qunit-userAgent'></h2>" +
  2710. "<ol id='qunit-tests'></ol>";
  2711. }
  2712. tests = id( "qunit-tests" );
  2713. banner = id( "qunit-banner" );
  2714. result = id( "qunit-testresult" );
  2715. if ( tests ) {
  2716. tests.innerHTML = "";
  2717. }
  2718. if ( banner ) {
  2719. banner.className = "";
  2720. }
  2721. if ( result ) {
  2722. result.parentNode.removeChild( result );
  2723. }
  2724. if ( tests ) {
  2725. result = document.createElement( "p" );
  2726. result.id = "qunit-testresult";
  2727. result.className = "result";
  2728. tests.parentNode.insertBefore( result, tests );
  2729. result.innerHTML = "Running...<br />&#160;";
  2730. }
  2731. };
  2732. // Don't load the HTML Reporter on non-Browser environments
  2733. if ( typeof window === "undefined" ) {
  2734. return;
  2735. }
  2736. var config = QUnit.config,
  2737. hasOwn = Object.prototype.hasOwnProperty,
  2738. defined = {
  2739. document: window.document !== undefined,
  2740. sessionStorage: (function() {
  2741. var x = "qunit-test-string";
  2742. try {
  2743. sessionStorage.setItem( x, x );
  2744. sessionStorage.removeItem( x );
  2745. return true;
  2746. } catch ( e ) {
  2747. return false;
  2748. }
  2749. }())
  2750. },
  2751. modulesList = [];
  2752. /**
  2753. * Escape text for attribute or text content.
  2754. */
  2755. function escapeText( s ) {
  2756. if ( !s ) {
  2757. return "";
  2758. }
  2759. s = s + "";
  2760. // Both single quotes and double quotes (for attributes)
  2761. return s.replace( /['"<>&]/g, function( s ) {
  2762. switch ( s ) {
  2763. case "'":
  2764. return "&#039;";
  2765. case "\"":
  2766. return "&quot;";
  2767. case "<":
  2768. return "&lt;";
  2769. case ">":
  2770. return "&gt;";
  2771. case "&":
  2772. return "&amp;";
  2773. }
  2774. });
  2775. }
  2776. /**
  2777. * @param {HTMLElement} elem
  2778. * @param {string} type
  2779. * @param {Function} fn
  2780. */
  2781. function addEvent( elem, type, fn ) {
  2782. if ( elem.addEventListener ) {
  2783. // Standards-based browsers
  2784. elem.addEventListener( type, fn, false );
  2785. } else if ( elem.attachEvent ) {
  2786. // support: IE <9
  2787. elem.attachEvent( "on" + type, function() {
  2788. var event = window.event;
  2789. if ( !event.target ) {
  2790. event.target = event.srcElement || document;
  2791. }
  2792. fn.call( elem, event );
  2793. });
  2794. }
  2795. }
  2796. /**
  2797. * @param {Array|NodeList} elems
  2798. * @param {string} type
  2799. * @param {Function} fn
  2800. */
  2801. function addEvents( elems, type, fn ) {
  2802. var i = elems.length;
  2803. while ( i-- ) {
  2804. addEvent( elems[ i ], type, fn );
  2805. }
  2806. }
  2807. function hasClass( elem, name ) {
  2808. return ( " " + elem.className + " " ).indexOf( " " + name + " " ) >= 0;
  2809. }
  2810. function addClass( elem, name ) {
  2811. if ( !hasClass( elem, name ) ) {
  2812. elem.className += ( elem.className ? " " : "" ) + name;
  2813. }
  2814. }
  2815. function toggleClass( elem, name ) {
  2816. if ( hasClass( elem, name ) ) {
  2817. removeClass( elem, name );
  2818. } else {
  2819. addClass( elem, name );
  2820. }
  2821. }
  2822. function removeClass( elem, name ) {
  2823. var set = " " + elem.className + " ";
  2824. // Class name may appear multiple times
  2825. while ( set.indexOf( " " + name + " " ) >= 0 ) {
  2826. set = set.replace( " " + name + " ", " " );
  2827. }
  2828. // trim for prettiness
  2829. elem.className = typeof set.trim === "function" ? set.trim() : set.replace( /^\s+|\s+$/g, "" );
  2830. }
  2831. function id( name ) {
  2832. return defined.document && document.getElementById && document.getElementById( name );
  2833. }
  2834. function getUrlConfigHtml() {
  2835. var i, j, val,
  2836. escaped, escapedTooltip,
  2837. selection = false,
  2838. len = config.urlConfig.length,
  2839. urlConfigHtml = "";
  2840. for ( i = 0; i < len; i++ ) {
  2841. val = config.urlConfig[ i ];
  2842. if ( typeof val === "string" ) {
  2843. val = {
  2844. id: val,
  2845. label: val
  2846. };
  2847. }
  2848. escaped = escapeText( val.id );
  2849. escapedTooltip = escapeText( val.tooltip );
  2850. if ( config[ val.id ] === undefined ) {
  2851. config[ val.id ] = QUnit.urlParams[ val.id ];
  2852. }
  2853. if ( !val.value || typeof val.value === "string" ) {
  2854. urlConfigHtml += "<input id='qunit-urlconfig-" + escaped +
  2855. "' name='" + escaped + "' type='checkbox'" +
  2856. ( val.value ? " value='" + escapeText( val.value ) + "'" : "" ) +
  2857. ( config[ val.id ] ? " checked='checked'" : "" ) +
  2858. " title='" + escapedTooltip + "' /><label for='qunit-urlconfig-" + escaped +
  2859. "' title='" + escapedTooltip + "'>" + val.label + "</label>";
  2860. } else {
  2861. urlConfigHtml += "<label for='qunit-urlconfig-" + escaped +
  2862. "' title='" + escapedTooltip + "'>" + val.label +
  2863. ": </label><select id='qunit-urlconfig-" + escaped +
  2864. "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
  2865. if ( QUnit.is( "array", val.value ) ) {
  2866. for ( j = 0; j < val.value.length; j++ ) {
  2867. escaped = escapeText( val.value[ j ] );
  2868. urlConfigHtml += "<option value='" + escaped + "'" +
  2869. ( config[ val.id ] === val.value[ j ] ?
  2870. ( selection = true ) && " selected='selected'" : "" ) +
  2871. ">" + escaped + "</option>";
  2872. }
  2873. } else {
  2874. for ( j in val.value ) {
  2875. if ( hasOwn.call( val.value, j ) ) {
  2876. urlConfigHtml += "<option value='" + escapeText( j ) + "'" +
  2877. ( config[ val.id ] === j ?
  2878. ( selection = true ) && " selected='selected'" : "" ) +
  2879. ">" + escapeText( val.value[ j ] ) + "</option>";
  2880. }
  2881. }
  2882. }
  2883. if ( config[ val.id ] && !selection ) {
  2884. escaped = escapeText( config[ val.id ] );
  2885. urlConfigHtml += "<option value='" + escaped +
  2886. "' selected='selected' disabled='disabled'>" + escaped + "</option>";
  2887. }
  2888. urlConfigHtml += "</select>";
  2889. }
  2890. }
  2891. return urlConfigHtml;
  2892. }
  2893. // Handle "click" events on toolbar checkboxes and "change" for select menus.
  2894. // Updates the URL with the new state of `config.urlConfig` values.
  2895. function toolbarChanged() {
  2896. var updatedUrl, value,
  2897. field = this,
  2898. params = {};
  2899. // Detect if field is a select menu or a checkbox
  2900. if ( "selectedIndex" in field ) {
  2901. value = field.options[ field.selectedIndex ].value || undefined;
  2902. } else {
  2903. value = field.checked ? ( field.defaultValue || true ) : undefined;
  2904. }
  2905. params[ field.name ] = value;
  2906. updatedUrl = setUrl( params );
  2907. if ( "hidepassed" === field.name && "replaceState" in window.history ) {
  2908. config[ field.name ] = value || false;
  2909. if ( value ) {
  2910. addClass( id( "qunit-tests" ), "hidepass" );
  2911. } else {
  2912. removeClass( id( "qunit-tests" ), "hidepass" );
  2913. }
  2914. // It is not necessary to refresh the whole page
  2915. window.history.replaceState( null, "", updatedUrl );
  2916. } else {
  2917. window.location = updatedUrl;
  2918. }
  2919. }
  2920. function setUrl( params ) {
  2921. var key,
  2922. querystring = "?";
  2923. params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params );
  2924. for ( key in params ) {
  2925. if ( hasOwn.call( params, key ) ) {
  2926. if ( params[ key ] === undefined ) {
  2927. continue;
  2928. }
  2929. querystring += encodeURIComponent( key );
  2930. if ( params[ key ] !== true ) {
  2931. querystring += "=" + encodeURIComponent( params[ key ] );
  2932. }
  2933. querystring += "&";
  2934. }
  2935. }
  2936. return location.protocol + "//" + location.host +
  2937. location.pathname + querystring.slice( 0, -1 );
  2938. }
  2939. function applyUrlParams() {
  2940. var selectedModule,
  2941. modulesList = id( "qunit-modulefilter" ),
  2942. filter = id( "qunit-filter-input" ).value;
  2943. selectedModule = modulesList ?
  2944. decodeURIComponent( modulesList.options[ modulesList.selectedIndex ].value ) :
  2945. undefined;
  2946. window.location = setUrl({
  2947. module: ( selectedModule === "" ) ? undefined : selectedModule,
  2948. filter: ( filter === "" ) ? undefined : filter,
  2949. // Remove testId filter
  2950. testId: undefined
  2951. });
  2952. }
  2953. function toolbarUrlConfigContainer() {
  2954. var urlConfigContainer = document.createElement( "span" );
  2955. urlConfigContainer.innerHTML = getUrlConfigHtml();
  2956. addClass( urlConfigContainer, "qunit-url-config" );
  2957. // For oldIE support:
  2958. // * Add handlers to the individual elements instead of the container
  2959. // * Use "click" instead of "change" for checkboxes
  2960. addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", toolbarChanged );
  2961. addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", toolbarChanged );
  2962. return urlConfigContainer;
  2963. }
  2964. function toolbarLooseFilter() {
  2965. var filter = document.createElement( "form" ),
  2966. label = document.createElement( "label" ),
  2967. input = document.createElement( "input" ),
  2968. button = document.createElement( "button" );
  2969. addClass( filter, "qunit-filter" );
  2970. label.innerHTML = "Filter: ";
  2971. input.type = "text";
  2972. input.value = config.filter || "";
  2973. input.name = "filter";
  2974. input.id = "qunit-filter-input";
  2975. button.innerHTML = "Go";
  2976. label.appendChild( input );
  2977. filter.appendChild( label );
  2978. filter.appendChild( button );
  2979. addEvent( filter, "submit", function( ev ) {
  2980. applyUrlParams();
  2981. if ( ev && ev.preventDefault ) {
  2982. ev.preventDefault();
  2983. }
  2984. return false;
  2985. });
  2986. return filter;
  2987. }
  2988. function toolbarModuleFilterHtml() {
  2989. var i,
  2990. moduleFilterHtml = "";
  2991. if ( !modulesList.length ) {
  2992. return false;
  2993. }
  2994. modulesList.sort(function( a, b ) {
  2995. return a.localeCompare( b );
  2996. });
  2997. moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label>" +
  2998. "<select id='qunit-modulefilter' name='modulefilter'><option value='' " +
  2999. ( QUnit.urlParams.module === undefined ? "selected='selected'" : "" ) +
  3000. ">< All Modules ></option>";
  3001. for ( i = 0; i < modulesList.length; i++ ) {
  3002. moduleFilterHtml += "<option value='" +
  3003. escapeText( encodeURIComponent( modulesList[ i ] ) ) + "' " +
  3004. ( QUnit.urlParams.module === modulesList[ i ] ? "selected='selected'" : "" ) +
  3005. ">" + escapeText( modulesList[ i ] ) + "</option>";
  3006. }
  3007. moduleFilterHtml += "</select>";
  3008. return moduleFilterHtml;
  3009. }
  3010. function toolbarModuleFilter() {
  3011. var toolbar = id( "qunit-testrunner-toolbar" ),
  3012. moduleFilter = document.createElement( "span" ),
  3013. moduleFilterHtml = toolbarModuleFilterHtml();
  3014. if ( !toolbar || !moduleFilterHtml ) {
  3015. return false;
  3016. }
  3017. moduleFilter.setAttribute( "id", "qunit-modulefilter-container" );
  3018. moduleFilter.innerHTML = moduleFilterHtml;
  3019. addEvent( moduleFilter.lastChild, "change", applyUrlParams );
  3020. toolbar.appendChild( moduleFilter );
  3021. }
  3022. function appendToolbar() {
  3023. var toolbar = id( "qunit-testrunner-toolbar" );
  3024. if ( toolbar ) {
  3025. toolbar.appendChild( toolbarUrlConfigContainer() );
  3026. toolbar.appendChild( toolbarLooseFilter() );
  3027. }
  3028. }
  3029. function appendHeader() {
  3030. var header = id( "qunit-header" );
  3031. if ( header ) {
  3032. header.innerHTML = "<a href='" +
  3033. setUrl({ filter: undefined, module: undefined, testId: undefined }) +
  3034. "'>" + header.innerHTML + "</a> ";
  3035. }
  3036. }
  3037. function appendBanner() {
  3038. var banner = id( "qunit-banner" );
  3039. if ( banner ) {
  3040. banner.className = "";
  3041. }
  3042. }
  3043. function appendTestResults() {
  3044. var tests = id( "qunit-tests" ),
  3045. result = id( "qunit-testresult" );
  3046. if ( result ) {
  3047. result.parentNode.removeChild( result );
  3048. }
  3049. if ( tests ) {
  3050. tests.innerHTML = "";
  3051. result = document.createElement( "p" );
  3052. result.id = "qunit-testresult";
  3053. result.className = "result";
  3054. tests.parentNode.insertBefore( result, tests );
  3055. result.innerHTML = "Running...<br />&#160;";
  3056. }
  3057. }
  3058. function storeFixture() {
  3059. var fixture = id( "qunit-fixture" );
  3060. if ( fixture ) {
  3061. config.fixture = fixture.innerHTML;
  3062. }
  3063. }
  3064. function appendUserAgent() {
  3065. var userAgent = id( "qunit-userAgent" );
  3066. if ( userAgent ) {
  3067. userAgent.innerHTML = "";
  3068. userAgent.appendChild(
  3069. document.createTextNode(
  3070. "QUnit " + QUnit.version + "; " + navigator.userAgent
  3071. )
  3072. );
  3073. }
  3074. }
  3075. function appendTestsList( modules ) {
  3076. var i, l, x, z, test, moduleObj;
  3077. for ( i = 0, l = modules.length; i < l; i++ ) {
  3078. moduleObj = modules[ i ];
  3079. if ( moduleObj.name ) {
  3080. modulesList.push( moduleObj.name );
  3081. }
  3082. for ( x = 0, z = moduleObj.tests.length; x < z; x++ ) {
  3083. test = moduleObj.tests[ x ];
  3084. appendTest( test.name, test.testId, moduleObj.name );
  3085. }
  3086. }
  3087. }
  3088. function appendTest( name, testId, moduleName ) {
  3089. var title, rerunTrigger, testBlock, assertList,
  3090. tests = id( "qunit-tests" );
  3091. if ( !tests ) {
  3092. return;
  3093. }
  3094. title = document.createElement( "strong" );
  3095. title.innerHTML = getNameHtml( name, moduleName );
  3096. rerunTrigger = document.createElement( "a" );
  3097. rerunTrigger.innerHTML = "Rerun";
  3098. rerunTrigger.href = setUrl({ testId: testId });
  3099. testBlock = document.createElement( "li" );
  3100. testBlock.appendChild( title );
  3101. testBlock.appendChild( rerunTrigger );
  3102. testBlock.id = "qunit-test-output-" + testId;
  3103. assertList = document.createElement( "ol" );
  3104. assertList.className = "qunit-assert-list";
  3105. testBlock.appendChild( assertList );
  3106. tests.appendChild( testBlock );
  3107. }
  3108. // HTML Reporter initialization and load
  3109. QUnit.begin(function( details ) {
  3110. var qunit = id( "qunit" );
  3111. // Fixture is the only one necessary to run without the #qunit element
  3112. storeFixture();
  3113. if ( qunit ) {
  3114. qunit.innerHTML =
  3115. "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" +
  3116. "<h2 id='qunit-banner'></h2>" +
  3117. "<div id='qunit-testrunner-toolbar'></div>" +
  3118. "<h2 id='qunit-userAgent'></h2>" +
  3119. "<ol id='qunit-tests'></ol>";
  3120. }
  3121. appendHeader();
  3122. appendBanner();
  3123. appendTestResults();
  3124. appendUserAgent();
  3125. appendToolbar();
  3126. appendTestsList( details.modules );
  3127. toolbarModuleFilter();
  3128. if ( qunit && config.hidepassed ) {
  3129. addClass( qunit.lastChild, "hidepass" );
  3130. }
  3131. });
  3132. QUnit.done(function( details ) {
  3133. var i, key,
  3134. banner = id( "qunit-banner" ),
  3135. tests = id( "qunit-tests" ),
  3136. html = [
  3137. "Tests completed in ",
  3138. details.runtime,
  3139. " milliseconds.<br />",
  3140. "<span class='passed'>",
  3141. details.passed,
  3142. "</span> assertions of <span class='total'>",
  3143. details.total,
  3144. "</span> passed, <span class='failed'>",
  3145. details.failed,
  3146. "</span> failed."
  3147. ].join( "" );
  3148. if ( banner ) {
  3149. banner.className = details.failed ? "qunit-fail" : "qunit-pass";
  3150. }
  3151. if ( tests ) {
  3152. id( "qunit-testresult" ).innerHTML = html;
  3153. }
  3154. if ( config.altertitle && defined.document && document.title ) {
  3155. // show ✖ for good, ✔ for bad suite result in title
  3156. // use escape sequences in case file gets loaded with non-utf-8-charset
  3157. document.title = [
  3158. ( details.failed ? "\u2716" : "\u2714" ),
  3159. document.title.replace( /^[\u2714\u2716] /i, "" )
  3160. ].join( " " );
  3161. }
  3162. // clear own sessionStorage items if all tests passed
  3163. if ( config.reorder && defined.sessionStorage && details.failed === 0 ) {
  3164. for ( i = 0; i < sessionStorage.length; i++ ) {
  3165. key = sessionStorage.key( i++ );
  3166. if ( key.indexOf( "qunit-test-" ) === 0 ) {
  3167. sessionStorage.removeItem( key );
  3168. }
  3169. }
  3170. }
  3171. // scroll back to top to show results
  3172. if ( config.scrolltop && window.scrollTo ) {
  3173. window.scrollTo( 0, 0 );
  3174. }
  3175. });
  3176. function getNameHtml( name, module ) {
  3177. var nameHtml = "";
  3178. if ( module ) {
  3179. nameHtml = "<span class='module-name'>" + escapeText( module ) + "</span>: ";
  3180. }
  3181. nameHtml += "<span class='test-name'>" + escapeText( name ) + "</span>";
  3182. return nameHtml;
  3183. }
  3184. QUnit.testStart(function( details ) {
  3185. var running, testBlock, bad;
  3186. testBlock = id( "qunit-test-output-" + details.testId );
  3187. if ( testBlock ) {
  3188. testBlock.className = "running";
  3189. } else {
  3190. // Report later registered tests
  3191. appendTest( details.name, details.testId, details.module );
  3192. }
  3193. running = id( "qunit-testresult" );
  3194. if ( running ) {
  3195. bad = QUnit.config.reorder && defined.sessionStorage &&
  3196. +sessionStorage.getItem( "qunit-test-" + details.module + "-" + details.name );
  3197. running.innerHTML = ( bad ?
  3198. "Rerunning previously failed test: <br />" :
  3199. "Running: <br />" ) +
  3200. getNameHtml( details.name, details.module );
  3201. }
  3202. });
  3203. QUnit.log(function( details ) {
  3204. var assertList, assertLi,
  3205. message, expected, actual,
  3206. testItem = id( "qunit-test-output-" + details.testId );
  3207. if ( !testItem ) {
  3208. return;
  3209. }
  3210. message = escapeText( details.message ) || ( details.result ? "okay" : "failed" );
  3211. message = "<span class='test-message'>" + message + "</span>";
  3212. message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
  3213. // pushFailure doesn't provide details.expected
  3214. // when it calls, it's implicit to also not show expected and diff stuff
  3215. // Also, we need to check details.expected existence, as it can exist and be undefined
  3216. if ( !details.result && hasOwn.call( details, "expected" ) ) {
  3217. expected = escapeText( QUnit.dump.parse( details.expected ) );
  3218. actual = escapeText( QUnit.dump.parse( details.actual ) );
  3219. message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" +
  3220. expected +
  3221. "</pre></td></tr>";
  3222. if ( actual !== expected ) {
  3223. message += "<tr class='test-actual'><th>Result: </th><td><pre>" +
  3224. actual + "</pre></td></tr>" +
  3225. "<tr class='test-diff'><th>Diff: </th><td><pre>" +
  3226. QUnit.diff( expected, actual ) + "</pre></td></tr>";
  3227. } else {
  3228. if ( expected.indexOf( "[object Array]" ) !== -1 ||
  3229. expected.indexOf( "[object Object]" ) !== -1 ) {
  3230. message += "<tr class='test-message'><th>Message: </th><td>" +
  3231. "Diff suppressed as the depth of object is more than current max depth (" +
  3232. QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " +
  3233. " run with a higher max depth or <a href='" + setUrl({ maxDepth: -1 }) + "'>" +
  3234. "Rerun</a> without max depth.</p></td></tr>";
  3235. }
  3236. }
  3237. if ( details.source ) {
  3238. message += "<tr class='test-source'><th>Source: </th><td><pre>" +
  3239. escapeText( details.source ) + "</pre></td></tr>";
  3240. }
  3241. message += "</table>";
  3242. // this occours when pushFailure is set and we have an extracted stack trace
  3243. } else if ( !details.result && details.source ) {
  3244. message += "<table>" +
  3245. "<tr class='test-source'><th>Source: </th><td><pre>" +
  3246. escapeText( details.source ) + "</pre></td></tr>" +
  3247. "</table>";
  3248. }
  3249. assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
  3250. assertLi = document.createElement( "li" );
  3251. assertLi.className = details.result ? "pass" : "fail";
  3252. assertLi.innerHTML = message;
  3253. assertList.appendChild( assertLi );
  3254. });
  3255. QUnit.testDone(function( details ) {
  3256. var testTitle, time, testItem, assertList,
  3257. good, bad, testCounts, skipped,
  3258. tests = id( "qunit-tests" );
  3259. if ( !tests ) {
  3260. return;
  3261. }
  3262. testItem = id( "qunit-test-output-" + details.testId );
  3263. assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
  3264. good = details.passed;
  3265. bad = details.failed;
  3266. // store result when possible
  3267. if ( config.reorder && defined.sessionStorage ) {
  3268. if ( bad ) {
  3269. sessionStorage.setItem( "qunit-test-" + details.module + "-" + details.name, bad );
  3270. } else {
  3271. sessionStorage.removeItem( "qunit-test-" + details.module + "-" + details.name );
  3272. }
  3273. }
  3274. if ( bad === 0 ) {
  3275. addClass( assertList, "qunit-collapsed" );
  3276. }
  3277. // testItem.firstChild is the test name
  3278. testTitle = testItem.firstChild;
  3279. testCounts = bad ?
  3280. "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " :
  3281. "";
  3282. testTitle.innerHTML += " <b class='counts'>(" + testCounts +
  3283. details.assertions.length + ")</b>";
  3284. if ( details.skipped ) {
  3285. testItem.className = "skipped";
  3286. skipped = document.createElement( "em" );
  3287. skipped.className = "qunit-skipped-label";
  3288. skipped.innerHTML = "skipped";
  3289. testItem.insertBefore( skipped, testTitle );
  3290. } else {
  3291. addEvent( testTitle, "click", function() {
  3292. toggleClass( assertList, "qunit-collapsed" );
  3293. });
  3294. testItem.className = bad ? "fail" : "pass";
  3295. time = document.createElement( "span" );
  3296. time.className = "runtime";
  3297. time.innerHTML = details.runtime + " ms";
  3298. testItem.insertBefore( time, assertList );
  3299. }
  3300. });
  3301. if ( defined.document ) {
  3302. if ( document.readyState === "complete" ) {
  3303. QUnit.load();
  3304. } else {
  3305. addEvent( window, "load", QUnit.load );
  3306. }
  3307. } else {
  3308. config.pageLoaded = true;
  3309. config.autorun = true;
  3310. }
  3311. })();