testharness.js 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908
  1. /*global self*/
  2. /*jshint latedef: nofunc*/
  3. /* Documentation: https://web-platform-tests.org/writing-tests/testharness-api.html
  4. * (../docs/_writing-tests/testharness-api.md) */
  5. (function (global_scope)
  6. {
  7. // default timeout is 10 seconds, test can override if needed
  8. var settings = {
  9. output:true,
  10. harness_timeout:{
  11. "normal":10000,
  12. "long":60000
  13. },
  14. test_timeout:null,
  15. message_events: ["start", "test_state", "result", "completion"],
  16. debug: false,
  17. };
  18. var xhtml_ns = "http://www.w3.org/1999/xhtml";
  19. /*
  20. * TestEnvironment is an abstraction for the environment in which the test
  21. * harness is used. Each implementation of a test environment has to provide
  22. * the following interface:
  23. *
  24. * interface TestEnvironment {
  25. * // Invoked after the global 'tests' object has been created and it's
  26. * // safe to call add_*_callback() to register event handlers.
  27. * void on_tests_ready();
  28. *
  29. * // Invoked after setup() has been called to notify the test environment
  30. * // of changes to the test harness properties.
  31. * void on_new_harness_properties(object properties);
  32. *
  33. * // Should return a new unique default test name.
  34. * DOMString next_default_test_name();
  35. *
  36. * // Should return the test harness timeout duration in milliseconds.
  37. * float test_timeout();
  38. * };
  39. */
  40. /*
  41. * A test environment with a DOM. The global object is 'window'. By default
  42. * test results are displayed in a table. Any parent windows receive
  43. * callbacks or messages via postMessage() when test events occur. See
  44. * apisample11.html and apisample12.html.
  45. */
  46. function WindowTestEnvironment() {
  47. this.name_counter = 0;
  48. this.window_cache = null;
  49. this.output_handler = null;
  50. this.all_loaded = false;
  51. var this_obj = this;
  52. this.message_events = [];
  53. this.dispatched_messages = [];
  54. this.message_functions = {
  55. start: [add_start_callback, remove_start_callback,
  56. function (properties) {
  57. this_obj._dispatch("start_callback", [properties],
  58. {type: "start", properties: properties});
  59. }],
  60. test_state: [add_test_state_callback, remove_test_state_callback,
  61. function(test) {
  62. this_obj._dispatch("test_state_callback", [test],
  63. {type: "test_state",
  64. test: test.structured_clone()});
  65. }],
  66. result: [add_result_callback, remove_result_callback,
  67. function (test) {
  68. this_obj.output_handler.show_status();
  69. this_obj._dispatch("result_callback", [test],
  70. {type: "result",
  71. test: test.structured_clone()});
  72. }],
  73. completion: [add_completion_callback, remove_completion_callback,
  74. function (tests, harness_status, asserts) {
  75. var cloned_tests = map(tests, function(test) {
  76. return test.structured_clone();
  77. });
  78. this_obj._dispatch("completion_callback", [tests, harness_status],
  79. {type: "complete",
  80. tests: cloned_tests,
  81. status: harness_status.structured_clone(),
  82. asserts: asserts.map(assert => assert.structured_clone())});
  83. }]
  84. }
  85. on_event(window, 'load', function() {
  86. this_obj.all_loaded = true;
  87. });
  88. on_event(window, 'message', function(event) {
  89. if (event.data && event.data.type === "getmessages" && event.source) {
  90. // A window can post "getmessages" to receive a duplicate of every
  91. // message posted by this environment so far. This allows subscribers
  92. // from fetch_tests_from_window to 'catch up' to the current state of
  93. // this environment.
  94. for (var i = 0; i < this_obj.dispatched_messages.length; ++i)
  95. {
  96. event.source.postMessage(this_obj.dispatched_messages[i], "*");
  97. }
  98. }
  99. });
  100. }
  101. WindowTestEnvironment.prototype._dispatch = function(selector, callback_args, message_arg) {
  102. this.dispatched_messages.push(message_arg);
  103. this._forEach_windows(
  104. function(w, same_origin) {
  105. if (same_origin) {
  106. try {
  107. var has_selector = selector in w;
  108. } catch(e) {
  109. // If document.domain was set at some point same_origin can be
  110. // wrong and the above will fail.
  111. has_selector = false;
  112. }
  113. if (has_selector) {
  114. try {
  115. w[selector].apply(undefined, callback_args);
  116. } catch (e) {}
  117. }
  118. }
  119. if (w !== self) {
  120. w.postMessage(message_arg, "*");
  121. }
  122. });
  123. };
  124. WindowTestEnvironment.prototype._forEach_windows = function(callback) {
  125. // Iterate over the windows [self ... top, opener]. The callback is passed
  126. // two objects, the first one is the window object itself, the second one
  127. // is a boolean indicating whether or not it's on the same origin as the
  128. // current window.
  129. var cache = this.window_cache;
  130. if (!cache) {
  131. cache = [[self, true]];
  132. var w = self;
  133. var i = 0;
  134. var so;
  135. while (w != w.parent) {
  136. w = w.parent;
  137. so = is_same_origin(w);
  138. cache.push([w, so]);
  139. i++;
  140. }
  141. w = window.opener;
  142. if (w) {
  143. cache.push([w, is_same_origin(w)]);
  144. }
  145. this.window_cache = cache;
  146. }
  147. forEach(cache,
  148. function(a) {
  149. callback.apply(null, a);
  150. });
  151. };
  152. WindowTestEnvironment.prototype.on_tests_ready = function() {
  153. var output = new Output();
  154. this.output_handler = output;
  155. var this_obj = this;
  156. add_start_callback(function (properties) {
  157. this_obj.output_handler.init(properties);
  158. });
  159. add_test_state_callback(function(test) {
  160. this_obj.output_handler.show_status();
  161. });
  162. add_result_callback(function (test) {
  163. this_obj.output_handler.show_status();
  164. });
  165. add_completion_callback(function (tests, harness_status, asserts_run) {
  166. this_obj.output_handler.show_results(tests, harness_status, asserts_run);
  167. });
  168. this.setup_messages(settings.message_events);
  169. };
  170. WindowTestEnvironment.prototype.setup_messages = function(new_events) {
  171. var this_obj = this;
  172. forEach(settings.message_events, function(x) {
  173. var current_dispatch = this_obj.message_events.indexOf(x) !== -1;
  174. var new_dispatch = new_events.indexOf(x) !== -1;
  175. if (!current_dispatch && new_dispatch) {
  176. this_obj.message_functions[x][0](this_obj.message_functions[x][2]);
  177. } else if (current_dispatch && !new_dispatch) {
  178. this_obj.message_functions[x][1](this_obj.message_functions[x][2]);
  179. }
  180. });
  181. this.message_events = new_events;
  182. }
  183. WindowTestEnvironment.prototype.next_default_test_name = function() {
  184. var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
  185. this.name_counter++;
  186. return get_title() + suffix;
  187. };
  188. WindowTestEnvironment.prototype.on_new_harness_properties = function(properties) {
  189. this.output_handler.setup(properties);
  190. if (properties.hasOwnProperty("message_events")) {
  191. this.setup_messages(properties.message_events);
  192. }
  193. };
  194. WindowTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
  195. on_event(window, 'load', callback);
  196. };
  197. WindowTestEnvironment.prototype.test_timeout = function() {
  198. var metas = document.getElementsByTagName("meta");
  199. for (var i = 0; i < metas.length; i++) {
  200. if (metas[i].name == "timeout") {
  201. if (metas[i].content == "long") {
  202. return settings.harness_timeout.long;
  203. }
  204. break;
  205. }
  206. }
  207. return settings.harness_timeout.normal;
  208. };
  209. /*
  210. * Base TestEnvironment implementation for a generic web worker.
  211. *
  212. * Workers accumulate test results. One or more clients can connect and
  213. * retrieve results from a worker at any time.
  214. *
  215. * WorkerTestEnvironment supports communicating with a client via a
  216. * MessagePort. The mechanism for determining the appropriate MessagePort
  217. * for communicating with a client depends on the type of worker and is
  218. * implemented by the various specializations of WorkerTestEnvironment
  219. * below.
  220. *
  221. * A client document using testharness can use fetch_tests_from_worker() to
  222. * retrieve results from a worker. See apisample16.html.
  223. */
  224. function WorkerTestEnvironment() {
  225. this.name_counter = 0;
  226. this.all_loaded = true;
  227. this.message_list = [];
  228. this.message_ports = [];
  229. }
  230. WorkerTestEnvironment.prototype._dispatch = function(message) {
  231. this.message_list.push(message);
  232. for (var i = 0; i < this.message_ports.length; ++i)
  233. {
  234. this.message_ports[i].postMessage(message);
  235. }
  236. };
  237. // The only requirement is that port has a postMessage() method. It doesn't
  238. // have to be an instance of a MessagePort, and often isn't.
  239. WorkerTestEnvironment.prototype._add_message_port = function(port) {
  240. this.message_ports.push(port);
  241. for (var i = 0; i < this.message_list.length; ++i)
  242. {
  243. port.postMessage(this.message_list[i]);
  244. }
  245. };
  246. WorkerTestEnvironment.prototype.next_default_test_name = function() {
  247. var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
  248. this.name_counter++;
  249. return get_title() + suffix;
  250. };
  251. WorkerTestEnvironment.prototype.on_new_harness_properties = function() {};
  252. WorkerTestEnvironment.prototype.on_tests_ready = function() {
  253. var this_obj = this;
  254. add_start_callback(
  255. function(properties) {
  256. this_obj._dispatch({
  257. type: "start",
  258. properties: properties,
  259. });
  260. });
  261. add_test_state_callback(
  262. function(test) {
  263. this_obj._dispatch({
  264. type: "test_state",
  265. test: test.structured_clone()
  266. });
  267. });
  268. add_result_callback(
  269. function(test) {
  270. this_obj._dispatch({
  271. type: "result",
  272. test: test.structured_clone()
  273. });
  274. });
  275. add_completion_callback(
  276. function(tests, harness_status, asserts) {
  277. this_obj._dispatch({
  278. type: "complete",
  279. tests: map(tests,
  280. function(test) {
  281. return test.structured_clone();
  282. }),
  283. status: harness_status.structured_clone(),
  284. asserts: asserts.map(assert => assert.structured_clone()),
  285. });
  286. });
  287. };
  288. WorkerTestEnvironment.prototype.add_on_loaded_callback = function() {};
  289. WorkerTestEnvironment.prototype.test_timeout = function() {
  290. // Tests running in a worker don't have a default timeout. I.e. all
  291. // worker tests behave as if settings.explicit_timeout is true.
  292. return null;
  293. };
  294. /*
  295. * Dedicated web workers.
  296. * https://html.spec.whatwg.org/multipage/workers.html#dedicatedworkerglobalscope
  297. *
  298. * This class is used as the test_environment when testharness is running
  299. * inside a dedicated worker.
  300. */
  301. function DedicatedWorkerTestEnvironment() {
  302. WorkerTestEnvironment.call(this);
  303. // self is an instance of DedicatedWorkerGlobalScope which exposes
  304. // a postMessage() method for communicating via the message channel
  305. // established when the worker is created.
  306. this._add_message_port(self);
  307. }
  308. DedicatedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
  309. DedicatedWorkerTestEnvironment.prototype.on_tests_ready = function() {
  310. WorkerTestEnvironment.prototype.on_tests_ready.call(this);
  311. // In the absence of an onload notification, we a require dedicated
  312. // workers to explicitly signal when the tests are done.
  313. tests.wait_for_finish = true;
  314. };
  315. /*
  316. * Shared web workers.
  317. * https://html.spec.whatwg.org/multipage/workers.html#sharedworkerglobalscope
  318. *
  319. * This class is used as the test_environment when testharness is running
  320. * inside a shared web worker.
  321. */
  322. function SharedWorkerTestEnvironment() {
  323. WorkerTestEnvironment.call(this);
  324. var this_obj = this;
  325. // Shared workers receive message ports via the 'onconnect' event for
  326. // each connection.
  327. self.addEventListener("connect",
  328. function(message_event) {
  329. this_obj._add_message_port(message_event.source);
  330. }, false);
  331. }
  332. SharedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
  333. SharedWorkerTestEnvironment.prototype.on_tests_ready = function() {
  334. WorkerTestEnvironment.prototype.on_tests_ready.call(this);
  335. // In the absence of an onload notification, we a require shared
  336. // workers to explicitly signal when the tests are done.
  337. tests.wait_for_finish = true;
  338. };
  339. /*
  340. * Service workers.
  341. * http://www.w3.org/TR/service-workers/
  342. *
  343. * This class is used as the test_environment when testharness is running
  344. * inside a service worker.
  345. */
  346. function ServiceWorkerTestEnvironment() {
  347. WorkerTestEnvironment.call(this);
  348. this.all_loaded = false;
  349. this.on_loaded_callback = null;
  350. var this_obj = this;
  351. self.addEventListener("message",
  352. function(event) {
  353. if (event.data && event.data.type && event.data.type === "connect") {
  354. this_obj._add_message_port(event.source);
  355. }
  356. }, false);
  357. // The oninstall event is received after the service worker script and
  358. // all imported scripts have been fetched and executed. It's the
  359. // equivalent of an onload event for a document. All tests should have
  360. // been added by the time this event is received, thus it's not
  361. // necessary to wait until the onactivate event. However, tests for
  362. // installed service workers need another event which is equivalent to
  363. // the onload event because oninstall is fired only on installation. The
  364. // onmessage event is used for that purpose since tests using
  365. // testharness.js should ask the result to its service worker by
  366. // PostMessage. If the onmessage event is triggered on the service
  367. // worker's context, that means the worker's script has been evaluated.
  368. on_event(self, "install", on_all_loaded);
  369. on_event(self, "message", on_all_loaded);
  370. function on_all_loaded() {
  371. if (this_obj.all_loaded)
  372. return;
  373. this_obj.all_loaded = true;
  374. if (this_obj.on_loaded_callback) {
  375. this_obj.on_loaded_callback();
  376. }
  377. }
  378. }
  379. ServiceWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
  380. ServiceWorkerTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
  381. if (this.all_loaded) {
  382. callback();
  383. } else {
  384. this.on_loaded_callback = callback;
  385. }
  386. };
  387. /*
  388. * Shadow realms.
  389. * https://github.com/tc39/proposal-shadowrealm
  390. *
  391. * This class is used as the test_environment when testharness is running
  392. * inside a shadow realm.
  393. */
  394. function ShadowRealmTestEnvironment() {
  395. WorkerTestEnvironment.call(this);
  396. this.all_loaded = false;
  397. this.on_loaded_callback = null;
  398. }
  399. ShadowRealmTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
  400. /**
  401. * Signal to the test environment that the tests are ready and the on-loaded
  402. * callback should be run.
  403. *
  404. * Shadow realms are not *really* a DOM context: they have no `onload` or similar
  405. * event for us to use to set up the test environment; so, instead, this method
  406. * is manually triggered from the incubating realm
  407. *
  408. * @param {Function} message_destination - a function that receives JSON-serializable
  409. * data to send to the incubating realm, in the same format as used by RemoteContext
  410. */
  411. ShadowRealmTestEnvironment.prototype.begin = function(message_destination) {
  412. if (this.all_loaded) {
  413. throw new Error("Tried to start a shadow realm test environment after it has already started");
  414. }
  415. var fakeMessagePort = {};
  416. fakeMessagePort.postMessage = message_destination;
  417. this._add_message_port(fakeMessagePort);
  418. this.all_loaded = true;
  419. if (this.on_loaded_callback) {
  420. this.on_loaded_callback();
  421. }
  422. };
  423. ShadowRealmTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
  424. if (this.all_loaded) {
  425. callback();
  426. } else {
  427. this.on_loaded_callback = callback;
  428. }
  429. };
  430. /*
  431. * JavaScript shells.
  432. *
  433. * This class is used as the test_environment when testharness is running
  434. * inside a JavaScript shell.
  435. */
  436. function ShellTestEnvironment() {
  437. this.name_counter = 0;
  438. this.all_loaded = false;
  439. this.on_loaded_callback = null;
  440. Promise.resolve().then(function() {
  441. this.all_loaded = true
  442. if (this.on_loaded_callback) {
  443. this.on_loaded_callback();
  444. }
  445. }.bind(this));
  446. this.message_list = [];
  447. this.message_ports = [];
  448. }
  449. ShellTestEnvironment.prototype.next_default_test_name = function() {
  450. var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
  451. this.name_counter++;
  452. return "Untitled" + suffix;
  453. };
  454. ShellTestEnvironment.prototype.on_new_harness_properties = function() {};
  455. ShellTestEnvironment.prototype.on_tests_ready = function() {};
  456. ShellTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
  457. if (this.all_loaded) {
  458. callback();
  459. } else {
  460. this.on_loaded_callback = callback;
  461. }
  462. };
  463. ShellTestEnvironment.prototype.test_timeout = function() {
  464. // Tests running in a shell don't have a default timeout, so behave as
  465. // if settings.explicit_timeout is true.
  466. return null;
  467. };
  468. function create_test_environment() {
  469. if ('document' in global_scope) {
  470. return new WindowTestEnvironment();
  471. }
  472. if ('DedicatedWorkerGlobalScope' in global_scope &&
  473. global_scope instanceof DedicatedWorkerGlobalScope) {
  474. return new DedicatedWorkerTestEnvironment();
  475. }
  476. if ('SharedWorkerGlobalScope' in global_scope &&
  477. global_scope instanceof SharedWorkerGlobalScope) {
  478. return new SharedWorkerTestEnvironment();
  479. }
  480. if ('ServiceWorkerGlobalScope' in global_scope &&
  481. global_scope instanceof ServiceWorkerGlobalScope) {
  482. return new ServiceWorkerTestEnvironment();
  483. }
  484. if ('WorkerGlobalScope' in global_scope &&
  485. global_scope instanceof WorkerGlobalScope) {
  486. return new DedicatedWorkerTestEnvironment();
  487. }
  488. /* Shadow realm global objects are _ordinary_ objects (i.e. their prototype is
  489. * Object) so we don't have a nice `instanceof` test to use; instead, we
  490. * check if the there is a GLOBAL.isShadowRealm() property
  491. * on the global object. that was set by the test harness when it
  492. * created the ShadowRealm.
  493. */
  494. if (global_scope.GLOBAL && global_scope.GLOBAL.isShadowRealm()) {
  495. return new ShadowRealmTestEnvironment();
  496. }
  497. return new ShellTestEnvironment();
  498. }
  499. var test_environment = create_test_environment();
  500. function is_shared_worker(worker) {
  501. return 'SharedWorker' in global_scope && worker instanceof SharedWorker;
  502. }
  503. function is_service_worker(worker) {
  504. // The worker object may be from another execution context,
  505. // so do not use instanceof here.
  506. return 'ServiceWorker' in global_scope &&
  507. Object.prototype.toString.call(worker) == '[object ServiceWorker]';
  508. }
  509. var seen_func_name = Object.create(null);
  510. function get_test_name(func, name)
  511. {
  512. if (name) {
  513. return name;
  514. }
  515. if (func) {
  516. var func_code = func.toString();
  517. // Try and match with brackets, but fallback to matching without
  518. var arrow = func_code.match(/^\(\)\s*=>\s*(?:{(.*)}\s*|(.*))$/);
  519. // Check for JS line separators
  520. if (arrow !== null && !/[\u000A\u000D\u2028\u2029]/.test(func_code)) {
  521. var trimmed = (arrow[1] !== undefined ? arrow[1] : arrow[2]).trim();
  522. // drop trailing ; if there's no earlier ones
  523. trimmed = trimmed.replace(/^([^;]*)(;\s*)+$/, "$1");
  524. if (trimmed) {
  525. let name = trimmed;
  526. if (seen_func_name[trimmed]) {
  527. // This subtest name already exists, so add a suffix.
  528. name += " " + seen_func_name[trimmed];
  529. } else {
  530. seen_func_name[trimmed] = 0;
  531. }
  532. seen_func_name[trimmed] += 1;
  533. return name;
  534. }
  535. }
  536. }
  537. return test_environment.next_default_test_name();
  538. }
  539. /**
  540. * @callback TestFunction
  541. * @param {Test} test - The test currnetly being run.
  542. * @param {Any[]} args - Additional args to pass to function.
  543. *
  544. */
  545. /**
  546. * Create a synchronous test
  547. *
  548. * @param {TestFunction} func - Test function. This is executed
  549. * immediately. If it returns without error, the test status is
  550. * set to ``PASS``. If it throws an :js:class:`AssertionError`, or
  551. * any other exception, the test status is set to ``FAIL``
  552. * (typically from an `assert` function).
  553. * @param {String} name - Test name. This must be unique in a
  554. * given file and must be invariant between runs.
  555. */
  556. function test(func, name, properties)
  557. {
  558. if (tests.promise_setup_called) {
  559. tests.status.status = tests.status.ERROR;
  560. tests.status.message = '`test` invoked after `promise_setup`';
  561. tests.complete();
  562. }
  563. var test_name = get_test_name(func, name);
  564. var test_obj = new Test(test_name, properties);
  565. var value = test_obj.step(func, test_obj, test_obj);
  566. if (value !== undefined) {
  567. var msg = 'Test named "' + test_name +
  568. '" passed a function to `test` that returned a value.';
  569. try {
  570. if (value && typeof value.then === 'function') {
  571. msg += ' Consider using `promise_test` instead when ' +
  572. 'using Promises or async/await.';
  573. }
  574. } catch (err) {}
  575. tests.status.status = tests.status.ERROR;
  576. tests.status.message = msg;
  577. }
  578. if (test_obj.phase === test_obj.phases.STARTED) {
  579. test_obj.done();
  580. }
  581. }
  582. /**
  583. * Create an asynchronous test
  584. *
  585. * @param {TestFunction|string} funcOrName - Initial step function
  586. * to call immediately with the test name as an argument (if any),
  587. * or name of the test.
  588. * @param {String} name - Test name (if a test function was
  589. * provided). This must be unique in a given file and must be
  590. * invariant between runs.
  591. * @returns {Test} An object representing the ongoing test.
  592. */
  593. function async_test(func, name, properties)
  594. {
  595. if (tests.promise_setup_called) {
  596. tests.status.status = tests.status.ERROR;
  597. tests.status.message = '`async_test` invoked after `promise_setup`';
  598. tests.complete();
  599. }
  600. if (typeof func !== "function") {
  601. properties = name;
  602. name = func;
  603. func = null;
  604. }
  605. var test_name = get_test_name(func, name);
  606. var test_obj = new Test(test_name, properties);
  607. if (func) {
  608. var value = test_obj.step(func, test_obj, test_obj);
  609. // Test authors sometimes return values to async_test, expecting us
  610. // to handle the value somehow. Make doing so a harness error to be
  611. // clear this is invalid, and point authors to promise_test if it
  612. // may be appropriate.
  613. //
  614. // Note that we only perform this check on the initial function
  615. // passed to async_test, not on any later steps - we haven't seen a
  616. // consistent problem with those (and it's harder to check).
  617. if (value !== undefined) {
  618. var msg = 'Test named "' + test_name +
  619. '" passed a function to `async_test` that returned a value.';
  620. try {
  621. if (value && typeof value.then === 'function') {
  622. msg += ' Consider using `promise_test` instead when ' +
  623. 'using Promises or async/await.';
  624. }
  625. } catch (err) {}
  626. tests.set_status(tests.status.ERROR, msg);
  627. tests.complete();
  628. }
  629. }
  630. return test_obj;
  631. }
  632. /**
  633. * Create a promise test.
  634. *
  635. * Promise tests are tests which are represented by a promise
  636. * object. If the promise is fulfilled the test passes, if it's
  637. * rejected the test fails, otherwise the test passes.
  638. *
  639. * @param {TestFunction} func - Test function. This must return a
  640. * promise. The test is automatically marked as complete once the
  641. * promise settles.
  642. * @param {String} name - Test name. This must be unique in a
  643. * given file and must be invariant between runs.
  644. */
  645. function promise_test(func, name, properties) {
  646. if (typeof func !== "function") {
  647. properties = name;
  648. name = func;
  649. func = null;
  650. }
  651. var test_name = get_test_name(func, name);
  652. var test = new Test(test_name, properties);
  653. test._is_promise_test = true;
  654. // If there is no promise tests queue make one.
  655. if (!tests.promise_tests) {
  656. tests.promise_tests = Promise.resolve();
  657. }
  658. tests.promise_tests = tests.promise_tests.then(function() {
  659. return new Promise(function(resolve) {
  660. var promise = test.step(func, test, test);
  661. test.step(function() {
  662. assert(!!promise, "promise_test", null,
  663. "test body must return a 'thenable' object (received ${value})",
  664. {value:promise});
  665. assert(typeof promise.then === "function", "promise_test", null,
  666. "test body must return a 'thenable' object (received an object with no `then` method)",
  667. null);
  668. });
  669. // Test authors may use the `step` method within a
  670. // `promise_test` even though this reflects a mixture of
  671. // asynchronous control flow paradigms. The "done" callback
  672. // should be registered prior to the resolution of the
  673. // user-provided Promise to avoid timeouts in cases where the
  674. // Promise does not settle but a `step` function has thrown an
  675. // error.
  676. add_test_done_callback(test, resolve);
  677. Promise.resolve(promise)
  678. .catch(test.step_func(
  679. function(value) {
  680. if (value instanceof AssertionError) {
  681. throw value;
  682. }
  683. assert(false, "promise_test", null,
  684. "Unhandled rejection with value: ${value}", {value:value});
  685. }))
  686. .then(function() {
  687. test.done();
  688. });
  689. });
  690. });
  691. }
  692. /**
  693. * Make a copy of a Promise in the current realm.
  694. *
  695. * @param {Promise} promise the given promise that may be from a different
  696. * realm
  697. * @returns {Promise}
  698. *
  699. * An arbitrary promise provided by the caller may have originated
  700. * in another frame that have since navigated away, rendering the
  701. * frame's document inactive. Such a promise cannot be used with
  702. * `await` or Promise.resolve(), as microtasks associated with it
  703. * may be prevented from being run. See `issue
  704. * 5319<https://github.com/whatwg/html/issues/5319>`_ for a
  705. * particular case.
  706. *
  707. * In functions we define here, there is an expectation from the caller
  708. * that the promise is from the current realm, that can always be used with
  709. * `await`, etc. We therefore create a new promise in this realm that
  710. * inherit the value and status from the given promise.
  711. */
  712. function bring_promise_to_current_realm(promise) {
  713. return new Promise(promise.then.bind(promise));
  714. }
  715. /**
  716. * Assert that a Promise is rejected with the right ECMAScript exception.
  717. *
  718. * @param {Test} test - the `Test` to use for the assertion.
  719. * @param {Function} constructor - The expected exception constructor.
  720. * @param {Promise} promise - The promise that's expected to
  721. * reject with the given exception.
  722. * @param {string} [description] Error message to add to assert in case of
  723. * failure.
  724. */
  725. function promise_rejects_js(test, constructor, promise, description) {
  726. return bring_promise_to_current_realm(promise)
  727. .then(test.unreached_func("Should have rejected: " + description))
  728. .catch(function(e) {
  729. assert_throws_js_impl(constructor, function() { throw e },
  730. description, "promise_rejects_js");
  731. });
  732. }
  733. /**
  734. * Assert that a Promise is rejected with the right DOMException.
  735. *
  736. * For the remaining arguments, there are two ways of calling
  737. * promise_rejects_dom:
  738. *
  739. * 1) If the DOMException is expected to come from the current global, the
  740. * third argument should be the promise expected to reject, and a fourth,
  741. * optional, argument is the assertion description.
  742. *
  743. * 2) If the DOMException is expected to come from some other global, the
  744. * third argument should be the DOMException constructor from that global,
  745. * the fourth argument the promise expected to reject, and the fifth,
  746. * optional, argument the assertion description.
  747. *
  748. * @param {Test} test - the `Test` to use for the assertion.
  749. * @param {number|string} type - See documentation for
  750. * `assert_throws_dom <#assert_throws_dom>`_.
  751. * @param {Function} promiseOrConstructor - Either the constructor
  752. * for the expected exception (if the exception comes from another
  753. * global), or the promise that's expected to reject (if the
  754. * exception comes from the current global).
  755. * @param {Function|string} descriptionOrPromise - Either the
  756. * promise that's expected to reject (if the exception comes from
  757. * another global), or the optional description of the condition
  758. * being tested (if the exception comes from the current global).
  759. * @param {string} [description] - Description of the condition
  760. * being tested (if the exception comes from another global).
  761. *
  762. */
  763. function promise_rejects_dom(test, type, promiseOrConstructor, descriptionOrPromise, maybeDescription) {
  764. let constructor, promise, description;
  765. if (typeof promiseOrConstructor === "function" &&
  766. promiseOrConstructor.name === "DOMException") {
  767. constructor = promiseOrConstructor;
  768. promise = descriptionOrPromise;
  769. description = maybeDescription;
  770. } else {
  771. constructor = self.DOMException;
  772. promise = promiseOrConstructor;
  773. description = descriptionOrPromise;
  774. assert(maybeDescription === undefined,
  775. "Too many args pased to no-constructor version of promise_rejects_dom");
  776. }
  777. return bring_promise_to_current_realm(promise)
  778. .then(test.unreached_func("Should have rejected: " + description))
  779. .catch(function(e) {
  780. assert_throws_dom_impl(type, function() { throw e }, description,
  781. "promise_rejects_dom", constructor);
  782. });
  783. }
  784. /**
  785. * Assert that a Promise is rejected with the provided value.
  786. *
  787. * @param {Test} test - the `Test` to use for the assertion.
  788. * @param {Any} exception - The expected value of the rejected promise.
  789. * @param {Promise} promise - The promise that's expected to
  790. * reject.
  791. * @param {string} [description] Error message to add to assert in case of
  792. * failure.
  793. */
  794. function promise_rejects_exactly(test, exception, promise, description) {
  795. return bring_promise_to_current_realm(promise)
  796. .then(test.unreached_func("Should have rejected: " + description))
  797. .catch(function(e) {
  798. assert_throws_exactly_impl(exception, function() { throw e },
  799. description, "promise_rejects_exactly");
  800. });
  801. }
  802. /**
  803. * Allow DOM events to be handled using Promises.
  804. *
  805. * This can make it a lot easier to test a very specific series of events,
  806. * including ensuring that unexpected events are not fired at any point.
  807. *
  808. * `EventWatcher` will assert if an event occurs while there is no `wait_for`
  809. * created Promise waiting to be fulfilled, or if the event is of a different type
  810. * to the type currently expected. This ensures that only the events that are
  811. * expected occur, in the correct order, and with the correct timing.
  812. *
  813. * @constructor
  814. * @param {Test} test - The `Test` to use for the assertion.
  815. * @param {EventTarget} watchedNode - The target expected to receive the events.
  816. * @param {string[]} eventTypes - List of events to watch for.
  817. * @param {Promise} timeoutPromise - Promise that will cause the
  818. * test to be set to `TIMEOUT` once fulfilled.
  819. *
  820. */
  821. function EventWatcher(test, watchedNode, eventTypes, timeoutPromise)
  822. {
  823. if (typeof eventTypes == 'string') {
  824. eventTypes = [eventTypes];
  825. }
  826. var waitingFor = null;
  827. // This is null unless we are recording all events, in which case it
  828. // will be an Array object.
  829. var recordedEvents = null;
  830. var eventHandler = test.step_func(function(evt) {
  831. assert_true(!!waitingFor,
  832. 'Not expecting event, but got ' + evt.type + ' event');
  833. assert_equals(evt.type, waitingFor.types[0],
  834. 'Expected ' + waitingFor.types[0] + ' event, but got ' +
  835. evt.type + ' event instead');
  836. if (Array.isArray(recordedEvents)) {
  837. recordedEvents.push(evt);
  838. }
  839. if (waitingFor.types.length > 1) {
  840. // Pop first event from array
  841. waitingFor.types.shift();
  842. return;
  843. }
  844. // We need to null out waitingFor before calling the resolve function
  845. // since the Promise's resolve handlers may call wait_for() which will
  846. // need to set waitingFor.
  847. var resolveFunc = waitingFor.resolve;
  848. waitingFor = null;
  849. // Likewise, we should reset the state of recordedEvents.
  850. var result = recordedEvents || evt;
  851. recordedEvents = null;
  852. resolveFunc(result);
  853. });
  854. for (var i = 0; i < eventTypes.length; i++) {
  855. watchedNode.addEventListener(eventTypes[i], eventHandler, false);
  856. }
  857. /**
  858. * Returns a Promise that will resolve after the specified event or
  859. * series of events has occurred.
  860. *
  861. * @param {Object} options An optional options object. If the 'record' property
  862. * on this object has the value 'all', when the Promise
  863. * returned by this function is resolved, *all* Event
  864. * objects that were waited for will be returned as an
  865. * array.
  866. *
  867. * @example
  868. * const watcher = new EventWatcher(t, div, [ 'animationstart',
  869. * 'animationiteration',
  870. * 'animationend' ]);
  871. * return watcher.wait_for([ 'animationstart', 'animationend' ],
  872. * { record: 'all' }).then(evts => {
  873. * assert_equals(evts[0].elapsedTime, 0.0);
  874. * assert_equals(evts[1].elapsedTime, 2.0);
  875. * });
  876. */
  877. this.wait_for = function(types, options) {
  878. if (waitingFor) {
  879. return Promise.reject('Already waiting for an event or events');
  880. }
  881. if (typeof types == 'string') {
  882. types = [types];
  883. }
  884. if (options && options.record && options.record === 'all') {
  885. recordedEvents = [];
  886. }
  887. return new Promise(function(resolve, reject) {
  888. var timeout = test.step_func(function() {
  889. // If the timeout fires after the events have been received
  890. // or during a subsequent call to wait_for, ignore it.
  891. if (!waitingFor || waitingFor.resolve !== resolve)
  892. return;
  893. // This should always fail, otherwise we should have
  894. // resolved the promise.
  895. assert_true(waitingFor.types.length == 0,
  896. 'Timed out waiting for ' + waitingFor.types.join(', '));
  897. var result = recordedEvents;
  898. recordedEvents = null;
  899. var resolveFunc = waitingFor.resolve;
  900. waitingFor = null;
  901. resolveFunc(result);
  902. });
  903. if (timeoutPromise) {
  904. timeoutPromise().then(timeout);
  905. }
  906. waitingFor = {
  907. types: types,
  908. resolve: resolve,
  909. reject: reject
  910. };
  911. });
  912. };
  913. /**
  914. * Stop listening for events
  915. */
  916. function stop_watching() {
  917. for (var i = 0; i < eventTypes.length; i++) {
  918. watchedNode.removeEventListener(eventTypes[i], eventHandler, false);
  919. }
  920. };
  921. test._add_cleanup(stop_watching);
  922. return this;
  923. }
  924. expose(EventWatcher, 'EventWatcher');
  925. /**
  926. * @typedef {Object} SettingsObject
  927. * @property {bool} single_test - Use the single-page-test
  928. * mode. In this mode the Document represents a single
  929. * `async_test`. Asserts may be used directly without requiring
  930. * `Test.step` or similar wrappers, and any exceptions set the
  931. * status of the test rather than the status of the harness.
  932. * @property {bool} allow_uncaught_exception - don't treat an
  933. * uncaught exception as an error; needed when e.g. testing the
  934. * `window.onerror` handler.
  935. * @property {boolean} explicit_done - Wait for a call to `done()`
  936. * before declaring all tests complete (this is always true for
  937. * single-page tests).
  938. * @property hide_test_state - hide the test state output while
  939. * the test is running; This is helpful when the output of the test state
  940. * may interfere the test results.
  941. * @property {bool} explicit_timeout - disable file timeout; only
  942. * stop waiting for results when the `timeout()` function is
  943. * called This should typically only be set for manual tests, or
  944. * by a test runner that providees its own timeout mechanism.
  945. * @property {number} timeout_multiplier - Multiplier to apply to
  946. * per-test timeouts. This should only be set by a test runner.
  947. * @property {Document} output_document - The document to which
  948. * results should be logged. By default this is the current
  949. * document but could be an ancestor document in some cases e.g. a
  950. * SVG test loaded in an HTML wrapper
  951. *
  952. */
  953. /**
  954. * Configure the harness
  955. *
  956. * @param {Function|SettingsObject} funcOrProperties - Either a
  957. * setup function to run, or a set of properties. If this is a
  958. * function that function is run synchronously. Any exception in
  959. * the function will set the overall harness status to `ERROR`.
  960. * @param {SettingsObject} maybeProperties - An object containing
  961. * the settings to use, if the first argument is a function.
  962. *
  963. */
  964. function setup(func_or_properties, maybe_properties)
  965. {
  966. var func = null;
  967. var properties = {};
  968. if (arguments.length === 2) {
  969. func = func_or_properties;
  970. properties = maybe_properties;
  971. } else if (func_or_properties instanceof Function) {
  972. func = func_or_properties;
  973. } else {
  974. properties = func_or_properties;
  975. }
  976. tests.setup(func, properties);
  977. test_environment.on_new_harness_properties(properties);
  978. }
  979. /**
  980. * Configure the harness, waiting for a promise to resolve
  981. * before running any `promise_test` tests.
  982. *
  983. * @param {Function} func - Function returning a promise that's
  984. * run synchronously. Promise tests are not run until after this
  985. * function has resolved.
  986. * @param {SettingsObject} [properties] - An object containing
  987. * the harness settings to use.
  988. *
  989. */
  990. function promise_setup(func, properties={})
  991. {
  992. if (typeof func !== "function") {
  993. tests.set_status(tests.status.ERROR,
  994. "promise_test invoked without a function");
  995. tests.complete();
  996. return;
  997. }
  998. tests.promise_setup_called = true;
  999. if (!tests.promise_tests) {
  1000. tests.promise_tests = Promise.resolve();
  1001. }
  1002. tests.promise_tests = tests.promise_tests
  1003. .then(function()
  1004. {
  1005. var result;
  1006. tests.setup(null, properties);
  1007. result = func();
  1008. test_environment.on_new_harness_properties(properties);
  1009. if (!result || typeof result.then !== "function") {
  1010. throw "Non-thenable returned by function passed to `promise_setup`";
  1011. }
  1012. return result;
  1013. })
  1014. .catch(function(e)
  1015. {
  1016. tests.set_status(tests.status.ERROR,
  1017. String(e),
  1018. e && e.stack);
  1019. tests.complete();
  1020. });
  1021. }
  1022. /**
  1023. * Mark test loading as complete.
  1024. *
  1025. * Typically this function is called implicitly on page load; it's
  1026. * only necessary for users to call this when either the
  1027. * ``explict_done`` or ``single_page`` properties have been set
  1028. * via the :js:func:`setup` function.
  1029. *
  1030. * For single page tests this marks the test as complete and sets its status.
  1031. * For other tests, this marks test loading as complete, but doesn't affect ongoing tests.
  1032. */
  1033. function done() {
  1034. if (tests.tests.length === 0) {
  1035. // `done` is invoked after handling uncaught exceptions, so if the
  1036. // harness status is already set, the corresponding message is more
  1037. // descriptive than the generic message defined here.
  1038. if (tests.status.status === null) {
  1039. tests.status.status = tests.status.ERROR;
  1040. tests.status.message = "done() was called without first defining any tests";
  1041. }
  1042. tests.complete();
  1043. return;
  1044. }
  1045. if (tests.file_is_test) {
  1046. // file is test files never have asynchronous cleanup logic,
  1047. // meaning the fully-synchronous `done` function can be used here.
  1048. tests.tests[0].done();
  1049. }
  1050. tests.end_wait();
  1051. }
  1052. /**
  1053. * @deprecated generate a list of tests from a function and list of arguments
  1054. *
  1055. * This is deprecated because it runs all the tests outside of the test functions
  1056. * and as a result any test throwing an exception will result in no tests being
  1057. * run. In almost all cases, you should simply call test within the loop you would
  1058. * use to generate the parameter list array.
  1059. *
  1060. * @param {Function} func - The function that will be called for each generated tests.
  1061. * @param {Any[][]} args - An array of arrays. Each nested array
  1062. * has the structure `[testName, ...testArgs]`. For each of these nested arrays
  1063. * array, a test is generated with name `testName` and test function equivalent to
  1064. * `func(..testArgs)`.
  1065. */
  1066. function generate_tests(func, args, properties) {
  1067. forEach(args, function(x, i)
  1068. {
  1069. var name = x[0];
  1070. test(function()
  1071. {
  1072. func.apply(this, x.slice(1));
  1073. },
  1074. name,
  1075. Array.isArray(properties) ? properties[i] : properties);
  1076. });
  1077. }
  1078. /**
  1079. * @deprecated
  1080. *
  1081. * Register a function as a DOM event listener to the
  1082. * given object for the event bubbling phase.
  1083. *
  1084. * @param {EventTarget} object - Event target
  1085. * @param {string} event - Event name
  1086. * @param {Function} callback - Event handler.
  1087. */
  1088. function on_event(object, event, callback)
  1089. {
  1090. object.addEventListener(event, callback, false);
  1091. }
  1092. /**
  1093. * Global version of :js:func:`Test.step_timeout` for use in single page tests.
  1094. *
  1095. * @param {Function} func - Function to run after the timeout
  1096. * @param {number} timeout - Time in ms to wait before running the
  1097. * test step. The actual wait time is ``timeout`` x
  1098. * ``timeout_multiplier``.
  1099. */
  1100. function step_timeout(func, timeout) {
  1101. var outer_this = this;
  1102. var args = Array.prototype.slice.call(arguments, 2);
  1103. return setTimeout(function() {
  1104. func.apply(outer_this, args);
  1105. }, timeout * tests.timeout_multiplier);
  1106. }
  1107. expose(test, 'test');
  1108. expose(async_test, 'async_test');
  1109. expose(promise_test, 'promise_test');
  1110. expose(promise_rejects_js, 'promise_rejects_js');
  1111. expose(promise_rejects_dom, 'promise_rejects_dom');
  1112. expose(promise_rejects_exactly, 'promise_rejects_exactly');
  1113. expose(generate_tests, 'generate_tests');
  1114. expose(setup, 'setup');
  1115. expose(promise_setup, 'promise_setup');
  1116. expose(done, 'done');
  1117. expose(on_event, 'on_event');
  1118. expose(step_timeout, 'step_timeout');
  1119. /*
  1120. * Return a string truncated to the given length, with ... added at the end
  1121. * if it was longer.
  1122. */
  1123. function truncate(s, len)
  1124. {
  1125. if (s.length > len) {
  1126. return s.substring(0, len - 3) + "...";
  1127. }
  1128. return s;
  1129. }
  1130. /*
  1131. * Return true if object is probably a Node object.
  1132. */
  1133. function is_node(object)
  1134. {
  1135. // I use duck-typing instead of instanceof, because
  1136. // instanceof doesn't work if the node is from another window (like an
  1137. // iframe's contentWindow):
  1138. // http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295
  1139. try {
  1140. var has_node_properties = ("nodeType" in object &&
  1141. "nodeName" in object &&
  1142. "nodeValue" in object &&
  1143. "childNodes" in object);
  1144. } catch (e) {
  1145. // We're probably cross-origin, which means we aren't a node
  1146. return false;
  1147. }
  1148. if (has_node_properties) {
  1149. try {
  1150. object.nodeType;
  1151. } catch (e) {
  1152. // The object is probably Node.prototype or another prototype
  1153. // object that inherits from it, and not a Node instance.
  1154. return false;
  1155. }
  1156. return true;
  1157. }
  1158. return false;
  1159. }
  1160. var replacements = {
  1161. "0": "0",
  1162. "1": "x01",
  1163. "2": "x02",
  1164. "3": "x03",
  1165. "4": "x04",
  1166. "5": "x05",
  1167. "6": "x06",
  1168. "7": "x07",
  1169. "8": "b",
  1170. "9": "t",
  1171. "10": "n",
  1172. "11": "v",
  1173. "12": "f",
  1174. "13": "r",
  1175. "14": "x0e",
  1176. "15": "x0f",
  1177. "16": "x10",
  1178. "17": "x11",
  1179. "18": "x12",
  1180. "19": "x13",
  1181. "20": "x14",
  1182. "21": "x15",
  1183. "22": "x16",
  1184. "23": "x17",
  1185. "24": "x18",
  1186. "25": "x19",
  1187. "26": "x1a",
  1188. "27": "x1b",
  1189. "28": "x1c",
  1190. "29": "x1d",
  1191. "30": "x1e",
  1192. "31": "x1f",
  1193. "0xfffd": "ufffd",
  1194. "0xfffe": "ufffe",
  1195. "0xffff": "uffff",
  1196. };
  1197. /**
  1198. * Convert a value to a nice, human-readable string
  1199. *
  1200. * When many JavaScript Object values are coerced to a String, the
  1201. * resulting value will be ``"[object Object]"``. This obscures
  1202. * helpful information, making the coerced value unsuitable for
  1203. * use in assertion messages, test names, and debugging
  1204. * statements. `format_value` produces more distinctive string
  1205. * representations of many kinds of objects, including arrays and
  1206. * the more important DOM Node types. It also translates String
  1207. * values containing control characters to include human-readable
  1208. * representations.
  1209. *
  1210. * @example
  1211. * // "Document node with 2 children"
  1212. * format_value(document);
  1213. * @example
  1214. * // "\"foo\\uffffbar\""
  1215. * format_value("foo\uffffbar");
  1216. * @example
  1217. * // "[-0, Infinity]"
  1218. * format_value([-0, Infinity]);
  1219. * @param {Any} val - The value to convert to a string.
  1220. * @returns {string} - A string representation of ``val``, optimised for human readability.
  1221. */
  1222. function format_value(val, seen)
  1223. {
  1224. if (!seen) {
  1225. seen = [];
  1226. }
  1227. if (typeof val === "object" && val !== null) {
  1228. if (seen.indexOf(val) >= 0) {
  1229. return "[...]";
  1230. }
  1231. seen.push(val);
  1232. }
  1233. if (Array.isArray(val)) {
  1234. let output = "[";
  1235. if (val.beginEllipsis !== undefined) {
  1236. output += "…, ";
  1237. }
  1238. output += val.map(function(x) {return format_value(x, seen);}).join(", ");
  1239. if (val.endEllipsis !== undefined) {
  1240. output += ", …";
  1241. }
  1242. return output + "]";
  1243. }
  1244. switch (typeof val) {
  1245. case "string":
  1246. val = val.replace(/\\/g, "\\\\");
  1247. for (var p in replacements) {
  1248. var replace = "\\" + replacements[p];
  1249. val = val.replace(RegExp(String.fromCharCode(p), "g"), replace);
  1250. }
  1251. return '"' + val.replace(/"/g, '\\"') + '"';
  1252. case "boolean":
  1253. case "undefined":
  1254. return String(val);
  1255. case "number":
  1256. // In JavaScript, -0 === 0 and String(-0) == "0", so we have to
  1257. // special-case.
  1258. if (val === -0 && 1/val === -Infinity) {
  1259. return "-0";
  1260. }
  1261. return String(val);
  1262. case "object":
  1263. if (val === null) {
  1264. return "null";
  1265. }
  1266. // Special-case Node objects, since those come up a lot in my tests. I
  1267. // ignore namespaces.
  1268. if (is_node(val)) {
  1269. switch (val.nodeType) {
  1270. case Node.ELEMENT_NODE:
  1271. var ret = "<" + val.localName;
  1272. for (var i = 0; i < val.attributes.length; i++) {
  1273. ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';
  1274. }
  1275. ret += ">" + val.innerHTML + "</" + val.localName + ">";
  1276. return "Element node " + truncate(ret, 60);
  1277. case Node.TEXT_NODE:
  1278. return 'Text node "' + truncate(val.data, 60) + '"';
  1279. case Node.PROCESSING_INSTRUCTION_NODE:
  1280. return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60));
  1281. case Node.COMMENT_NODE:
  1282. return "Comment node <!--" + truncate(val.data, 60) + "-->";
  1283. case Node.DOCUMENT_NODE:
  1284. return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
  1285. case Node.DOCUMENT_TYPE_NODE:
  1286. return "DocumentType node";
  1287. case Node.DOCUMENT_FRAGMENT_NODE:
  1288. return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
  1289. default:
  1290. return "Node object of unknown type";
  1291. }
  1292. }
  1293. /* falls through */
  1294. default:
  1295. try {
  1296. return typeof val + ' "' + truncate(String(val), 1000) + '"';
  1297. } catch(e) {
  1298. return ("[stringifying object threw " + String(e) +
  1299. " with type " + String(typeof e) + "]");
  1300. }
  1301. }
  1302. }
  1303. expose(format_value, "format_value");
  1304. /*
  1305. * Assertions
  1306. */
  1307. function expose_assert(f, name) {
  1308. function assert_wrapper(...args) {
  1309. let status = Test.statuses.TIMEOUT;
  1310. let stack = null;
  1311. try {
  1312. if (settings.debug) {
  1313. console.debug("ASSERT", name, tests.current_test && tests.current_test.name, args);
  1314. }
  1315. if (tests.output) {
  1316. tests.set_assert(name, args);
  1317. }
  1318. const rv = f.apply(undefined, args);
  1319. status = Test.statuses.PASS;
  1320. return rv;
  1321. } catch(e) {
  1322. status = Test.statuses.FAIL;
  1323. stack = e.stack ? e.stack : null;
  1324. throw e;
  1325. } finally {
  1326. if (tests.output && !stack) {
  1327. stack = get_stack();
  1328. }
  1329. if (tests.output) {
  1330. tests.set_assert_status(status, stack);
  1331. }
  1332. }
  1333. }
  1334. expose(assert_wrapper, name);
  1335. }
  1336. /**
  1337. * Assert that ``actual`` is strictly true
  1338. *
  1339. * @param {Any} actual - Value that is asserted to be true
  1340. * @param {string} [description] - Description of the condition being tested
  1341. */
  1342. function assert_true(actual, description)
  1343. {
  1344. assert(actual === true, "assert_true", description,
  1345. "expected true got ${actual}", {actual:actual});
  1346. }
  1347. expose_assert(assert_true, "assert_true");
  1348. /**
  1349. * Assert that ``actual`` is strictly false
  1350. *
  1351. * @param {Any} actual - Value that is asserted to be false
  1352. * @param {string} [description] - Description of the condition being tested
  1353. */
  1354. function assert_false(actual, description)
  1355. {
  1356. assert(actual === false, "assert_false", description,
  1357. "expected false got ${actual}", {actual:actual});
  1358. }
  1359. expose_assert(assert_false, "assert_false");
  1360. function same_value(x, y) {
  1361. if (y !== y) {
  1362. //NaN case
  1363. return x !== x;
  1364. }
  1365. if (x === 0 && y === 0) {
  1366. //Distinguish +0 and -0
  1367. return 1/x === 1/y;
  1368. }
  1369. return x === y;
  1370. }
  1371. /**
  1372. * Assert that ``actual`` is the same value as ``expected``.
  1373. *
  1374. * For objects this compares by cobject identity; for primitives
  1375. * this distinguishes between 0 and -0, and has correct handling
  1376. * of NaN.
  1377. *
  1378. * @param {Any} actual - Test value.
  1379. * @param {Any} expected - Expected value.
  1380. * @param {string} [description] - Description of the condition being tested.
  1381. */
  1382. function assert_equals(actual, expected, description)
  1383. {
  1384. /*
  1385. * Test if two primitives are equal or two objects
  1386. * are the same object
  1387. */
  1388. if (typeof actual != typeof expected) {
  1389. assert(false, "assert_equals", description,
  1390. "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",
  1391. {expected:expected, actual:actual});
  1392. return;
  1393. }
  1394. assert(same_value(actual, expected), "assert_equals", description,
  1395. "expected ${expected} but got ${actual}",
  1396. {expected:expected, actual:actual});
  1397. }
  1398. expose_assert(assert_equals, "assert_equals");
  1399. /**
  1400. * Assert that ``actual`` is not the same value as ``expected``.
  1401. *
  1402. * Comparison is as for :js:func:`assert_equals`.
  1403. *
  1404. * @param {Any} actual - Test value.
  1405. * @param {Any} expected - The value ``actual`` is expected to be different to.
  1406. * @param {string} [description] - Description of the condition being tested.
  1407. */
  1408. function assert_not_equals(actual, expected, description)
  1409. {
  1410. assert(!same_value(actual, expected), "assert_not_equals", description,
  1411. "got disallowed value ${actual}",
  1412. {actual:actual});
  1413. }
  1414. expose_assert(assert_not_equals, "assert_not_equals");
  1415. /**
  1416. * Assert that ``expected`` is an array and ``actual`` is one of the members.
  1417. * This is implemented using ``indexOf``, so doesn't handle NaN or ±0 correctly.
  1418. *
  1419. * @param {Any} actual - Test value.
  1420. * @param {Array} expected - An array that ``actual`` is expected to
  1421. * be a member of.
  1422. * @param {string} [description] - Description of the condition being tested.
  1423. */
  1424. function assert_in_array(actual, expected, description)
  1425. {
  1426. assert(expected.indexOf(actual) != -1, "assert_in_array", description,
  1427. "value ${actual} not in array ${expected}",
  1428. {actual:actual, expected:expected});
  1429. }
  1430. expose_assert(assert_in_array, "assert_in_array");
  1431. // This function was deprecated in July of 2015.
  1432. // See https://github.com/web-platform-tests/wpt/issues/2033
  1433. /**
  1434. * @deprecated
  1435. * Recursively compare two objects for equality.
  1436. *
  1437. * See `Issue 2033
  1438. * <https://github.com/web-platform-tests/wpt/issues/2033>`_ for
  1439. * more information.
  1440. *
  1441. * @param {Object} actual - Test value.
  1442. * @param {Object} expected - Expected value.
  1443. * @param {string} [description] - Description of the condition being tested.
  1444. */
  1445. function assert_object_equals(actual, expected, description)
  1446. {
  1447. assert(typeof actual === "object" && actual !== null, "assert_object_equals", description,
  1448. "value is ${actual}, expected object",
  1449. {actual: actual});
  1450. //This needs to be improved a great deal
  1451. function check_equal(actual, expected, stack)
  1452. {
  1453. stack.push(actual);
  1454. var p;
  1455. for (p in actual) {
  1456. assert(expected.hasOwnProperty(p), "assert_object_equals", description,
  1457. "unexpected property ${p}", {p:p});
  1458. if (typeof actual[p] === "object" && actual[p] !== null) {
  1459. if (stack.indexOf(actual[p]) === -1) {
  1460. check_equal(actual[p], expected[p], stack);
  1461. }
  1462. } else {
  1463. assert(same_value(actual[p], expected[p]), "assert_object_equals", description,
  1464. "property ${p} expected ${expected} got ${actual}",
  1465. {p:p, expected:expected[p], actual:actual[p]});
  1466. }
  1467. }
  1468. for (p in expected) {
  1469. assert(actual.hasOwnProperty(p),
  1470. "assert_object_equals", description,
  1471. "expected property ${p} missing", {p:p});
  1472. }
  1473. stack.pop();
  1474. }
  1475. check_equal(actual, expected, []);
  1476. }
  1477. expose_assert(assert_object_equals, "assert_object_equals");
  1478. /**
  1479. * Assert that ``actual`` and ``expected`` are both arrays, and that the array properties of
  1480. * ``actual`` and ``expected`` are all the same value (as for :js:func:`assert_equals`).
  1481. *
  1482. * @param {Array} actual - Test array.
  1483. * @param {Array} expected - Array that is expected to contain the same values as ``actual``.
  1484. * @param {string} [description] - Description of the condition being tested.
  1485. */
  1486. function assert_array_equals(actual, expected, description)
  1487. {
  1488. const max_array_length = 20;
  1489. function shorten_array(arr, offset = 0) {
  1490. // Make ", …" only show up when it would likely reduce the length, not accounting for
  1491. // fonts.
  1492. if (arr.length < max_array_length + 2) {
  1493. return arr;
  1494. }
  1495. // By default we want half the elements after the offset and half before
  1496. // But if that takes us past the end of the array, we have more before, and
  1497. // if it takes us before the start we have more after.
  1498. const length_after_offset = Math.floor(max_array_length / 2);
  1499. let upper_bound = Math.min(length_after_offset + offset, arr.length);
  1500. const lower_bound = Math.max(upper_bound - max_array_length, 0);
  1501. if (lower_bound === 0) {
  1502. upper_bound = max_array_length;
  1503. }
  1504. const output = arr.slice(lower_bound, upper_bound);
  1505. if (lower_bound > 0) {
  1506. output.beginEllipsis = true;
  1507. }
  1508. if (upper_bound < arr.length) {
  1509. output.endEllipsis = true;
  1510. }
  1511. return output;
  1512. }
  1513. assert(typeof actual === "object" && actual !== null && "length" in actual,
  1514. "assert_array_equals", description,
  1515. "value is ${actual}, expected array",
  1516. {actual:actual});
  1517. assert(actual.length === expected.length,
  1518. "assert_array_equals", description,
  1519. "lengths differ, expected array ${expected} length ${expectedLength}, got ${actual} length ${actualLength}",
  1520. {expected:shorten_array(expected, expected.length - 1), expectedLength:expected.length,
  1521. actual:shorten_array(actual, actual.length - 1), actualLength:actual.length
  1522. });
  1523. for (var i = 0; i < actual.length; i++) {
  1524. assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
  1525. "assert_array_equals", description,
  1526. "expected property ${i} to be ${expected} but was ${actual} (expected array ${arrayExpected} got ${arrayActual})",
  1527. {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
  1528. actual:actual.hasOwnProperty(i) ? "present" : "missing",
  1529. arrayExpected:shorten_array(expected, i), arrayActual:shorten_array(actual, i)});
  1530. assert(same_value(expected[i], actual[i]),
  1531. "assert_array_equals", description,
  1532. "expected property ${i} to be ${expected} but got ${actual} (expected array ${arrayExpected} got ${arrayActual})",
  1533. {i:i, expected:expected[i], actual:actual[i],
  1534. arrayExpected:shorten_array(expected, i), arrayActual:shorten_array(actual, i)});
  1535. }
  1536. }
  1537. expose_assert(assert_array_equals, "assert_array_equals");
  1538. /**
  1539. * Assert that each array property in ``actual`` is a number within
  1540. * ± `epsilon` of the corresponding property in `expected`.
  1541. *
  1542. * @param {Array} actual - Array of test values.
  1543. * @param {Array} expected - Array of values expected to be close to the values in ``actual``.
  1544. * @param {number} epsilon - Magnitude of allowed difference
  1545. * between each value in ``actual`` and ``expected``.
  1546. * @param {string} [description] - Description of the condition being tested.
  1547. */
  1548. function assert_array_approx_equals(actual, expected, epsilon, description)
  1549. {
  1550. /*
  1551. * Test if two primitive arrays are equal within +/- epsilon
  1552. */
  1553. assert(actual.length === expected.length,
  1554. "assert_array_approx_equals", description,
  1555. "lengths differ, expected ${expected} got ${actual}",
  1556. {expected:expected.length, actual:actual.length});
  1557. for (var i = 0; i < actual.length; i++) {
  1558. assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
  1559. "assert_array_approx_equals", description,
  1560. "property ${i}, property expected to be ${expected} but was ${actual}",
  1561. {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
  1562. actual:actual.hasOwnProperty(i) ? "present" : "missing"});
  1563. assert(typeof actual[i] === "number",
  1564. "assert_array_approx_equals", description,
  1565. "property ${i}, expected a number but got a ${type_actual}",
  1566. {i:i, type_actual:typeof actual[i]});
  1567. assert(Math.abs(actual[i] - expected[i]) <= epsilon,
  1568. "assert_array_approx_equals", description,
  1569. "property ${i}, expected ${expected} +/- ${epsilon}, expected ${expected} but got ${actual}",
  1570. {i:i, expected:expected[i], actual:actual[i], epsilon:epsilon});
  1571. }
  1572. }
  1573. expose_assert(assert_array_approx_equals, "assert_array_approx_equals");
  1574. /**
  1575. * Assert that ``actual`` is within ± ``epsilon`` of ``expected``.
  1576. *
  1577. * @param {number} actual - Test value.
  1578. * @param {number} expected - Value number is expected to be close to.
  1579. * @param {number} epsilon - Magnitude of allowed difference between ``actual`` and ``expected``.
  1580. * @param {string} [description] - Description of the condition being tested.
  1581. */
  1582. function assert_approx_equals(actual, expected, epsilon, description)
  1583. {
  1584. /*
  1585. * Test if two primitive numbers are equal within +/- epsilon
  1586. */
  1587. assert(typeof actual === "number",
  1588. "assert_approx_equals", description,
  1589. "expected a number but got a ${type_actual}",
  1590. {type_actual:typeof actual});
  1591. // The epsilon math below does not place nice with NaN and Infinity
  1592. // But in this case Infinity = Infinity and NaN = NaN
  1593. if (isFinite(actual) || isFinite(expected)) {
  1594. assert(Math.abs(actual - expected) <= epsilon,
  1595. "assert_approx_equals", description,
  1596. "expected ${expected} +/- ${epsilon} but got ${actual}",
  1597. {expected:expected, actual:actual, epsilon:epsilon});
  1598. } else {
  1599. assert_equals(actual, expected);
  1600. }
  1601. }
  1602. expose_assert(assert_approx_equals, "assert_approx_equals");
  1603. /**
  1604. * Assert that ``actual`` is a number less than ``expected``.
  1605. *
  1606. * @param {number} actual - Test value.
  1607. * @param {number} expected - Number that ``actual`` must be less than.
  1608. * @param {string} [description] - Description of the condition being tested.
  1609. */
  1610. function assert_less_than(actual, expected, description)
  1611. {
  1612. /*
  1613. * Test if a primitive number is less than another
  1614. */
  1615. assert(typeof actual === "number",
  1616. "assert_less_than", description,
  1617. "expected a number but got a ${type_actual}",
  1618. {type_actual:typeof actual});
  1619. assert(actual < expected,
  1620. "assert_less_than", description,
  1621. "expected a number less than ${expected} but got ${actual}",
  1622. {expected:expected, actual:actual});
  1623. }
  1624. expose_assert(assert_less_than, "assert_less_than");
  1625. /**
  1626. * Assert that ``actual`` is a number greater than ``expected``.
  1627. *
  1628. * @param {number} actual - Test value.
  1629. * @param {number} expected - Number that ``actual`` must be greater than.
  1630. * @param {string} [description] - Description of the condition being tested.
  1631. */
  1632. function assert_greater_than(actual, expected, description)
  1633. {
  1634. /*
  1635. * Test if a primitive number is greater than another
  1636. */
  1637. assert(typeof actual === "number",
  1638. "assert_greater_than", description,
  1639. "expected a number but got a ${type_actual}",
  1640. {type_actual:typeof actual});
  1641. assert(actual > expected,
  1642. "assert_greater_than", description,
  1643. "expected a number greater than ${expected} but got ${actual}",
  1644. {expected:expected, actual:actual});
  1645. }
  1646. expose_assert(assert_greater_than, "assert_greater_than");
  1647. /**
  1648. * Assert that ``actual`` is a number greater than ``lower`` and less
  1649. * than ``upper`` but not equal to either.
  1650. *
  1651. * @param {number} actual - Test value.
  1652. * @param {number} lower - Number that ``actual`` must be greater than.
  1653. * @param {number} upper - Number that ``actual`` must be less than.
  1654. * @param {string} [description] - Description of the condition being tested.
  1655. */
  1656. function assert_between_exclusive(actual, lower, upper, description)
  1657. {
  1658. /*
  1659. * Test if a primitive number is between two others
  1660. */
  1661. assert(typeof actual === "number",
  1662. "assert_between_exclusive", description,
  1663. "expected a number but got a ${type_actual}",
  1664. {type_actual:typeof actual});
  1665. assert(actual > lower && actual < upper,
  1666. "assert_between_exclusive", description,
  1667. "expected a number greater than ${lower} " +
  1668. "and less than ${upper} but got ${actual}",
  1669. {lower:lower, upper:upper, actual:actual});
  1670. }
  1671. expose_assert(assert_between_exclusive, "assert_between_exclusive");
  1672. /**
  1673. * Assert that ``actual`` is a number less than or equal to ``expected``.
  1674. *
  1675. * @param {number} actual - Test value.
  1676. * @param {number} expected - Number that ``actual`` must be less
  1677. * than or equal to.
  1678. * @param {string} [description] - Description of the condition being tested.
  1679. */
  1680. function assert_less_than_equal(actual, expected, description)
  1681. {
  1682. /*
  1683. * Test if a primitive number is less than or equal to another
  1684. */
  1685. assert(typeof actual === "number",
  1686. "assert_less_than_equal", description,
  1687. "expected a number but got a ${type_actual}",
  1688. {type_actual:typeof actual});
  1689. assert(actual <= expected,
  1690. "assert_less_than_equal", description,
  1691. "expected a number less than or equal to ${expected} but got ${actual}",
  1692. {expected:expected, actual:actual});
  1693. }
  1694. expose_assert(assert_less_than_equal, "assert_less_than_equal");
  1695. /**
  1696. * Assert that ``actual`` is a number greater than or equal to ``expected``.
  1697. *
  1698. * @param {number} actual - Test value.
  1699. * @param {number} expected - Number that ``actual`` must be greater
  1700. * than or equal to.
  1701. * @param {string} [description] - Description of the condition being tested.
  1702. */
  1703. function assert_greater_than_equal(actual, expected, description)
  1704. {
  1705. /*
  1706. * Test if a primitive number is greater than or equal to another
  1707. */
  1708. assert(typeof actual === "number",
  1709. "assert_greater_than_equal", description,
  1710. "expected a number but got a ${type_actual}",
  1711. {type_actual:typeof actual});
  1712. assert(actual >= expected,
  1713. "assert_greater_than_equal", description,
  1714. "expected a number greater than or equal to ${expected} but got ${actual}",
  1715. {expected:expected, actual:actual});
  1716. }
  1717. expose_assert(assert_greater_than_equal, "assert_greater_than_equal");
  1718. /**
  1719. * Assert that ``actual`` is a number greater than or equal to ``lower`` and less
  1720. * than or equal to ``upper``.
  1721. *
  1722. * @param {number} actual - Test value.
  1723. * @param {number} lower - Number that ``actual`` must be greater than or equal to.
  1724. * @param {number} upper - Number that ``actual`` must be less than or equal to.
  1725. * @param {string} [description] - Description of the condition being tested.
  1726. */
  1727. function assert_between_inclusive(actual, lower, upper, description)
  1728. {
  1729. /*
  1730. * Test if a primitive number is between to two others or equal to either of them
  1731. */
  1732. assert(typeof actual === "number",
  1733. "assert_between_inclusive", description,
  1734. "expected a number but got a ${type_actual}",
  1735. {type_actual:typeof actual});
  1736. assert(actual >= lower && actual <= upper,
  1737. "assert_between_inclusive", description,
  1738. "expected a number greater than or equal to ${lower} " +
  1739. "and less than or equal to ${upper} but got ${actual}",
  1740. {lower:lower, upper:upper, actual:actual});
  1741. }
  1742. expose_assert(assert_between_inclusive, "assert_between_inclusive");
  1743. /**
  1744. * Assert that ``actual`` matches the RegExp ``expected``.
  1745. *
  1746. * @param {String} actual - Test string.
  1747. * @param {RegExp} expected - RegExp ``actual`` must match.
  1748. * @param {string} [description] - Description of the condition being tested.
  1749. */
  1750. function assert_regexp_match(actual, expected, description) {
  1751. /*
  1752. * Test if a string (actual) matches a regexp (expected)
  1753. */
  1754. assert(expected.test(actual),
  1755. "assert_regexp_match", description,
  1756. "expected ${expected} but got ${actual}",
  1757. {expected:expected, actual:actual});
  1758. }
  1759. expose_assert(assert_regexp_match, "assert_regexp_match");
  1760. /**
  1761. * Assert that the class string of ``object`` as returned in
  1762. * ``Object.prototype.toString`` is equal to ``class_name``.
  1763. *
  1764. * @param {Object} object - Object to stringify.
  1765. * @param {string} class_string - Expected class string for ``object``.
  1766. * @param {string} [description] - Description of the condition being tested.
  1767. */
  1768. function assert_class_string(object, class_string, description) {
  1769. var actual = {}.toString.call(object);
  1770. var expected = "[object " + class_string + "]";
  1771. assert(same_value(actual, expected), "assert_class_string", description,
  1772. "expected ${expected} but got ${actual}",
  1773. {expected:expected, actual:actual});
  1774. }
  1775. expose_assert(assert_class_string, "assert_class_string");
  1776. /**
  1777. * Assert that ``object`` has an own property with name ``property_name``.
  1778. *
  1779. * @param {Object} object - Object that should have the given property.
  1780. * @param {string} property_name - Expected property name.
  1781. * @param {string} [description] - Description of the condition being tested.
  1782. */
  1783. function assert_own_property(object, property_name, description) {
  1784. assert(object.hasOwnProperty(property_name),
  1785. "assert_own_property", description,
  1786. "expected property ${p} missing", {p:property_name});
  1787. }
  1788. expose_assert(assert_own_property, "assert_own_property");
  1789. /**
  1790. * Assert that ``object`` does not have an own property with name ``property_name``.
  1791. *
  1792. * @param {Object} object - Object that should not have the given property.
  1793. * @param {string} property_name - Property name to test.
  1794. * @param {string} [description] - Description of the condition being tested.
  1795. */
  1796. function assert_not_own_property(object, property_name, description) {
  1797. assert(!object.hasOwnProperty(property_name),
  1798. "assert_not_own_property", description,
  1799. "unexpected property ${p} is found on object", {p:property_name});
  1800. }
  1801. expose_assert(assert_not_own_property, "assert_not_own_property");
  1802. function _assert_inherits(name) {
  1803. return function (object, property_name, description)
  1804. {
  1805. assert((typeof object === "object" && object !== null) ||
  1806. typeof object === "function" ||
  1807. // Or has [[IsHTMLDDA]] slot
  1808. String(object) === "[object HTMLAllCollection]",
  1809. name, description,
  1810. "provided value is not an object");
  1811. assert("hasOwnProperty" in object,
  1812. name, description,
  1813. "provided value is an object but has no hasOwnProperty method");
  1814. assert(!object.hasOwnProperty(property_name),
  1815. name, description,
  1816. "property ${p} found on object expected in prototype chain",
  1817. {p:property_name});
  1818. assert(property_name in object,
  1819. name, description,
  1820. "property ${p} not found in prototype chain",
  1821. {p:property_name});
  1822. };
  1823. }
  1824. /**
  1825. * Assert that ``object`` does not have an own property with name
  1826. * ``property_name``, but inherits one through the prototype chain.
  1827. *
  1828. * @param {Object} object - Object that should have the given property in its prototype chain.
  1829. * @param {string} property_name - Expected property name.
  1830. * @param {string} [description] - Description of the condition being tested.
  1831. */
  1832. function assert_inherits(object, property_name, description) {
  1833. return _assert_inherits("assert_inherits")(object, property_name, description);
  1834. }
  1835. expose_assert(assert_inherits, "assert_inherits");
  1836. /**
  1837. * Alias for :js:func:`insert_inherits`.
  1838. *
  1839. * @param {Object} object - Object that should have the given property in its prototype chain.
  1840. * @param {string} property_name - Expected property name.
  1841. * @param {string} [description] - Description of the condition being tested.
  1842. */
  1843. function assert_idl_attribute(object, property_name, description) {
  1844. return _assert_inherits("assert_idl_attribute")(object, property_name, description);
  1845. }
  1846. expose_assert(assert_idl_attribute, "assert_idl_attribute");
  1847. /**
  1848. * Assert that ``object`` has a property named ``property_name`` and that the property is readonly.
  1849. *
  1850. * Note: The implementation tries to update the named property, so
  1851. * any side effects of updating will be triggered. Users are
  1852. * encouraged to instead inspect the property descriptor of ``property_name`` on ``object``.
  1853. *
  1854. * @param {Object} object - Object that should have the given property in its prototype chain.
  1855. * @param {string} property_name - Expected property name.
  1856. * @param {string} [description] - Description of the condition being tested.
  1857. */
  1858. function assert_readonly(object, property_name, description)
  1859. {
  1860. var initial_value = object[property_name];
  1861. try {
  1862. //Note that this can have side effects in the case where
  1863. //the property has PutForwards
  1864. object[property_name] = initial_value + "a"; //XXX use some other value here?
  1865. assert(same_value(object[property_name], initial_value),
  1866. "assert_readonly", description,
  1867. "changing property ${p} succeeded",
  1868. {p:property_name});
  1869. } finally {
  1870. object[property_name] = initial_value;
  1871. }
  1872. }
  1873. expose_assert(assert_readonly, "assert_readonly");
  1874. /**
  1875. * Assert a JS Error with the expected constructor is thrown.
  1876. *
  1877. * @param {object} constructor The expected exception constructor.
  1878. * @param {Function} func Function which should throw.
  1879. * @param {string} [description] Error description for the case that the error is not thrown.
  1880. */
  1881. function assert_throws_js(constructor, func, description)
  1882. {
  1883. assert_throws_js_impl(constructor, func, description,
  1884. "assert_throws_js");
  1885. }
  1886. expose_assert(assert_throws_js, "assert_throws_js");
  1887. /**
  1888. * Like assert_throws_js but allows specifying the assertion type
  1889. * (assert_throws_js or promise_rejects_js, in practice).
  1890. */
  1891. function assert_throws_js_impl(constructor, func, description,
  1892. assertion_type)
  1893. {
  1894. try {
  1895. func.call(this);
  1896. assert(false, assertion_type, description,
  1897. "${func} did not throw", {func:func});
  1898. } catch (e) {
  1899. if (e instanceof AssertionError) {
  1900. throw e;
  1901. }
  1902. // Basic sanity-checks on the thrown exception.
  1903. assert(typeof e === "object",
  1904. assertion_type, description,
  1905. "${func} threw ${e} with type ${type}, not an object",
  1906. {func:func, e:e, type:typeof e});
  1907. assert(e !== null,
  1908. assertion_type, description,
  1909. "${func} threw null, not an object",
  1910. {func:func});
  1911. // Basic sanity-check on the passed-in constructor
  1912. assert(typeof constructor == "function",
  1913. assertion_type, description,
  1914. "${constructor} is not a constructor",
  1915. {constructor:constructor});
  1916. var obj = constructor;
  1917. while (obj) {
  1918. if (typeof obj === "function" &&
  1919. obj.name === "Error") {
  1920. break;
  1921. }
  1922. obj = Object.getPrototypeOf(obj);
  1923. }
  1924. assert(obj != null,
  1925. assertion_type, description,
  1926. "${constructor} is not an Error subtype",
  1927. {constructor:constructor});
  1928. // And checking that our exception is reasonable
  1929. assert(e.constructor === constructor &&
  1930. e.name === constructor.name,
  1931. assertion_type, description,
  1932. "${func} threw ${actual} (${actual_name}) expected instance of ${expected} (${expected_name})",
  1933. {func:func, actual:e, actual_name:e.name,
  1934. expected:constructor,
  1935. expected_name:constructor.name});
  1936. }
  1937. }
  1938. // TODO: Figure out how to document the overloads better.
  1939. // sphinx-js doesn't seem to handle @variation correctly,
  1940. // and only expects a single JSDoc entry per function.
  1941. /**
  1942. * Assert a DOMException with the expected type is thrown.
  1943. *
  1944. * There are two ways of calling assert_throws_dom:
  1945. *
  1946. * 1) If the DOMException is expected to come from the current global, the
  1947. * second argument should be the function expected to throw and a third,
  1948. * optional, argument is the assertion description.
  1949. *
  1950. * 2) If the DOMException is expected to come from some other global, the
  1951. * second argument should be the DOMException constructor from that global,
  1952. * the third argument the function expected to throw, and the fourth, optional,
  1953. * argument the assertion description.
  1954. *
  1955. * @param {number|string} type - The expected exception name or
  1956. * code. See the `table of names and codes
  1957. * <https://webidl.spec.whatwg.org/#dfn-error-names-table>`_. If a
  1958. * number is passed it should be one of the numeric code values in
  1959. * that table (e.g. 3, 4, etc). If a string is passed it can
  1960. * either be an exception name (e.g. "HierarchyRequestError",
  1961. * "WrongDocumentError") or the name of the corresponding error
  1962. * code (e.g. "``HIERARCHY_REQUEST_ERR``", "``WRONG_DOCUMENT_ERR``").
  1963. * @param {Function} descriptionOrFunc - The function expected to
  1964. * throw (if the exception comes from another global), or the
  1965. * optional description of the condition being tested (if the
  1966. * exception comes from the current global).
  1967. * @param {string} [description] - Description of the condition
  1968. * being tested (if the exception comes from another global).
  1969. *
  1970. */
  1971. function assert_throws_dom(type, funcOrConstructor, descriptionOrFunc, maybeDescription)
  1972. {
  1973. let constructor, func, description;
  1974. if (funcOrConstructor.name === "DOMException") {
  1975. constructor = funcOrConstructor;
  1976. func = descriptionOrFunc;
  1977. description = maybeDescription;
  1978. } else {
  1979. constructor = self.DOMException;
  1980. func = funcOrConstructor;
  1981. description = descriptionOrFunc;
  1982. assert(maybeDescription === undefined,
  1983. "Too many args pased to no-constructor version of assert_throws_dom");
  1984. }
  1985. assert_throws_dom_impl(type, func, description, "assert_throws_dom", constructor)
  1986. }
  1987. expose_assert(assert_throws_dom, "assert_throws_dom");
  1988. /**
  1989. * Similar to assert_throws_dom but allows specifying the assertion type
  1990. * (assert_throws_dom or promise_rejects_dom, in practice). The
  1991. * "constructor" argument must be the DOMException constructor from the
  1992. * global we expect the exception to come from.
  1993. */
  1994. function assert_throws_dom_impl(type, func, description, assertion_type, constructor)
  1995. {
  1996. try {
  1997. func.call(this);
  1998. assert(false, assertion_type, description,
  1999. "${func} did not throw", {func:func});
  2000. } catch (e) {
  2001. if (e instanceof AssertionError) {
  2002. throw e;
  2003. }
  2004. // Basic sanity-checks on the thrown exception.
  2005. assert(typeof e === "object",
  2006. assertion_type, description,
  2007. "${func} threw ${e} with type ${type}, not an object",
  2008. {func:func, e:e, type:typeof e});
  2009. assert(e !== null,
  2010. assertion_type, description,
  2011. "${func} threw null, not an object",
  2012. {func:func});
  2013. // Sanity-check our type
  2014. assert(typeof type == "number" ||
  2015. typeof type == "string",
  2016. assertion_type, description,
  2017. "${type} is not a number or string",
  2018. {type:type});
  2019. var codename_name_map = {
  2020. INDEX_SIZE_ERR: 'IndexSizeError',
  2021. HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',
  2022. WRONG_DOCUMENT_ERR: 'WrongDocumentError',
  2023. INVALID_CHARACTER_ERR: 'InvalidCharacterError',
  2024. NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
  2025. NOT_FOUND_ERR: 'NotFoundError',
  2026. NOT_SUPPORTED_ERR: 'NotSupportedError',
  2027. INUSE_ATTRIBUTE_ERR: 'InUseAttributeError',
  2028. INVALID_STATE_ERR: 'InvalidStateError',
  2029. SYNTAX_ERR: 'SyntaxError',
  2030. INVALID_MODIFICATION_ERR: 'InvalidModificationError',
  2031. NAMESPACE_ERR: 'NamespaceError',
  2032. INVALID_ACCESS_ERR: 'InvalidAccessError',
  2033. TYPE_MISMATCH_ERR: 'TypeMismatchError',
  2034. SECURITY_ERR: 'SecurityError',
  2035. NETWORK_ERR: 'NetworkError',
  2036. ABORT_ERR: 'AbortError',
  2037. URL_MISMATCH_ERR: 'URLMismatchError',
  2038. QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
  2039. TIMEOUT_ERR: 'TimeoutError',
  2040. INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',
  2041. DATA_CLONE_ERR: 'DataCloneError'
  2042. };
  2043. var name_code_map = {
  2044. IndexSizeError: 1,
  2045. HierarchyRequestError: 3,
  2046. WrongDocumentError: 4,
  2047. InvalidCharacterError: 5,
  2048. NoModificationAllowedError: 7,
  2049. NotFoundError: 8,
  2050. NotSupportedError: 9,
  2051. InUseAttributeError: 10,
  2052. InvalidStateError: 11,
  2053. SyntaxError: 12,
  2054. InvalidModificationError: 13,
  2055. NamespaceError: 14,
  2056. InvalidAccessError: 15,
  2057. TypeMismatchError: 17,
  2058. SecurityError: 18,
  2059. NetworkError: 19,
  2060. AbortError: 20,
  2061. URLMismatchError: 21,
  2062. QuotaExceededError: 22,
  2063. TimeoutError: 23,
  2064. InvalidNodeTypeError: 24,
  2065. DataCloneError: 25,
  2066. EncodingError: 0,
  2067. NotReadableError: 0,
  2068. UnknownError: 0,
  2069. ConstraintError: 0,
  2070. DataError: 0,
  2071. TransactionInactiveError: 0,
  2072. ReadOnlyError: 0,
  2073. VersionError: 0,
  2074. OperationError: 0,
  2075. NotAllowedError: 0
  2076. };
  2077. var code_name_map = {};
  2078. for (var key in name_code_map) {
  2079. if (name_code_map[key] > 0) {
  2080. code_name_map[name_code_map[key]] = key;
  2081. }
  2082. }
  2083. var required_props = {};
  2084. var name;
  2085. if (typeof type === "number") {
  2086. if (type === 0) {
  2087. throw new AssertionError('Test bug: ambiguous DOMException code 0 passed to assert_throws_dom()');
  2088. } else if (!(type in code_name_map)) {
  2089. throw new AssertionError('Test bug: unrecognized DOMException code "' + type + '" passed to assert_throws_dom()');
  2090. }
  2091. name = code_name_map[type];
  2092. required_props.code = type;
  2093. } else if (typeof type === "string") {
  2094. name = type in codename_name_map ? codename_name_map[type] : type;
  2095. if (!(name in name_code_map)) {
  2096. throw new AssertionError('Test bug: unrecognized DOMException code name or name "' + type + '" passed to assert_throws_dom()');
  2097. }
  2098. required_props.code = name_code_map[name];
  2099. }
  2100. if (required_props.code === 0 ||
  2101. ("name" in e &&
  2102. e.name !== e.name.toUpperCase() &&
  2103. e.name !== "DOMException")) {
  2104. // New style exception: also test the name property.
  2105. required_props.name = name;
  2106. }
  2107. for (var prop in required_props) {
  2108. assert(prop in e && e[prop] == required_props[prop],
  2109. assertion_type, description,
  2110. "${func} threw ${e} that is not a DOMException " + type + ": property ${prop} is equal to ${actual}, expected ${expected}",
  2111. {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});
  2112. }
  2113. // Check that the exception is from the right global. This check is last
  2114. // so more specific, and more informative, checks on the properties can
  2115. // happen in case a totally incorrect exception is thrown.
  2116. assert(e.constructor === constructor,
  2117. assertion_type, description,
  2118. "${func} threw an exception from the wrong global",
  2119. {func});
  2120. }
  2121. }
  2122. /**
  2123. * Assert the provided value is thrown.
  2124. *
  2125. * @param {value} exception The expected exception.
  2126. * @param {Function} func Function which should throw.
  2127. * @param {string} [description] Error description for the case that the error is not thrown.
  2128. */
  2129. function assert_throws_exactly(exception, func, description)
  2130. {
  2131. assert_throws_exactly_impl(exception, func, description,
  2132. "assert_throws_exactly");
  2133. }
  2134. expose_assert(assert_throws_exactly, "assert_throws_exactly");
  2135. /**
  2136. * Like assert_throws_exactly but allows specifying the assertion type
  2137. * (assert_throws_exactly or promise_rejects_exactly, in practice).
  2138. */
  2139. function assert_throws_exactly_impl(exception, func, description,
  2140. assertion_type)
  2141. {
  2142. try {
  2143. func.call(this);
  2144. assert(false, assertion_type, description,
  2145. "${func} did not throw", {func:func});
  2146. } catch (e) {
  2147. if (e instanceof AssertionError) {
  2148. throw e;
  2149. }
  2150. assert(same_value(e, exception), assertion_type, description,
  2151. "${func} threw ${e} but we expected it to throw ${exception}",
  2152. {func:func, e:e, exception:exception});
  2153. }
  2154. }
  2155. /**
  2156. * Asserts if called. Used to ensure that a specific codepath is
  2157. * not taken e.g. that an error event isn't fired.
  2158. *
  2159. * @param {string} [description] - Description of the condition being tested.
  2160. */
  2161. function assert_unreached(description) {
  2162. assert(false, "assert_unreached", description,
  2163. "Reached unreachable code");
  2164. }
  2165. expose_assert(assert_unreached, "assert_unreached");
  2166. /**
  2167. * @callback AssertFunc
  2168. * @param {Any} actual
  2169. * @param {Any} expected
  2170. * @param {Any[]} args
  2171. */
  2172. /**
  2173. * Asserts that ``actual`` matches at least one value of ``expected``
  2174. * according to a comparison defined by ``assert_func``.
  2175. *
  2176. * Note that tests with multiple allowed pass conditions are bad
  2177. * practice unless the spec specifically allows multiple
  2178. * behaviours. Test authors should not use this method simply to
  2179. * hide UA bugs.
  2180. *
  2181. * @param {AssertFunc} assert_func - Function to compare actual
  2182. * and expected. It must throw when the comparison fails and
  2183. * return when the comparison passes.
  2184. * @param {Any} actual - Test value.
  2185. * @param {Array} expected_array - Array of possible expected values.
  2186. * @param {Any[]} args - Additional arguments to pass to ``assert_func``.
  2187. */
  2188. function assert_any(assert_func, actual, expected_array, ...args)
  2189. {
  2190. var errors = [];
  2191. var passed = false;
  2192. forEach(expected_array,
  2193. function(expected)
  2194. {
  2195. try {
  2196. assert_func.apply(this, [actual, expected].concat(args));
  2197. passed = true;
  2198. } catch (e) {
  2199. errors.push(e.message);
  2200. }
  2201. });
  2202. if (!passed) {
  2203. throw new AssertionError(errors.join("\n\n"));
  2204. }
  2205. }
  2206. // FIXME: assert_any cannot use expose_assert, because assert_wrapper does
  2207. // not support nested assert calls (e.g. to assert_func). We need to
  2208. // support bypassing assert_wrapper for the inner asserts here.
  2209. expose(assert_any, "assert_any");
  2210. /**
  2211. * Assert that a feature is implemented, based on a 'truthy' condition.
  2212. *
  2213. * This function should be used to early-exit from tests in which there is
  2214. * no point continuing without support for a non-optional spec or spec
  2215. * feature. For example:
  2216. *
  2217. * assert_implements(window.Foo, 'Foo is not supported');
  2218. *
  2219. * @param {object} condition The truthy value to test
  2220. * @param {string} [description] Error description for the case that the condition is not truthy.
  2221. */
  2222. function assert_implements(condition, description) {
  2223. assert(!!condition, "assert_implements", description);
  2224. }
  2225. expose_assert(assert_implements, "assert_implements")
  2226. /**
  2227. * Assert that an optional feature is implemented, based on a 'truthy' condition.
  2228. *
  2229. * This function should be used to early-exit from tests in which there is
  2230. * no point continuing without support for an explicitly optional spec or
  2231. * spec feature. For example:
  2232. *
  2233. * assert_implements_optional(video.canPlayType("video/webm"),
  2234. * "webm video playback not supported");
  2235. *
  2236. * @param {object} condition The truthy value to test
  2237. * @param {string} [description] Error description for the case that the condition is not truthy.
  2238. */
  2239. function assert_implements_optional(condition, description) {
  2240. if (!condition) {
  2241. throw new OptionalFeatureUnsupportedError(description);
  2242. }
  2243. }
  2244. expose_assert(assert_implements_optional, "assert_implements_optional");
  2245. /**
  2246. * @class
  2247. *
  2248. * A single subtest. A Test is not constructed directly but via the
  2249. * :js:func:`test`, :js:func:`async_test` or :js:func:`promise_test` functions.
  2250. *
  2251. * @param {string} name - This must be unique in a given file and must be
  2252. * invariant between runs.
  2253. *
  2254. */
  2255. function Test(name, properties)
  2256. {
  2257. if (tests.file_is_test && tests.tests.length) {
  2258. throw new Error("Tried to create a test with file_is_test");
  2259. }
  2260. /** The test name. */
  2261. this.name = name;
  2262. this.phase = (tests.is_aborted || tests.phase === tests.phases.COMPLETE) ?
  2263. this.phases.COMPLETE : this.phases.INITIAL;
  2264. /** The test status code.*/
  2265. this.status = this.NOTRUN;
  2266. this.timeout_id = null;
  2267. this.index = null;
  2268. this.properties = properties || {};
  2269. this.timeout_length = settings.test_timeout;
  2270. if (this.timeout_length !== null) {
  2271. this.timeout_length *= tests.timeout_multiplier;
  2272. }
  2273. /** A message indicating the reason for test failure. */
  2274. this.message = null;
  2275. /** Stack trace in case of failure. */
  2276. this.stack = null;
  2277. this.steps = [];
  2278. this._is_promise_test = false;
  2279. this.cleanup_callbacks = [];
  2280. this._user_defined_cleanup_count = 0;
  2281. this._done_callbacks = [];
  2282. // Tests declared following harness completion are likely an indication
  2283. // of a programming error, but they cannot be reported
  2284. // deterministically.
  2285. if (tests.phase === tests.phases.COMPLETE) {
  2286. return;
  2287. }
  2288. tests.push(this);
  2289. }
  2290. /**
  2291. * Enum of possible test statuses.
  2292. *
  2293. * :values:
  2294. * - ``PASS``
  2295. * - ``FAIL``
  2296. * - ``TIMEOUT``
  2297. * - ``NOTRUN``
  2298. * - ``PRECONDITION_FAILED``
  2299. */
  2300. Test.statuses = {
  2301. PASS:0,
  2302. FAIL:1,
  2303. TIMEOUT:2,
  2304. NOTRUN:3,
  2305. PRECONDITION_FAILED:4
  2306. };
  2307. Test.prototype = merge({}, Test.statuses);
  2308. Test.prototype.phases = {
  2309. INITIAL:0,
  2310. STARTED:1,
  2311. HAS_RESULT:2,
  2312. CLEANING:3,
  2313. COMPLETE:4
  2314. };
  2315. Test.prototype.status_formats = {
  2316. 0: "Pass",
  2317. 1: "Fail",
  2318. 2: "Timeout",
  2319. 3: "Not Run",
  2320. 4: "Optional Feature Unsupported",
  2321. }
  2322. Test.prototype.format_status = function() {
  2323. return this.status_formats[this.status];
  2324. }
  2325. Test.prototype.structured_clone = function()
  2326. {
  2327. if (!this._structured_clone) {
  2328. var msg = this.message;
  2329. msg = msg ? String(msg) : msg;
  2330. this._structured_clone = merge({
  2331. name:String(this.name),
  2332. properties:merge({}, this.properties),
  2333. phases:merge({}, this.phases)
  2334. }, Test.statuses);
  2335. }
  2336. this._structured_clone.status = this.status;
  2337. this._structured_clone.message = this.message;
  2338. this._structured_clone.stack = this.stack;
  2339. this._structured_clone.index = this.index;
  2340. this._structured_clone.phase = this.phase;
  2341. return this._structured_clone;
  2342. };
  2343. /**
  2344. * Run a single step of an ongoing test.
  2345. *
  2346. * @param {string} func - Callback function to run as a step. If
  2347. * this throws an :js:func:`AssertionError`, or any other
  2348. * exception, the :js:class:`Test` status is set to ``FAIL``.
  2349. * @param {Object} [this_obj] - The object to use as the this
  2350. * value when calling ``func``. Defaults to the :js:class:`Test` object.
  2351. */
  2352. Test.prototype.step = function(func, this_obj)
  2353. {
  2354. if (this.phase > this.phases.STARTED) {
  2355. return;
  2356. }
  2357. if (settings.debug && this.phase !== this.phases.STARTED) {
  2358. console.log("TEST START", this.name);
  2359. }
  2360. this.phase = this.phases.STARTED;
  2361. //If we don't get a result before the harness times out that will be a test timeout
  2362. this.set_status(this.TIMEOUT, "Test timed out");
  2363. tests.started = true;
  2364. tests.current_test = this;
  2365. tests.notify_test_state(this);
  2366. if (this.timeout_id === null) {
  2367. this.set_timeout();
  2368. }
  2369. this.steps.push(func);
  2370. if (arguments.length === 1) {
  2371. this_obj = this;
  2372. }
  2373. if (settings.debug) {
  2374. console.debug("TEST STEP", this.name);
  2375. }
  2376. try {
  2377. return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
  2378. } catch (e) {
  2379. if (this.phase >= this.phases.HAS_RESULT) {
  2380. return;
  2381. }
  2382. var status = e instanceof OptionalFeatureUnsupportedError ? this.PRECONDITION_FAILED : this.FAIL;
  2383. var message = String((typeof e === "object" && e !== null) ? e.message : e);
  2384. var stack = e.stack ? e.stack : null;
  2385. this.set_status(status, message, stack);
  2386. this.phase = this.phases.HAS_RESULT;
  2387. this.done();
  2388. } finally {
  2389. this.current_test = null;
  2390. }
  2391. };
  2392. /**
  2393. * Wrap a function so that it runs as a step of the current test.
  2394. *
  2395. * This allows creating a callback function that will run as a
  2396. * test step.
  2397. *
  2398. * @example
  2399. * let t = async_test("Example");
  2400. * onload = t.step_func(e => {
  2401. * assert_equals(e.name, "load");
  2402. * // Mark the test as complete.
  2403. * t.done();
  2404. * })
  2405. *
  2406. * @param {string} func - Function to run as a step. If this
  2407. * throws an :js:func:`AssertionError`, or any other exception,
  2408. * the :js:class:`Test` status is set to ``FAIL``.
  2409. * @param {Object} [this_obj] - The object to use as the this
  2410. * value when calling ``func``. Defaults to the :js:class:`Test` object.
  2411. */
  2412. Test.prototype.step_func = function(func, this_obj)
  2413. {
  2414. var test_this = this;
  2415. if (arguments.length === 1) {
  2416. this_obj = test_this;
  2417. }
  2418. return function()
  2419. {
  2420. return test_this.step.apply(test_this, [func, this_obj].concat(
  2421. Array.prototype.slice.call(arguments)));
  2422. };
  2423. };
  2424. /**
  2425. * Wrap a function so that it runs as a step of the current test,
  2426. * and automatically marks the test as complete if the function
  2427. * returns without error.
  2428. *
  2429. * @param {string} func - Function to run as a step. If this
  2430. * throws an :js:func:`AssertionError`, or any other exception,
  2431. * the :js:class:`Test` status is set to ``FAIL``. If it returns
  2432. * without error the status is set to ``PASS``.
  2433. * @param {Object} [this_obj] - The object to use as the this
  2434. * value when calling `func`. Defaults to the :js:class:`Test` object.
  2435. */
  2436. Test.prototype.step_func_done = function(func, this_obj)
  2437. {
  2438. var test_this = this;
  2439. if (arguments.length === 1) {
  2440. this_obj = test_this;
  2441. }
  2442. return function()
  2443. {
  2444. if (func) {
  2445. test_this.step.apply(test_this, [func, this_obj].concat(
  2446. Array.prototype.slice.call(arguments)));
  2447. }
  2448. test_this.done();
  2449. };
  2450. };
  2451. /**
  2452. * Return a function that automatically sets the current test to
  2453. * ``FAIL`` if it's called.
  2454. *
  2455. * @param {string} [description] - Error message to add to assert
  2456. * in case of failure.
  2457. *
  2458. */
  2459. Test.prototype.unreached_func = function(description)
  2460. {
  2461. return this.step_func(function() {
  2462. assert_unreached(description);
  2463. });
  2464. };
  2465. /**
  2466. * Run a function as a step of the test after a given timeout.
  2467. *
  2468. * This multiplies the timeout by the global timeout multiplier to
  2469. * account for the expected execution speed of the current test
  2470. * environment. For example ``test.step_timeout(f, 2000)`` with a
  2471. * timeout multiplier of 2 will wait for 4000ms before calling ``f``.
  2472. *
  2473. * In general it's encouraged to use :js:func:`Test.step_wait` or
  2474. * :js:func:`step_wait_func` in preference to this function where possible,
  2475. * as they provide better test performance.
  2476. *
  2477. * @param {Function} func - Function to run as a test
  2478. * step.
  2479. * @param {number} timeout - Time in ms to wait before running the
  2480. * test step. The actual wait time is ``timeout`` x
  2481. * ``timeout_multiplier``.
  2482. *
  2483. */
  2484. Test.prototype.step_timeout = function(func, timeout) {
  2485. var test_this = this;
  2486. var args = Array.prototype.slice.call(arguments, 2);
  2487. return setTimeout(this.step_func(function() {
  2488. return func.apply(test_this, args);
  2489. }), timeout * tests.timeout_multiplier);
  2490. };
  2491. /**
  2492. * Poll for a function to return true, and call a callback
  2493. * function once it does, or assert if a timeout is
  2494. * reached. This is preferred over a simple step_timeout
  2495. * whenever possible since it allows the timeout to be longer
  2496. * to reduce intermittents without compromising test execution
  2497. * speed when the condition is quickly met.
  2498. *
  2499. * @example
  2500. * async_test(t => {
  2501. * const popup = window.open("resources/coop-coep.py?coop=same-origin&coep=&navigate=about:blank");
  2502. * t.add_cleanup(() => popup.close());
  2503. * assert_equals(window, popup.opener);
  2504. *
  2505. * popup.onload = t.step_func(() => {
  2506. * assert_true(popup.location.href.endsWith("&navigate=about:blank"));
  2507. * // Use step_wait_func_done as about:blank cannot message back.
  2508. * t.step_wait_func_done(() => popup.location.href === "about:blank");
  2509. * });
  2510. * }, "Navigating a popup to about:blank");
  2511. *
  2512. * @param {Function} cond A function taking no arguments and
  2513. * returning a boolean. The callback is called
  2514. * when this function returns true.
  2515. * @param {Function} func A function taking no arguments to call once
  2516. * the condition is met.
  2517. * @param {string} [description] Error message to add to assert in case of
  2518. * failure.
  2519. * @param {number} timeout Timeout in ms. This is multiplied by the global
  2520. * timeout_multiplier
  2521. * @param {number} interval Polling interval in ms
  2522. *
  2523. */
  2524. Test.prototype.step_wait_func = function(cond, func, description,
  2525. timeout=3000, interval=100) {
  2526. var timeout_full = timeout * tests.timeout_multiplier;
  2527. var remaining = Math.ceil(timeout_full / interval);
  2528. var test_this = this;
  2529. var wait_for_inner = test_this.step_func(() => {
  2530. if (cond()) {
  2531. func();
  2532. } else {
  2533. if(remaining === 0) {
  2534. assert(false, "step_wait_func", description,
  2535. "Timed out waiting on condition");
  2536. }
  2537. remaining--;
  2538. setTimeout(wait_for_inner, interval);
  2539. }
  2540. });
  2541. wait_for_inner();
  2542. };
  2543. /**
  2544. * Poll for a function to return true, and invoke a callback
  2545. * followed by this.done() once it does, or assert if a timeout
  2546. * is reached. This is preferred over a simple step_timeout
  2547. * whenever possible since it allows the timeout to be longer
  2548. * to reduce intermittents without compromising test execution speed
  2549. * when the condition is quickly met.
  2550. *
  2551. * @param {Function} cond A function taking no arguments and
  2552. * returning a boolean. The callback is called
  2553. * when this function returns true.
  2554. * @param {Function} func A function taking no arguments to call once
  2555. * the condition is met.
  2556. * @param {string} [description] Error message to add to assert in case of
  2557. * failure.
  2558. * @param {number} timeout Timeout in ms. This is multiplied by the global
  2559. * timeout_multiplier
  2560. * @param {number} interval Polling interval in ms
  2561. *
  2562. */
  2563. Test.prototype.step_wait_func_done = function(cond, func, description,
  2564. timeout=3000, interval=100) {
  2565. this.step_wait_func(cond, () => {
  2566. if (func) {
  2567. func();
  2568. }
  2569. this.done();
  2570. }, description, timeout, interval);
  2571. };
  2572. /**
  2573. * Poll for a function to return true, and resolve a promise
  2574. * once it does, or assert if a timeout is reached. This is
  2575. * preferred over a simple step_timeout whenever possible
  2576. * since it allows the timeout to be longer to reduce
  2577. * intermittents without compromising test execution speed
  2578. * when the condition is quickly met.
  2579. *
  2580. * @example
  2581. * promise_test(async t => {
  2582. * // …
  2583. * await t.step_wait(() => frame.contentDocument === null, "Frame navigated to a cross-origin document");
  2584. * // …
  2585. * }, "");
  2586. *
  2587. * @param {Function} cond A function taking no arguments and
  2588. * returning a boolean.
  2589. * @param {string} [description] Error message to add to assert in case of
  2590. * failure.
  2591. * @param {number} timeout Timeout in ms. This is multiplied by the global
  2592. * timeout_multiplier
  2593. * @param {number} interval Polling interval in ms
  2594. * @returns {Promise} Promise resolved once cond is met.
  2595. *
  2596. */
  2597. Test.prototype.step_wait = function(cond, description, timeout=3000, interval=100) {
  2598. return new Promise(resolve => {
  2599. this.step_wait_func(cond, resolve, description, timeout, interval);
  2600. });
  2601. }
  2602. /*
  2603. * Private method for registering cleanup functions. `testharness.js`
  2604. * internals should use this method instead of the public `add_cleanup`
  2605. * method in order to hide implementation details from the harness status
  2606. * message in the case errors.
  2607. */
  2608. Test.prototype._add_cleanup = function(callback) {
  2609. this.cleanup_callbacks.push(callback);
  2610. };
  2611. /**
  2612. * Schedule a function to be run after the test result is known, regardless
  2613. * of passing or failing state.
  2614. *
  2615. * The behavior of this function will not
  2616. * influence the result of the test, but if an exception is thrown, the
  2617. * test harness will report an error.
  2618. *
  2619. * @param {Function} callback - The cleanup function to run. This
  2620. * is called with no arguments.
  2621. */
  2622. Test.prototype.add_cleanup = function(callback) {
  2623. this._user_defined_cleanup_count += 1;
  2624. this._add_cleanup(callback);
  2625. };
  2626. Test.prototype.set_timeout = function()
  2627. {
  2628. if (this.timeout_length !== null) {
  2629. var this_obj = this;
  2630. this.timeout_id = setTimeout(function()
  2631. {
  2632. this_obj.timeout();
  2633. }, this.timeout_length);
  2634. }
  2635. };
  2636. Test.prototype.set_status = function(status, message, stack)
  2637. {
  2638. this.status = status;
  2639. this.message = message;
  2640. this.stack = stack ? stack : null;
  2641. };
  2642. /**
  2643. * Manually set the test status to ``TIMEOUT``.
  2644. */
  2645. Test.prototype.timeout = function()
  2646. {
  2647. this.timeout_id = null;
  2648. this.set_status(this.TIMEOUT, "Test timed out");
  2649. this.phase = this.phases.HAS_RESULT;
  2650. this.done();
  2651. };
  2652. /**
  2653. * Manually set the test status to ``TIMEOUT``.
  2654. *
  2655. * Alias for `Test.timeout <#Test.timeout>`_.
  2656. */
  2657. Test.prototype.force_timeout = function() {
  2658. return this.timeout();
  2659. };
  2660. /**
  2661. * Mark the test as complete.
  2662. *
  2663. * This sets the test status to ``PASS`` if no other status was
  2664. * already recorded. Any subsequent attempts to run additional
  2665. * test steps will be ignored.
  2666. *
  2667. * After setting the test status any test cleanup functions will
  2668. * be run.
  2669. */
  2670. Test.prototype.done = function()
  2671. {
  2672. if (this.phase >= this.phases.CLEANING) {
  2673. return;
  2674. }
  2675. if (this.phase <= this.phases.STARTED) {
  2676. this.set_status(this.PASS, null);
  2677. }
  2678. if (global_scope.clearTimeout) {
  2679. clearTimeout(this.timeout_id);
  2680. }
  2681. if (settings.debug) {
  2682. console.log("TEST DONE",
  2683. this.status,
  2684. this.name);
  2685. }
  2686. this.cleanup();
  2687. };
  2688. function add_test_done_callback(test, callback)
  2689. {
  2690. if (test.phase === test.phases.COMPLETE) {
  2691. callback();
  2692. return;
  2693. }
  2694. test._done_callbacks.push(callback);
  2695. }
  2696. /*
  2697. * Invoke all specified cleanup functions. If one or more produce an error,
  2698. * the context is in an unpredictable state, so all further testing should
  2699. * be cancelled.
  2700. */
  2701. Test.prototype.cleanup = function() {
  2702. var errors = [];
  2703. var bad_value_count = 0;
  2704. function on_error(e) {
  2705. errors.push(e);
  2706. // Abort tests immediately so that tests declared within subsequent
  2707. // cleanup functions are not run.
  2708. tests.abort();
  2709. }
  2710. var this_obj = this;
  2711. var results = [];
  2712. this.phase = this.phases.CLEANING;
  2713. forEach(this.cleanup_callbacks,
  2714. function(cleanup_callback) {
  2715. var result;
  2716. try {
  2717. result = cleanup_callback();
  2718. } catch (e) {
  2719. on_error(e);
  2720. return;
  2721. }
  2722. if (!is_valid_cleanup_result(this_obj, result)) {
  2723. bad_value_count += 1;
  2724. // Abort tests immediately so that tests declared
  2725. // within subsequent cleanup functions are not run.
  2726. tests.abort();
  2727. }
  2728. results.push(result);
  2729. });
  2730. if (!this._is_promise_test) {
  2731. cleanup_done(this_obj, errors, bad_value_count);
  2732. } else {
  2733. all_async(results,
  2734. function(result, done) {
  2735. if (result && typeof result.then === "function") {
  2736. result
  2737. .then(null, on_error)
  2738. .then(done);
  2739. } else {
  2740. done();
  2741. }
  2742. },
  2743. function() {
  2744. cleanup_done(this_obj, errors, bad_value_count);
  2745. });
  2746. }
  2747. };
  2748. /*
  2749. * Determine if the return value of a cleanup function is valid for a given
  2750. * test. Any test may return the value `undefined`. Tests created with
  2751. * `promise_test` may alternatively return "thenable" object values.
  2752. */
  2753. function is_valid_cleanup_result(test, result) {
  2754. if (result === undefined) {
  2755. return true;
  2756. }
  2757. if (test._is_promise_test) {
  2758. return result && typeof result.then === "function";
  2759. }
  2760. return false;
  2761. }
  2762. function cleanup_done(test, errors, bad_value_count) {
  2763. if (errors.length || bad_value_count) {
  2764. var total = test._user_defined_cleanup_count;
  2765. tests.status.status = tests.status.ERROR;
  2766. tests.status.stack = null;
  2767. tests.status.message = "Test named '" + test.name +
  2768. "' specified " + total +
  2769. " 'cleanup' function" + (total > 1 ? "s" : "");
  2770. if (errors.length) {
  2771. tests.status.message += ", and " + errors.length + " failed";
  2772. tests.status.stack = ((typeof errors[0] === "object" &&
  2773. errors[0].hasOwnProperty("stack")) ?
  2774. errors[0].stack : null);
  2775. }
  2776. if (bad_value_count) {
  2777. var type = test._is_promise_test ?
  2778. "non-thenable" : "non-undefined";
  2779. tests.status.message += ", and " + bad_value_count +
  2780. " returned a " + type + " value";
  2781. }
  2782. tests.status.message += ".";
  2783. }
  2784. test.phase = test.phases.COMPLETE;
  2785. tests.result(test);
  2786. forEach(test._done_callbacks,
  2787. function(callback) {
  2788. callback();
  2789. });
  2790. test._done_callbacks.length = 0;
  2791. }
  2792. /**
  2793. * A RemoteTest object mirrors a Test object on a remote worker. The
  2794. * associated RemoteWorker updates the RemoteTest object in response to
  2795. * received events. In turn, the RemoteTest object replicates these events
  2796. * on the local document. This allows listeners (test result reporting
  2797. * etc..) to transparently handle local and remote events.
  2798. */
  2799. function RemoteTest(clone) {
  2800. var this_obj = this;
  2801. Object.keys(clone).forEach(
  2802. function(key) {
  2803. this_obj[key] = clone[key];
  2804. });
  2805. this.index = null;
  2806. this.phase = this.phases.INITIAL;
  2807. this.update_state_from(clone);
  2808. this._done_callbacks = [];
  2809. tests.push(this);
  2810. }
  2811. RemoteTest.prototype.structured_clone = function() {
  2812. var clone = {};
  2813. Object.keys(this).forEach(
  2814. (function(key) {
  2815. var value = this[key];
  2816. // `RemoteTest` instances are responsible for managing
  2817. // their own "done" callback functions, so those functions
  2818. // are not relevant in other execution contexts. Because of
  2819. // this (and because Function values cannot be serialized
  2820. // for cross-realm transmittance), the property should not
  2821. // be considered when cloning instances.
  2822. if (key === '_done_callbacks' ) {
  2823. return;
  2824. }
  2825. if (typeof value === "object" && value !== null) {
  2826. clone[key] = merge({}, value);
  2827. } else {
  2828. clone[key] = value;
  2829. }
  2830. }).bind(this));
  2831. clone.phases = merge({}, this.phases);
  2832. return clone;
  2833. };
  2834. /**
  2835. * `RemoteTest` instances are objects which represent tests running in
  2836. * another realm. They do not define "cleanup" functions (if necessary,
  2837. * such functions are defined on the associated `Test` instance within the
  2838. * external realm). However, `RemoteTests` may have "done" callbacks (e.g.
  2839. * as attached by the `Tests` instance responsible for tracking the overall
  2840. * test status in the parent realm). The `cleanup` method delegates to
  2841. * `done` in order to ensure that such callbacks are invoked following the
  2842. * completion of the `RemoteTest`.
  2843. */
  2844. RemoteTest.prototype.cleanup = function() {
  2845. this.done();
  2846. };
  2847. RemoteTest.prototype.phases = Test.prototype.phases;
  2848. RemoteTest.prototype.update_state_from = function(clone) {
  2849. this.status = clone.status;
  2850. this.message = clone.message;
  2851. this.stack = clone.stack;
  2852. if (this.phase === this.phases.INITIAL) {
  2853. this.phase = this.phases.STARTED;
  2854. }
  2855. };
  2856. RemoteTest.prototype.done = function() {
  2857. this.phase = this.phases.COMPLETE;
  2858. forEach(this._done_callbacks,
  2859. function(callback) {
  2860. callback();
  2861. });
  2862. }
  2863. RemoteTest.prototype.format_status = function() {
  2864. return Test.prototype.status_formats[this.status];
  2865. }
  2866. /*
  2867. * A RemoteContext listens for test events from a remote test context, such
  2868. * as another window or a worker. These events are then used to construct
  2869. * and maintain RemoteTest objects that mirror the tests running in the
  2870. * remote context.
  2871. *
  2872. * An optional third parameter can be used as a predicate to filter incoming
  2873. * MessageEvents.
  2874. */
  2875. function RemoteContext(remote, message_target, message_filter) {
  2876. this.running = true;
  2877. this.started = false;
  2878. this.tests = new Array();
  2879. this.early_exception = null;
  2880. var this_obj = this;
  2881. // If remote context is cross origin assigning to onerror is not
  2882. // possible, so silently catch those errors.
  2883. try {
  2884. remote.onerror = function(error) { this_obj.remote_error(error); };
  2885. } catch (e) {
  2886. // Ignore.
  2887. }
  2888. // Keeping a reference to the remote object and the message handler until
  2889. // remote_done() is seen prevents the remote object and its message channel
  2890. // from going away before all the messages are dispatched.
  2891. this.remote = remote;
  2892. this.message_target = message_target;
  2893. this.message_handler = function(message) {
  2894. var passesFilter = !message_filter || message_filter(message);
  2895. // The reference to the `running` property in the following
  2896. // condition is unnecessary because that value is only set to
  2897. // `false` after the `message_handler` function has been
  2898. // unsubscribed.
  2899. // TODO: Simplify the condition by removing the reference.
  2900. if (this_obj.running && message.data && passesFilter &&
  2901. (message.data.type in this_obj.message_handlers)) {
  2902. this_obj.message_handlers[message.data.type].call(this_obj, message.data);
  2903. }
  2904. };
  2905. if (self.Promise) {
  2906. this.done = new Promise(function(resolve) {
  2907. this_obj.doneResolve = resolve;
  2908. });
  2909. }
  2910. this.message_target.addEventListener("message", this.message_handler);
  2911. }
  2912. RemoteContext.prototype.remote_error = function(error) {
  2913. if (error.preventDefault) {
  2914. error.preventDefault();
  2915. }
  2916. // Defer interpretation of errors until the testing protocol has
  2917. // started and the remote test's `allow_uncaught_exception` property
  2918. // is available.
  2919. if (!this.started) {
  2920. this.early_exception = error;
  2921. } else if (!this.allow_uncaught_exception) {
  2922. this.report_uncaught(error);
  2923. }
  2924. };
  2925. RemoteContext.prototype.report_uncaught = function(error) {
  2926. var message = error.message || String(error);
  2927. var filename = (error.filename ? " " + error.filename: "");
  2928. // FIXME: Display remote error states separately from main document
  2929. // error state.
  2930. tests.set_status(tests.status.ERROR,
  2931. "Error in remote" + filename + ": " + message,
  2932. error.stack);
  2933. };
  2934. RemoteContext.prototype.start = function(data) {
  2935. this.started = true;
  2936. this.allow_uncaught_exception = data.properties.allow_uncaught_exception;
  2937. if (this.early_exception && !this.allow_uncaught_exception) {
  2938. this.report_uncaught(this.early_exception);
  2939. }
  2940. };
  2941. RemoteContext.prototype.test_state = function(data) {
  2942. var remote_test = this.tests[data.test.index];
  2943. if (!remote_test) {
  2944. remote_test = new RemoteTest(data.test);
  2945. this.tests[data.test.index] = remote_test;
  2946. }
  2947. remote_test.update_state_from(data.test);
  2948. tests.notify_test_state(remote_test);
  2949. };
  2950. RemoteContext.prototype.test_done = function(data) {
  2951. var remote_test = this.tests[data.test.index];
  2952. remote_test.update_state_from(data.test);
  2953. remote_test.done();
  2954. tests.result(remote_test);
  2955. };
  2956. RemoteContext.prototype.remote_done = function(data) {
  2957. if (tests.status.status === null &&
  2958. data.status.status !== data.status.OK) {
  2959. tests.set_status(data.status.status, data.status.message, data.status.stack);
  2960. }
  2961. for (let assert of data.asserts) {
  2962. var record = new AssertRecord();
  2963. record.assert_name = assert.assert_name;
  2964. record.args = assert.args;
  2965. record.test = assert.test != null ? this.tests[assert.test.index] : null;
  2966. record.status = assert.status;
  2967. record.stack = assert.stack;
  2968. tests.asserts_run.push(record);
  2969. }
  2970. this.message_target.removeEventListener("message", this.message_handler);
  2971. this.running = false;
  2972. // If remote context is cross origin assigning to onerror is not
  2973. // possible, so silently catch those errors.
  2974. try {
  2975. this.remote.onerror = null;
  2976. } catch (e) {
  2977. // Ignore.
  2978. }
  2979. this.remote = null;
  2980. this.message_target = null;
  2981. if (this.doneResolve) {
  2982. this.doneResolve();
  2983. }
  2984. if (tests.all_done()) {
  2985. tests.complete();
  2986. }
  2987. };
  2988. RemoteContext.prototype.message_handlers = {
  2989. start: RemoteContext.prototype.start,
  2990. test_state: RemoteContext.prototype.test_state,
  2991. result: RemoteContext.prototype.test_done,
  2992. complete: RemoteContext.prototype.remote_done
  2993. };
  2994. /**
  2995. * @class
  2996. * Status of the overall harness
  2997. */
  2998. function TestsStatus()
  2999. {
  3000. /** The status code */
  3001. this.status = null;
  3002. /** Message in case of failure */
  3003. this.message = null;
  3004. /** Stack trace in case of an exception. */
  3005. this.stack = null;
  3006. }
  3007. /**
  3008. * Enum of possible harness statuses.
  3009. *
  3010. * :values:
  3011. * - ``OK``
  3012. * - ``ERROR``
  3013. * - ``TIMEOUT``
  3014. * - ``PRECONDITION_FAILED``
  3015. */
  3016. TestsStatus.statuses = {
  3017. OK:0,
  3018. ERROR:1,
  3019. TIMEOUT:2,
  3020. PRECONDITION_FAILED:3
  3021. };
  3022. TestsStatus.prototype = merge({}, TestsStatus.statuses);
  3023. TestsStatus.prototype.formats = {
  3024. 0: "OK",
  3025. 1: "Error",
  3026. 2: "Timeout",
  3027. 3: "Optional Feature Unsupported"
  3028. };
  3029. TestsStatus.prototype.structured_clone = function()
  3030. {
  3031. if (!this._structured_clone) {
  3032. var msg = this.message;
  3033. msg = msg ? String(msg) : msg;
  3034. this._structured_clone = merge({
  3035. status:this.status,
  3036. message:msg,
  3037. stack:this.stack
  3038. }, TestsStatus.statuses);
  3039. }
  3040. return this._structured_clone;
  3041. };
  3042. TestsStatus.prototype.format_status = function() {
  3043. return this.formats[this.status];
  3044. };
  3045. /**
  3046. * @class
  3047. * Record of an assert that ran.
  3048. *
  3049. * @param {Test} test - The test which ran the assert.
  3050. * @param {string} assert_name - The function name of the assert.
  3051. * @param {Any} args - The arguments passed to the assert function.
  3052. */
  3053. function AssertRecord(test, assert_name, args = []) {
  3054. /** Name of the assert that ran */
  3055. this.assert_name = assert_name;
  3056. /** Test that ran the assert */
  3057. this.test = test;
  3058. // Avoid keeping complex objects alive
  3059. /** Stringification of the arguments that were passed to the assert function */
  3060. this.args = args.map(x => format_value(x).replace(/\n/g, " "));
  3061. /** Status of the assert */
  3062. this.status = null;
  3063. }
  3064. AssertRecord.prototype.structured_clone = function() {
  3065. return {
  3066. assert_name: this.assert_name,
  3067. test: this.test ? this.test.structured_clone() : null,
  3068. args: this.args,
  3069. status: this.status,
  3070. };
  3071. };
  3072. function Tests()
  3073. {
  3074. this.tests = [];
  3075. this.num_pending = 0;
  3076. this.phases = {
  3077. INITIAL:0,
  3078. SETUP:1,
  3079. HAVE_TESTS:2,
  3080. HAVE_RESULTS:3,
  3081. COMPLETE:4
  3082. };
  3083. this.phase = this.phases.INITIAL;
  3084. this.properties = {};
  3085. this.wait_for_finish = false;
  3086. this.processing_callbacks = false;
  3087. this.allow_uncaught_exception = false;
  3088. this.file_is_test = false;
  3089. // This value is lazily initialized in order to avoid introducing a
  3090. // dependency on ECMAScript 2015 Promises to all tests.
  3091. this.promise_tests = null;
  3092. this.promise_setup_called = false;
  3093. this.timeout_multiplier = 1;
  3094. this.timeout_length = test_environment.test_timeout();
  3095. this.timeout_id = null;
  3096. this.start_callbacks = [];
  3097. this.test_state_callbacks = [];
  3098. this.test_done_callbacks = [];
  3099. this.all_done_callbacks = [];
  3100. this.hide_test_state = false;
  3101. this.pending_remotes = [];
  3102. this.current_test = null;
  3103. this.asserts_run = [];
  3104. // Track whether output is enabled, and thus whether or not we should
  3105. // track asserts.
  3106. //
  3107. // On workers we don't get properties set from testharnessreport.js, so
  3108. // we don't know whether or not to track asserts. To avoid the
  3109. // resulting performance hit, we assume we are not meant to. This means
  3110. // that assert tracking does not function on workers.
  3111. this.output = settings.output && 'document' in global_scope;
  3112. this.status = new TestsStatus();
  3113. var this_obj = this;
  3114. test_environment.add_on_loaded_callback(function() {
  3115. if (this_obj.all_done()) {
  3116. this_obj.complete();
  3117. }
  3118. });
  3119. this.set_timeout();
  3120. }
  3121. Tests.prototype.setup = function(func, properties)
  3122. {
  3123. if (this.phase >= this.phases.HAVE_RESULTS) {
  3124. return;
  3125. }
  3126. if (this.phase < this.phases.SETUP) {
  3127. this.phase = this.phases.SETUP;
  3128. }
  3129. this.properties = properties;
  3130. for (var p in properties) {
  3131. if (properties.hasOwnProperty(p)) {
  3132. var value = properties[p];
  3133. if (p == "allow_uncaught_exception") {
  3134. this.allow_uncaught_exception = value;
  3135. } else if (p == "explicit_done" && value) {
  3136. this.wait_for_finish = true;
  3137. } else if (p == "explicit_timeout" && value) {
  3138. this.timeout_length = null;
  3139. if (this.timeout_id)
  3140. {
  3141. clearTimeout(this.timeout_id);
  3142. }
  3143. } else if (p == "single_test" && value) {
  3144. this.set_file_is_test();
  3145. } else if (p == "timeout_multiplier") {
  3146. this.timeout_multiplier = value;
  3147. if (this.timeout_length) {
  3148. this.timeout_length *= this.timeout_multiplier;
  3149. }
  3150. } else if (p == "hide_test_state") {
  3151. this.hide_test_state = value;
  3152. } else if (p == "output") {
  3153. this.output = value;
  3154. } else if (p === "debug") {
  3155. settings.debug = value;
  3156. }
  3157. }
  3158. }
  3159. if (func) {
  3160. try {
  3161. func();
  3162. } catch (e) {
  3163. this.status.status = e instanceof OptionalFeatureUnsupportedError ? this.status.PRECONDITION_FAILED : this.status.ERROR;
  3164. this.status.message = String(e);
  3165. this.status.stack = e.stack ? e.stack : null;
  3166. this.complete();
  3167. }
  3168. }
  3169. this.set_timeout();
  3170. };
  3171. Tests.prototype.set_file_is_test = function() {
  3172. if (this.tests.length > 0) {
  3173. throw new Error("Tried to set file as test after creating a test");
  3174. }
  3175. this.wait_for_finish = true;
  3176. this.file_is_test = true;
  3177. // Create the test, which will add it to the list of tests
  3178. tests.current_test = async_test();
  3179. };
  3180. Tests.prototype.set_status = function(status, message, stack)
  3181. {
  3182. this.status.status = status;
  3183. this.status.message = message;
  3184. this.status.stack = stack ? stack : null;
  3185. };
  3186. Tests.prototype.set_timeout = function() {
  3187. if (global_scope.clearTimeout) {
  3188. var this_obj = this;
  3189. clearTimeout(this.timeout_id);
  3190. if (this.timeout_length !== null) {
  3191. this.timeout_id = setTimeout(function() {
  3192. this_obj.timeout();
  3193. }, this.timeout_length);
  3194. }
  3195. }
  3196. };
  3197. Tests.prototype.timeout = function() {
  3198. var test_in_cleanup = null;
  3199. if (this.status.status === null) {
  3200. forEach(this.tests,
  3201. function(test) {
  3202. // No more than one test is expected to be in the
  3203. // "CLEANUP" phase at any time
  3204. if (test.phase === test.phases.CLEANING) {
  3205. test_in_cleanup = test;
  3206. }
  3207. test.phase = test.phases.COMPLETE;
  3208. });
  3209. // Timeouts that occur while a test is in the "cleanup" phase
  3210. // indicate that some global state was not properly reverted. This
  3211. // invalidates the overall test execution, so the timeout should be
  3212. // reported as an error and cancel the execution of any remaining
  3213. // tests.
  3214. if (test_in_cleanup) {
  3215. this.status.status = this.status.ERROR;
  3216. this.status.message = "Timeout while running cleanup for " +
  3217. "test named \"" + test_in_cleanup.name + "\".";
  3218. tests.status.stack = null;
  3219. } else {
  3220. this.status.status = this.status.TIMEOUT;
  3221. }
  3222. }
  3223. this.complete();
  3224. };
  3225. Tests.prototype.end_wait = function()
  3226. {
  3227. this.wait_for_finish = false;
  3228. if (this.all_done()) {
  3229. this.complete();
  3230. }
  3231. };
  3232. Tests.prototype.push = function(test)
  3233. {
  3234. if (this.phase < this.phases.HAVE_TESTS) {
  3235. this.start();
  3236. }
  3237. this.num_pending++;
  3238. test.index = this.tests.push(test);
  3239. this.notify_test_state(test);
  3240. };
  3241. Tests.prototype.notify_test_state = function(test) {
  3242. var this_obj = this;
  3243. forEach(this.test_state_callbacks,
  3244. function(callback) {
  3245. callback(test, this_obj);
  3246. });
  3247. };
  3248. Tests.prototype.all_done = function() {
  3249. return (this.tests.length > 0 || this.pending_remotes.length > 0) &&
  3250. test_environment.all_loaded &&
  3251. (this.num_pending === 0 || this.is_aborted) && !this.wait_for_finish &&
  3252. !this.processing_callbacks &&
  3253. !this.pending_remotes.some(function(w) { return w.running; });
  3254. };
  3255. Tests.prototype.start = function() {
  3256. this.phase = this.phases.HAVE_TESTS;
  3257. this.notify_start();
  3258. };
  3259. Tests.prototype.notify_start = function() {
  3260. var this_obj = this;
  3261. forEach (this.start_callbacks,
  3262. function(callback)
  3263. {
  3264. callback(this_obj.properties);
  3265. });
  3266. };
  3267. Tests.prototype.result = function(test)
  3268. {
  3269. // If the harness has already transitioned beyond the `HAVE_RESULTS`
  3270. // phase, subsequent tests should not cause it to revert.
  3271. if (this.phase <= this.phases.HAVE_RESULTS) {
  3272. this.phase = this.phases.HAVE_RESULTS;
  3273. }
  3274. this.num_pending--;
  3275. this.notify_result(test);
  3276. };
  3277. Tests.prototype.notify_result = function(test) {
  3278. var this_obj = this;
  3279. this.processing_callbacks = true;
  3280. forEach(this.test_done_callbacks,
  3281. function(callback)
  3282. {
  3283. callback(test, this_obj);
  3284. });
  3285. this.processing_callbacks = false;
  3286. if (this_obj.all_done()) {
  3287. this_obj.complete();
  3288. }
  3289. };
  3290. Tests.prototype.complete = function() {
  3291. if (this.phase === this.phases.COMPLETE) {
  3292. return;
  3293. }
  3294. var this_obj = this;
  3295. var all_complete = function() {
  3296. this_obj.phase = this_obj.phases.COMPLETE;
  3297. this_obj.notify_complete();
  3298. };
  3299. var incomplete = filter(this.tests,
  3300. function(test) {
  3301. return test.phase < test.phases.COMPLETE;
  3302. });
  3303. /**
  3304. * To preserve legacy behavior, overall test completion must be
  3305. * signaled synchronously.
  3306. */
  3307. if (incomplete.length === 0) {
  3308. all_complete();
  3309. return;
  3310. }
  3311. all_async(incomplete,
  3312. function(test, testDone)
  3313. {
  3314. if (test.phase === test.phases.INITIAL) {
  3315. test.phase = test.phases.COMPLETE;
  3316. testDone();
  3317. } else {
  3318. add_test_done_callback(test, testDone);
  3319. test.cleanup();
  3320. }
  3321. },
  3322. all_complete);
  3323. };
  3324. Tests.prototype.set_assert = function(assert_name, args) {
  3325. this.asserts_run.push(new AssertRecord(this.current_test, assert_name, args))
  3326. }
  3327. Tests.prototype.set_assert_status = function(status, stack) {
  3328. let assert_record = this.asserts_run[this.asserts_run.length - 1];
  3329. assert_record.status = status;
  3330. assert_record.stack = stack;
  3331. }
  3332. /**
  3333. * Update the harness status to reflect an unrecoverable harness error that
  3334. * should cancel all further testing. Update all previously-defined tests
  3335. * which have not yet started to indicate that they will not be executed.
  3336. */
  3337. Tests.prototype.abort = function() {
  3338. this.status.status = this.status.ERROR;
  3339. this.is_aborted = true;
  3340. forEach(this.tests,
  3341. function(test) {
  3342. if (test.phase === test.phases.INITIAL) {
  3343. test.phase = test.phases.COMPLETE;
  3344. }
  3345. });
  3346. };
  3347. /*
  3348. * Determine if any tests share the same `name` property. Return an array
  3349. * containing the names of any such duplicates.
  3350. */
  3351. Tests.prototype.find_duplicates = function() {
  3352. var names = Object.create(null);
  3353. var duplicates = [];
  3354. forEach (this.tests,
  3355. function(test)
  3356. {
  3357. if (test.name in names && duplicates.indexOf(test.name) === -1) {
  3358. duplicates.push(test.name);
  3359. }
  3360. names[test.name] = true;
  3361. });
  3362. return duplicates;
  3363. };
  3364. function code_unit_str(char) {
  3365. return 'U+' + char.charCodeAt(0).toString(16);
  3366. }
  3367. function sanitize_unpaired_surrogates(str) {
  3368. return str.replace(
  3369. /([\ud800-\udbff]+)(?![\udc00-\udfff])|(^|[^\ud800-\udbff])([\udc00-\udfff]+)/g,
  3370. function(_, low, prefix, high) {
  3371. var output = prefix || ""; // prefix may be undefined
  3372. var string = low || high; // only one of these alternates can match
  3373. for (var i = 0; i < string.length; i++) {
  3374. output += code_unit_str(string[i]);
  3375. }
  3376. return output;
  3377. });
  3378. }
  3379. function sanitize_all_unpaired_surrogates(tests) {
  3380. forEach (tests,
  3381. function (test)
  3382. {
  3383. var sanitized = sanitize_unpaired_surrogates(test.name);
  3384. if (test.name !== sanitized) {
  3385. test.name = sanitized;
  3386. delete test._structured_clone;
  3387. }
  3388. });
  3389. }
  3390. Tests.prototype.notify_complete = function() {
  3391. var this_obj = this;
  3392. var duplicates;
  3393. if (this.status.status === null) {
  3394. duplicates = this.find_duplicates();
  3395. // Some transports adhere to UTF-8's restriction on unpaired
  3396. // surrogates. Sanitize the titles so that the results can be
  3397. // consistently sent via all transports.
  3398. sanitize_all_unpaired_surrogates(this.tests);
  3399. // Test names are presumed to be unique within test files--this
  3400. // allows consumers to use them for identification purposes.
  3401. // Duplicated names violate this expectation and should therefore
  3402. // be reported as an error.
  3403. if (duplicates.length) {
  3404. this.status.status = this.status.ERROR;
  3405. this.status.message =
  3406. duplicates.length + ' duplicate test name' +
  3407. (duplicates.length > 1 ? 's' : '') + ': "' +
  3408. duplicates.join('", "') + '"';
  3409. } else {
  3410. this.status.status = this.status.OK;
  3411. }
  3412. }
  3413. forEach (this.all_done_callbacks,
  3414. function(callback)
  3415. {
  3416. callback(this_obj.tests, this_obj.status, this_obj.asserts_run);
  3417. });
  3418. };
  3419. /*
  3420. * Constructs a RemoteContext that tracks tests from a specific worker.
  3421. */
  3422. Tests.prototype.create_remote_worker = function(worker) {
  3423. var message_port;
  3424. if (is_service_worker(worker)) {
  3425. message_port = navigator.serviceWorker;
  3426. worker.postMessage({type: "connect"});
  3427. } else if (is_shared_worker(worker)) {
  3428. message_port = worker.port;
  3429. message_port.start();
  3430. } else {
  3431. message_port = worker;
  3432. }
  3433. return new RemoteContext(worker, message_port);
  3434. };
  3435. /*
  3436. * Constructs a RemoteContext that tracks tests from a specific window.
  3437. */
  3438. Tests.prototype.create_remote_window = function(remote) {
  3439. remote.postMessage({type: "getmessages"}, "*");
  3440. return new RemoteContext(
  3441. remote,
  3442. window,
  3443. function(msg) {
  3444. return msg.source === remote;
  3445. }
  3446. );
  3447. };
  3448. Tests.prototype.fetch_tests_from_worker = function(worker) {
  3449. if (this.phase >= this.phases.COMPLETE) {
  3450. return;
  3451. }
  3452. var remoteContext = this.create_remote_worker(worker);
  3453. this.pending_remotes.push(remoteContext);
  3454. return remoteContext.done;
  3455. };
  3456. /**
  3457. * Get test results from a worker and include them in the current test.
  3458. *
  3459. * @param {Worker|SharedWorker|ServiceWorker|MessagePort} port -
  3460. * Either a worker object or a port connected to a worker which is
  3461. * running tests..
  3462. * @returns {Promise} - A promise that's resolved once all the remote tests are complete.
  3463. */
  3464. function fetch_tests_from_worker(port) {
  3465. return tests.fetch_tests_from_worker(port);
  3466. }
  3467. expose(fetch_tests_from_worker, 'fetch_tests_from_worker');
  3468. Tests.prototype.fetch_tests_from_window = function(remote) {
  3469. if (this.phase >= this.phases.COMPLETE) {
  3470. return;
  3471. }
  3472. this.pending_remotes.push(this.create_remote_window(remote));
  3473. };
  3474. /**
  3475. * Aggregate tests from separate windows or iframes
  3476. * into the current document as if they were all part of the same test file.
  3477. *
  3478. * The document of the second window (or iframe) should include
  3479. * ``testharness.js``, but not ``testharnessreport.js``, and use
  3480. * :js:func:`test`, :js:func:`async_test`, and :js:func:`promise_test` in
  3481. * the usual manner.
  3482. *
  3483. * @param {Window} window - The window to fetch tests from.
  3484. */
  3485. function fetch_tests_from_window(window) {
  3486. tests.fetch_tests_from_window(window);
  3487. }
  3488. expose(fetch_tests_from_window, 'fetch_tests_from_window');
  3489. /**
  3490. * Get test results from a shadow realm and include them in the current test.
  3491. *
  3492. * @param {ShadowRealm} realm - A shadow realm also running the test harness
  3493. * @returns {Promise} - A promise that's resolved once all the remote tests are complete.
  3494. */
  3495. function fetch_tests_from_shadow_realm(realm) {
  3496. var chan = new MessageChannel();
  3497. function receiveMessage(msg_json) {
  3498. chan.port1.postMessage(JSON.parse(msg_json));
  3499. }
  3500. var done = tests.fetch_tests_from_worker(chan.port2);
  3501. realm.evaluate("begin_shadow_realm_tests")(receiveMessage);
  3502. chan.port2.start();
  3503. return done;
  3504. }
  3505. expose(fetch_tests_from_shadow_realm, 'fetch_tests_from_shadow_realm');
  3506. /**
  3507. * Begin running tests in this shadow realm test harness.
  3508. *
  3509. * To be called after all tests have been loaded; it is an error to call
  3510. * this more than once or in a non-Shadow Realm environment
  3511. *
  3512. * @param {Function} postMessage - A function to send test updates to the
  3513. * incubating realm-- accepts JSON-encoded messages in the format used by
  3514. * RemoteContext
  3515. */
  3516. function begin_shadow_realm_tests(postMessage) {
  3517. if (!(test_environment instanceof ShadowRealmTestEnvironment)) {
  3518. throw new Error("beign_shadow_realm_tests called in non-Shadow Realm environment");
  3519. }
  3520. test_environment.begin(function (msg) {
  3521. postMessage(JSON.stringify(msg));
  3522. });
  3523. }
  3524. expose(begin_shadow_realm_tests, 'begin_shadow_realm_tests');
  3525. /**
  3526. * Timeout the tests.
  3527. *
  3528. * This only has an effect when ``explict_timeout`` has been set
  3529. * in :js:func:`setup`. In other cases any call is a no-op.
  3530. *
  3531. */
  3532. function timeout() {
  3533. if (tests.timeout_length === null) {
  3534. tests.timeout();
  3535. }
  3536. }
  3537. expose(timeout, 'timeout');
  3538. /**
  3539. * Add a callback that's triggered when the first :js:class:`Test` is created.
  3540. *
  3541. * @param {Function} callback - Callback function. This is called
  3542. * without arguments.
  3543. */
  3544. function add_start_callback(callback) {
  3545. tests.start_callbacks.push(callback);
  3546. }
  3547. /**
  3548. * Add a callback that's triggered when a test state changes.
  3549. *
  3550. * @param {Function} callback - Callback function, called with the
  3551. * :js:class:`Test` as the only argument.
  3552. */
  3553. function add_test_state_callback(callback) {
  3554. tests.test_state_callbacks.push(callback);
  3555. }
  3556. /**
  3557. * Add a callback that's triggered when a test result is received.
  3558. *
  3559. * @param {Function} callback - Callback function, called with the
  3560. * :js:class:`Test` as the only argument.
  3561. */
  3562. function add_result_callback(callback) {
  3563. tests.test_done_callbacks.push(callback);
  3564. }
  3565. /**
  3566. * Add a callback that's triggered when all tests are complete.
  3567. *
  3568. * @param {Function} callback - Callback function, called with an
  3569. * array of :js:class:`Test` objects, a :js:class:`TestsStatus`
  3570. * object and an array of :js:class:`AssertRecord` objects. If the
  3571. * debug setting is ``false`` the final argument will be an empty
  3572. * array.
  3573. *
  3574. * For performance reasons asserts are only tracked when the debug
  3575. * setting is ``true``. In other cases the array of asserts will be
  3576. * empty.
  3577. */
  3578. function add_completion_callback(callback) {
  3579. tests.all_done_callbacks.push(callback);
  3580. }
  3581. expose(add_start_callback, 'add_start_callback');
  3582. expose(add_test_state_callback, 'add_test_state_callback');
  3583. expose(add_result_callback, 'add_result_callback');
  3584. expose(add_completion_callback, 'add_completion_callback');
  3585. function remove(array, item) {
  3586. var index = array.indexOf(item);
  3587. if (index > -1) {
  3588. array.splice(index, 1);
  3589. }
  3590. }
  3591. function remove_start_callback(callback) {
  3592. remove(tests.start_callbacks, callback);
  3593. }
  3594. function remove_test_state_callback(callback) {
  3595. remove(tests.test_state_callbacks, callback);
  3596. }
  3597. function remove_result_callback(callback) {
  3598. remove(tests.test_done_callbacks, callback);
  3599. }
  3600. function remove_completion_callback(callback) {
  3601. remove(tests.all_done_callbacks, callback);
  3602. }
  3603. /*
  3604. * Output listener
  3605. */
  3606. function Output() {
  3607. this.output_document = document;
  3608. this.output_node = null;
  3609. this.enabled = settings.output;
  3610. this.phase = this.INITIAL;
  3611. }
  3612. Output.prototype.INITIAL = 0;
  3613. Output.prototype.STARTED = 1;
  3614. Output.prototype.HAVE_RESULTS = 2;
  3615. Output.prototype.COMPLETE = 3;
  3616. Output.prototype.setup = function(properties) {
  3617. if (this.phase > this.INITIAL) {
  3618. return;
  3619. }
  3620. //If output is disabled in testharnessreport.js the test shouldn't be
  3621. //able to override that
  3622. this.enabled = this.enabled && (properties.hasOwnProperty("output") ?
  3623. properties.output : settings.output);
  3624. };
  3625. Output.prototype.init = function(properties) {
  3626. if (this.phase >= this.STARTED) {
  3627. return;
  3628. }
  3629. if (properties.output_document) {
  3630. this.output_document = properties.output_document;
  3631. } else {
  3632. this.output_document = document;
  3633. }
  3634. this.phase = this.STARTED;
  3635. };
  3636. Output.prototype.resolve_log = function() {
  3637. var output_document;
  3638. if (this.output_node) {
  3639. return;
  3640. }
  3641. if (typeof this.output_document === "function") {
  3642. output_document = this.output_document.apply(undefined);
  3643. } else {
  3644. output_document = this.output_document;
  3645. }
  3646. if (!output_document) {
  3647. return;
  3648. }
  3649. var node = output_document.getElementById("log");
  3650. if (!node) {
  3651. if (output_document.readyState === "loading") {
  3652. return;
  3653. }
  3654. node = output_document.createElementNS("http://www.w3.org/1999/xhtml", "div");
  3655. node.id = "log";
  3656. if (output_document.body) {
  3657. output_document.body.appendChild(node);
  3658. } else {
  3659. var root = output_document.documentElement;
  3660. var is_html = (root &&
  3661. root.namespaceURI == "http://www.w3.org/1999/xhtml" &&
  3662. root.localName == "html");
  3663. var is_svg = (output_document.defaultView &&
  3664. "SVGSVGElement" in output_document.defaultView &&
  3665. root instanceof output_document.defaultView.SVGSVGElement);
  3666. if (is_svg) {
  3667. var foreignObject = output_document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
  3668. foreignObject.setAttribute("width", "100%");
  3669. foreignObject.setAttribute("height", "100%");
  3670. root.appendChild(foreignObject);
  3671. foreignObject.appendChild(node);
  3672. } else if (is_html) {
  3673. root.appendChild(output_document.createElementNS("http://www.w3.org/1999/xhtml", "body"))
  3674. .appendChild(node);
  3675. } else {
  3676. root.appendChild(node);
  3677. }
  3678. }
  3679. }
  3680. this.output_document = output_document;
  3681. this.output_node = node;
  3682. };
  3683. Output.prototype.show_status = function() {
  3684. if (this.phase < this.STARTED) {
  3685. this.init({});
  3686. }
  3687. if (!this.enabled || this.phase === this.COMPLETE) {
  3688. return;
  3689. }
  3690. this.resolve_log();
  3691. if (this.phase < this.HAVE_RESULTS) {
  3692. this.phase = this.HAVE_RESULTS;
  3693. }
  3694. var done_count = tests.tests.length - tests.num_pending;
  3695. if (this.output_node && !tests.hide_test_state) {
  3696. if (done_count < 100 ||
  3697. (done_count < 1000 && done_count % 100 === 0) ||
  3698. done_count % 1000 === 0) {
  3699. this.output_node.textContent = "Running, " +
  3700. done_count + " complete, " +
  3701. tests.num_pending + " remain";
  3702. }
  3703. }
  3704. };
  3705. Output.prototype.show_results = function (tests, harness_status, asserts_run) {
  3706. if (this.phase >= this.COMPLETE) {
  3707. return;
  3708. }
  3709. if (!this.enabled) {
  3710. return;
  3711. }
  3712. if (!this.output_node) {
  3713. this.resolve_log();
  3714. }
  3715. this.phase = this.COMPLETE;
  3716. var log = this.output_node;
  3717. if (!log) {
  3718. return;
  3719. }
  3720. var output_document = this.output_document;
  3721. while (log.lastChild) {
  3722. log.removeChild(log.lastChild);
  3723. }
  3724. var stylesheet = output_document.createElementNS(xhtml_ns, "style");
  3725. stylesheet.textContent = stylesheetContent;
  3726. var heads = output_document.getElementsByTagName("head");
  3727. if (heads.length) {
  3728. heads[0].appendChild(stylesheet);
  3729. }
  3730. var status_number = {};
  3731. forEach(tests,
  3732. function(test) {
  3733. var status = test.format_status();
  3734. if (status_number.hasOwnProperty(status)) {
  3735. status_number[status] += 1;
  3736. } else {
  3737. status_number[status] = 1;
  3738. }
  3739. });
  3740. function status_class(status)
  3741. {
  3742. return status.replace(/\s/g, '').toLowerCase();
  3743. }
  3744. var summary_template = ["section", {"id":"summary"},
  3745. ["h2", {}, "Summary"],
  3746. function()
  3747. {
  3748. var status = harness_status.format_status();
  3749. var rv = [["section", {},
  3750. ["p", {},
  3751. "Harness status: ",
  3752. ["span", {"class":status_class(status)},
  3753. status
  3754. ],
  3755. ],
  3756. ["button",
  3757. {"onclick": "let evt = new Event('__test_restart'); " +
  3758. "let canceled = !window.dispatchEvent(evt);" +
  3759. "if (!canceled) { location.reload() }"},
  3760. "Rerun"]
  3761. ]];
  3762. if (harness_status.status === harness_status.ERROR) {
  3763. rv[0].push(["pre", {}, harness_status.message]);
  3764. if (harness_status.stack) {
  3765. rv[0].push(["pre", {}, harness_status.stack]);
  3766. }
  3767. }
  3768. return rv;
  3769. },
  3770. ["p", {}, "Found ${num_tests} tests"],
  3771. function() {
  3772. var rv = [["div", {}]];
  3773. var i = 0;
  3774. while (Test.prototype.status_formats.hasOwnProperty(i)) {
  3775. if (status_number.hasOwnProperty(Test.prototype.status_formats[i])) {
  3776. var status = Test.prototype.status_formats[i];
  3777. rv[0].push(["div", {},
  3778. ["label", {},
  3779. ["input", {type:"checkbox", checked:"checked"}],
  3780. status_number[status] + " ",
  3781. ["span", {"class":status_class(status)}, status]]]);
  3782. }
  3783. i++;
  3784. }
  3785. return rv;
  3786. },
  3787. ];
  3788. log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
  3789. forEach(output_document.querySelectorAll("section#summary label"),
  3790. function(element)
  3791. {
  3792. on_event(element, "click",
  3793. function(e)
  3794. {
  3795. if (output_document.getElementById("results") === null) {
  3796. e.preventDefault();
  3797. return;
  3798. }
  3799. var result_class = element.querySelector("span[class]").getAttribute("class");
  3800. var style_element = output_document.querySelector("style#hide-" + result_class);
  3801. var input_element = element.querySelector("input");
  3802. if (!style_element && !input_element.checked) {
  3803. style_element = output_document.createElementNS(xhtml_ns, "style");
  3804. style_element.id = "hide-" + result_class;
  3805. style_element.textContent = "table#results > tbody > tr.overall-"+result_class+"{display:none}";
  3806. output_document.body.appendChild(style_element);
  3807. } else if (style_element && input_element.checked) {
  3808. style_element.parentNode.removeChild(style_element);
  3809. }
  3810. });
  3811. });
  3812. // This use of innerHTML plus manual escaping is not recommended in
  3813. // general, but is necessary here for performance. Using textContent
  3814. // on each individual <td> adds tens of seconds of execution time for
  3815. // large test suites (tens of thousands of tests).
  3816. function escape_html(s)
  3817. {
  3818. return s.replace(/\&/g, "&amp;")
  3819. .replace(/</g, "&lt;")
  3820. .replace(/"/g, "&quot;")
  3821. .replace(/'/g, "&#39;");
  3822. }
  3823. function has_assertions()
  3824. {
  3825. for (var i = 0; i < tests.length; i++) {
  3826. if (tests[i].properties.hasOwnProperty("assert")) {
  3827. return true;
  3828. }
  3829. }
  3830. return false;
  3831. }
  3832. function get_assertion(test)
  3833. {
  3834. if (test.properties.hasOwnProperty("assert")) {
  3835. if (Array.isArray(test.properties.assert)) {
  3836. return test.properties.assert.join(' ');
  3837. }
  3838. return test.properties.assert;
  3839. }
  3840. return '';
  3841. }
  3842. var asserts_run_by_test = new Map();
  3843. asserts_run.forEach(assert => {
  3844. if (!asserts_run_by_test.has(assert.test)) {
  3845. asserts_run_by_test.set(assert.test, []);
  3846. }
  3847. asserts_run_by_test.get(assert.test).push(assert);
  3848. });
  3849. function get_asserts_output(test) {
  3850. var asserts = asserts_run_by_test.get(test);
  3851. if (!asserts) {
  3852. return "No asserts ran";
  3853. }
  3854. rv = "<table>";
  3855. rv += asserts.map(assert => {
  3856. var output_fn = "<strong>" + escape_html(assert.assert_name) + "</strong>(";
  3857. var prefix_len = output_fn.length;
  3858. var output_args = assert.args;
  3859. var output_len = output_args.reduce((prev, current) => prev+current, prefix_len);
  3860. if (output_len[output_len.length - 1] > 50) {
  3861. output_args = output_args.map((x, i) =>
  3862. (i > 0 ? " ".repeat(prefix_len) : "" )+ x + (i < output_args.length - 1 ? ",\n" : ""));
  3863. } else {
  3864. output_args = output_args.map((x, i) => x + (i < output_args.length - 1 ? ", " : ""));
  3865. }
  3866. output_fn += escape_html(output_args.join(""));
  3867. output_fn += ')';
  3868. var output_location;
  3869. if (assert.stack) {
  3870. output_location = assert.stack.split("\n", 1)[0].replace(/@?\w+:\/\/[^ "\/]+(?::\d+)?/g, " ");
  3871. }
  3872. return "<tr class='overall-" +
  3873. status_class(Test.prototype.status_formats[assert.status]) + "'>" +
  3874. "<td class='" +
  3875. status_class(Test.prototype.status_formats[assert.status]) + "'>" +
  3876. Test.prototype.status_formats[assert.status] + "</td>" +
  3877. "<td><pre>" +
  3878. output_fn +
  3879. (output_location ? "\n" + escape_html(output_location) : "") +
  3880. "</pre></td></tr>";
  3881. }
  3882. ).join("\n");
  3883. rv += "</table>";
  3884. return rv;
  3885. }
  3886. log.appendChild(document.createElementNS(xhtml_ns, "section"));
  3887. var assertions = has_assertions();
  3888. var html = "<h2>Details</h2><table id='results' " + (assertions ? "class='assertions'" : "" ) + ">" +
  3889. "<thead><tr><th>Result</th><th>Test Name</th>" +
  3890. (assertions ? "<th>Assertion</th>" : "") +
  3891. "<th>Message</th></tr></thead>" +
  3892. "<tbody>";
  3893. for (var i = 0; i < tests.length; i++) {
  3894. var test = tests[i];
  3895. html += '<tr class="overall-' +
  3896. status_class(test.format_status()) +
  3897. '">' +
  3898. '<td class="' +
  3899. status_class(test.format_status()) +
  3900. '">' +
  3901. test.format_status() +
  3902. "</td><td>" +
  3903. escape_html(test.name) +
  3904. "</td><td>" +
  3905. (assertions ? escape_html(get_assertion(test)) + "</td><td>" : "") +
  3906. escape_html(test.message ? tests[i].message : " ") +
  3907. (tests[i].stack ? "<pre>" +
  3908. escape_html(tests[i].stack) +
  3909. "</pre>": "");
  3910. if (!(test instanceof RemoteTest)) {
  3911. html += "<details><summary>Asserts run</summary>" + get_asserts_output(test) + "</details>"
  3912. }
  3913. html += "</td></tr>";
  3914. }
  3915. html += "</tbody></table>";
  3916. try {
  3917. log.lastChild.innerHTML = html;
  3918. } catch (e) {
  3919. log.appendChild(document.createElementNS(xhtml_ns, "p"))
  3920. .textContent = "Setting innerHTML for the log threw an exception.";
  3921. log.appendChild(document.createElementNS(xhtml_ns, "pre"))
  3922. .textContent = html;
  3923. }
  3924. };
  3925. /*
  3926. * Template code
  3927. *
  3928. * A template is just a JavaScript structure. An element is represented as:
  3929. *
  3930. * [tag_name, {attr_name:attr_value}, child1, child2]
  3931. *
  3932. * the children can either be strings (which act like text nodes), other templates or
  3933. * functions (see below)
  3934. *
  3935. * A text node is represented as
  3936. *
  3937. * ["{text}", value]
  3938. *
  3939. * String values have a simple substitution syntax; ${foo} represents a variable foo.
  3940. *
  3941. * It is possible to embed logic in templates by using a function in a place where a
  3942. * node would usually go. The function must either return part of a template or null.
  3943. *
  3944. * In cases where a set of nodes are required as output rather than a single node
  3945. * with children it is possible to just use a list
  3946. * [node1, node2, node3]
  3947. *
  3948. * Usage:
  3949. *
  3950. * render(template, substitutions) - take a template and an object mapping
  3951. * variable names to parameters and return either a DOM node or a list of DOM nodes
  3952. *
  3953. * substitute(template, substitutions) - take a template and variable mapping object,
  3954. * make the variable substitutions and return the substituted template
  3955. *
  3956. */
  3957. function is_single_node(template)
  3958. {
  3959. return typeof template[0] === "string";
  3960. }
  3961. function substitute(template, substitutions)
  3962. {
  3963. if (typeof template === "function") {
  3964. var replacement = template(substitutions);
  3965. if (!replacement) {
  3966. return null;
  3967. }
  3968. return substitute(replacement, substitutions);
  3969. }
  3970. if (is_single_node(template)) {
  3971. return substitute_single(template, substitutions);
  3972. }
  3973. return filter(map(template, function(x) {
  3974. return substitute(x, substitutions);
  3975. }), function(x) {return x !== null;});
  3976. }
  3977. function substitute_single(template, substitutions)
  3978. {
  3979. var substitution_re = /\$\{([^ }]*)\}/g;
  3980. function do_substitution(input) {
  3981. var components = input.split(substitution_re);
  3982. var rv = [];
  3983. for (var i = 0; i < components.length; i += 2) {
  3984. rv.push(components[i]);
  3985. if (components[i + 1]) {
  3986. rv.push(String(substitutions[components[i + 1]]));
  3987. }
  3988. }
  3989. return rv;
  3990. }
  3991. function substitute_attrs(attrs, rv)
  3992. {
  3993. rv[1] = {};
  3994. for (var name in template[1]) {
  3995. if (attrs.hasOwnProperty(name)) {
  3996. var new_name = do_substitution(name).join("");
  3997. var new_value = do_substitution(attrs[name]).join("");
  3998. rv[1][new_name] = new_value;
  3999. }
  4000. }
  4001. }
  4002. function substitute_children(children, rv)
  4003. {
  4004. for (var i = 0; i < children.length; i++) {
  4005. if (children[i] instanceof Object) {
  4006. var replacement = substitute(children[i], substitutions);
  4007. if (replacement !== null) {
  4008. if (is_single_node(replacement)) {
  4009. rv.push(replacement);
  4010. } else {
  4011. extend(rv, replacement);
  4012. }
  4013. }
  4014. } else {
  4015. extend(rv, do_substitution(String(children[i])));
  4016. }
  4017. }
  4018. return rv;
  4019. }
  4020. var rv = [];
  4021. rv.push(do_substitution(String(template[0])).join(""));
  4022. if (template[0] === "{text}") {
  4023. substitute_children(template.slice(1), rv);
  4024. } else {
  4025. substitute_attrs(template[1], rv);
  4026. substitute_children(template.slice(2), rv);
  4027. }
  4028. return rv;
  4029. }
  4030. function make_dom_single(template, doc)
  4031. {
  4032. var output_document = doc || document;
  4033. var element;
  4034. if (template[0] === "{text}") {
  4035. element = output_document.createTextNode("");
  4036. for (var i = 1; i < template.length; i++) {
  4037. element.data += template[i];
  4038. }
  4039. } else {
  4040. element = output_document.createElementNS(xhtml_ns, template[0]);
  4041. for (var name in template[1]) {
  4042. if (template[1].hasOwnProperty(name)) {
  4043. element.setAttribute(name, template[1][name]);
  4044. }
  4045. }
  4046. for (var i = 2; i < template.length; i++) {
  4047. if (template[i] instanceof Object) {
  4048. var sub_element = make_dom(template[i]);
  4049. element.appendChild(sub_element);
  4050. } else {
  4051. var text_node = output_document.createTextNode(template[i]);
  4052. element.appendChild(text_node);
  4053. }
  4054. }
  4055. }
  4056. return element;
  4057. }
  4058. function make_dom(template, substitutions, output_document)
  4059. {
  4060. if (is_single_node(template)) {
  4061. return make_dom_single(template, output_document);
  4062. }
  4063. return map(template, function(x) {
  4064. return make_dom_single(x, output_document);
  4065. });
  4066. }
  4067. function render(template, substitutions, output_document)
  4068. {
  4069. return make_dom(substitute(template, substitutions), output_document);
  4070. }
  4071. /*
  4072. * Utility functions
  4073. */
  4074. function assert(expected_true, function_name, description, error, substitutions)
  4075. {
  4076. if (expected_true !== true) {
  4077. var msg = make_message(function_name, description,
  4078. error, substitutions);
  4079. throw new AssertionError(msg);
  4080. }
  4081. }
  4082. /**
  4083. * @class
  4084. * Exception type that represents a failing assert.
  4085. *
  4086. * @param {string} message - Error message.
  4087. */
  4088. function AssertionError(message)
  4089. {
  4090. if (typeof message == "string") {
  4091. message = sanitize_unpaired_surrogates(message);
  4092. }
  4093. this.message = message;
  4094. this.stack = get_stack();
  4095. }
  4096. expose(AssertionError, "AssertionError");
  4097. AssertionError.prototype = Object.create(Error.prototype);
  4098. const get_stack = function() {
  4099. var stack = new Error().stack;
  4100. // 'Error.stack' is not supported in all browsers/versions
  4101. if (!stack) {
  4102. return "(Stack trace unavailable)";
  4103. }
  4104. var lines = stack.split("\n");
  4105. // Create a pattern to match stack frames originating within testharness.js. These include the
  4106. // script URL, followed by the line/col (e.g., '/resources/testharness.js:120:21').
  4107. // Escape the URL per http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  4108. // in case it contains RegExp characters.
  4109. var script_url = get_script_url();
  4110. var re_text = script_url ? script_url.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') : "\\btestharness.js";
  4111. var re = new RegExp(re_text + ":\\d+:\\d+");
  4112. // Some browsers include a preamble that specifies the type of the error object. Skip this by
  4113. // advancing until we find the first stack frame originating from testharness.js.
  4114. var i = 0;
  4115. while (!re.test(lines[i]) && i < lines.length) {
  4116. i++;
  4117. }
  4118. // Then skip the top frames originating from testharness.js to begin the stack at the test code.
  4119. while (re.test(lines[i]) && i < lines.length) {
  4120. i++;
  4121. }
  4122. // Paranoid check that we didn't skip all frames. If so, return the original stack unmodified.
  4123. if (i >= lines.length) {
  4124. return stack;
  4125. }
  4126. return lines.slice(i).join("\n");
  4127. }
  4128. function OptionalFeatureUnsupportedError(message)
  4129. {
  4130. AssertionError.call(this, message);
  4131. }
  4132. OptionalFeatureUnsupportedError.prototype = Object.create(AssertionError.prototype);
  4133. expose(OptionalFeatureUnsupportedError, "OptionalFeatureUnsupportedError");
  4134. function make_message(function_name, description, error, substitutions)
  4135. {
  4136. for (var p in substitutions) {
  4137. if (substitutions.hasOwnProperty(p)) {
  4138. substitutions[p] = format_value(substitutions[p]);
  4139. }
  4140. }
  4141. var node_form = substitute(["{text}", "${function_name}: ${description}" + error],
  4142. merge({function_name:function_name,
  4143. description:(description?description + " ":"")},
  4144. substitutions));
  4145. return node_form.slice(1).join("");
  4146. }
  4147. function filter(array, callable, thisObj) {
  4148. var rv = [];
  4149. for (var i = 0; i < array.length; i++) {
  4150. if (array.hasOwnProperty(i)) {
  4151. var pass = callable.call(thisObj, array[i], i, array);
  4152. if (pass) {
  4153. rv.push(array[i]);
  4154. }
  4155. }
  4156. }
  4157. return rv;
  4158. }
  4159. function map(array, callable, thisObj)
  4160. {
  4161. var rv = [];
  4162. rv.length = array.length;
  4163. for (var i = 0; i < array.length; i++) {
  4164. if (array.hasOwnProperty(i)) {
  4165. rv[i] = callable.call(thisObj, array[i], i, array);
  4166. }
  4167. }
  4168. return rv;
  4169. }
  4170. function extend(array, items)
  4171. {
  4172. Array.prototype.push.apply(array, items);
  4173. }
  4174. function forEach(array, callback, thisObj)
  4175. {
  4176. for (var i = 0; i < array.length; i++) {
  4177. if (array.hasOwnProperty(i)) {
  4178. callback.call(thisObj, array[i], i, array);
  4179. }
  4180. }
  4181. }
  4182. /**
  4183. * Immediately invoke a "iteratee" function with a series of values in
  4184. * parallel and invoke a final "done" function when all of the "iteratee"
  4185. * invocations have signaled completion.
  4186. *
  4187. * If all callbacks complete synchronously (or if no callbacks are
  4188. * specified), the ``done_callback`` will be invoked synchronously. It is the
  4189. * responsibility of the caller to ensure asynchronicity in cases where
  4190. * that is desired.
  4191. *
  4192. * @param {array} value Zero or more values to use in the invocation of
  4193. * ``iter_callback``
  4194. * @param {function} iter_callback A function that will be invoked
  4195. * once for each of the values min
  4196. * ``value``. Two arguments will
  4197. * be available in each
  4198. * invocation: the value from
  4199. * ``value`` and a function that
  4200. * must be invoked to signal
  4201. * completion
  4202. * @param {function} done_callback A function that will be invoked after
  4203. * all operations initiated by the
  4204. * ``iter_callback`` function have signaled
  4205. * completion
  4206. */
  4207. function all_async(values, iter_callback, done_callback)
  4208. {
  4209. var remaining = values.length;
  4210. if (remaining === 0) {
  4211. done_callback();
  4212. }
  4213. forEach(values,
  4214. function(element) {
  4215. var invoked = false;
  4216. var elDone = function() {
  4217. if (invoked) {
  4218. return;
  4219. }
  4220. invoked = true;
  4221. remaining -= 1;
  4222. if (remaining === 0) {
  4223. done_callback();
  4224. }
  4225. };
  4226. iter_callback(element, elDone);
  4227. });
  4228. }
  4229. function merge(a,b)
  4230. {
  4231. var rv = {};
  4232. var p;
  4233. for (p in a) {
  4234. rv[p] = a[p];
  4235. }
  4236. for (p in b) {
  4237. rv[p] = b[p];
  4238. }
  4239. return rv;
  4240. }
  4241. function expose(object, name)
  4242. {
  4243. var components = name.split(".");
  4244. var target = global_scope;
  4245. for (var i = 0; i < components.length - 1; i++) {
  4246. if (!(components[i] in target)) {
  4247. target[components[i]] = {};
  4248. }
  4249. target = target[components[i]];
  4250. }
  4251. target[components[components.length - 1]] = object;
  4252. }
  4253. function is_same_origin(w) {
  4254. try {
  4255. 'random_prop' in w;
  4256. return true;
  4257. } catch (e) {
  4258. return false;
  4259. }
  4260. }
  4261. /** Returns the 'src' URL of the first <script> tag in the page to include the file 'testharness.js'. */
  4262. function get_script_url()
  4263. {
  4264. if (!('document' in global_scope)) {
  4265. return undefined;
  4266. }
  4267. var scripts = document.getElementsByTagName("script");
  4268. for (var i = 0; i < scripts.length; i++) {
  4269. var src;
  4270. if (scripts[i].src) {
  4271. src = scripts[i].src;
  4272. } else if (scripts[i].href) {
  4273. //SVG case
  4274. src = scripts[i].href.baseVal;
  4275. }
  4276. var matches = src && src.match(/^(.*\/|)testharness\.js$/);
  4277. if (matches) {
  4278. return src;
  4279. }
  4280. }
  4281. return undefined;
  4282. }
  4283. /** Returns the <title> or filename or "Untitled" */
  4284. function get_title()
  4285. {
  4286. if ('document' in global_scope) {
  4287. //Don't use document.title to work around an Opera/Presto bug in XHTML documents
  4288. var title = document.getElementsByTagName("title")[0];
  4289. if (title && title.firstChild && title.firstChild.data) {
  4290. return title.firstChild.data;
  4291. }
  4292. }
  4293. if ('META_TITLE' in global_scope && META_TITLE) {
  4294. return META_TITLE;
  4295. }
  4296. if ('location' in global_scope) {
  4297. return location.pathname.substring(location.pathname.lastIndexOf('/') + 1, location.pathname.indexOf('.'));
  4298. }
  4299. return "Untitled";
  4300. }
  4301. /**
  4302. * Setup globals
  4303. */
  4304. var tests = new Tests();
  4305. if (global_scope.addEventListener) {
  4306. var error_handler = function(error, message, stack) {
  4307. var optional_unsupported = error instanceof OptionalFeatureUnsupportedError;
  4308. if (tests.file_is_test) {
  4309. var test = tests.tests[0];
  4310. if (test.phase >= test.phases.HAS_RESULT) {
  4311. return;
  4312. }
  4313. var status = optional_unsupported ? test.PRECONDITION_FAILED : test.FAIL;
  4314. test.set_status(status, message, stack);
  4315. test.phase = test.phases.HAS_RESULT;
  4316. } else if (!tests.allow_uncaught_exception) {
  4317. var status = optional_unsupported ? tests.status.PRECONDITION_FAILED : tests.status.ERROR;
  4318. tests.status.status = status;
  4319. tests.status.message = message;
  4320. tests.status.stack = stack;
  4321. }
  4322. // Do not transition to the "complete" phase if the test has been
  4323. // configured to allow uncaught exceptions. This gives the test an
  4324. // opportunity to define subtests based on the exception reporting
  4325. // behavior.
  4326. if (!tests.allow_uncaught_exception) {
  4327. done();
  4328. }
  4329. };
  4330. addEventListener("error", function(e) {
  4331. var message = e.message;
  4332. var stack;
  4333. if (e.error && e.error.stack) {
  4334. stack = e.error.stack;
  4335. } else {
  4336. stack = e.filename + ":" + e.lineno + ":" + e.colno;
  4337. }
  4338. error_handler(e.error, message, stack);
  4339. }, false);
  4340. addEventListener("unhandledrejection", function(e) {
  4341. var message;
  4342. if (e.reason && e.reason.message) {
  4343. message = "Unhandled rejection: " + e.reason.message;
  4344. } else {
  4345. message = "Unhandled rejection";
  4346. }
  4347. var stack;
  4348. if (e.reason && e.reason.stack) {
  4349. stack = e.reason.stack;
  4350. }
  4351. error_handler(e.reason, message, stack);
  4352. }, false);
  4353. }
  4354. test_environment.on_tests_ready();
  4355. /**
  4356. * Stylesheet
  4357. */
  4358. var stylesheetContent = "\
  4359. html {\
  4360. font-family:DejaVu Sans, Bitstream Vera Sans, Arial, Sans;\
  4361. }\
  4362. \
  4363. #log .warning,\
  4364. #log .warning a {\
  4365. color: black;\
  4366. background: yellow;\
  4367. }\
  4368. \
  4369. #log .error,\
  4370. #log .error a {\
  4371. color: white;\
  4372. background: red;\
  4373. }\
  4374. \
  4375. section#summary {\
  4376. margin-bottom:1em;\
  4377. }\
  4378. \
  4379. table#results {\
  4380. border-collapse:collapse;\
  4381. table-layout:fixed;\
  4382. width:100%;\
  4383. }\
  4384. \
  4385. table#results > thead > tr > th:first-child,\
  4386. table#results > tbody > tr > td:first-child {\
  4387. width:8em;\
  4388. }\
  4389. \
  4390. table#results > thead > tr > th:last-child,\
  4391. table#results > thead > tr > td:last-child {\
  4392. width:50%;\
  4393. }\
  4394. \
  4395. table#results.assertions > thead > tr > th:last-child,\
  4396. table#results.assertions > tbody > tr > td:last-child {\
  4397. width:35%;\
  4398. }\
  4399. \
  4400. table#results > thead > > tr > th {\
  4401. padding:0;\
  4402. padding-bottom:0.5em;\
  4403. border-bottom:medium solid black;\
  4404. }\
  4405. \
  4406. table#results > tbody > tr> td {\
  4407. padding:1em;\
  4408. padding-bottom:0.5em;\
  4409. border-bottom:thin solid black;\
  4410. }\
  4411. \
  4412. .pass {\
  4413. color:green;\
  4414. }\
  4415. \
  4416. .fail {\
  4417. color:red;\
  4418. }\
  4419. \
  4420. tr.timeout {\
  4421. color:red;\
  4422. }\
  4423. \
  4424. tr.notrun {\
  4425. color:blue;\
  4426. }\
  4427. \
  4428. tr.optionalunsupported {\
  4429. color:blue;\
  4430. }\
  4431. \
  4432. .ok {\
  4433. color:green;\
  4434. }\
  4435. \
  4436. .error {\
  4437. color:red;\
  4438. }\
  4439. \
  4440. .pass, .fail, .timeout, .notrun, .optionalunsupported .ok, .timeout, .error {\
  4441. font-variant:small-caps;\
  4442. }\
  4443. \
  4444. table#results span {\
  4445. display:block;\
  4446. }\
  4447. \
  4448. table#results span.expected {\
  4449. font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;\
  4450. white-space:pre;\
  4451. }\
  4452. \
  4453. table#results span.actual {\
  4454. font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace;\
  4455. white-space:pre;\
  4456. }\
  4457. ";
  4458. })(self);
  4459. // vim: set expandtab shiftwidth=4 tabstop=4: