Tests.js 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  1. /*
  2. * Copyright (C) 2010 Google Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are
  6. * met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above
  11. * copyright notice, this list of conditions and the following disclaimer
  12. * in the documentation and/or other materials provided with the
  13. * distribution.
  14. * * Neither the name of Google Inc. nor the names of its
  15. * contributors may be used to endorse or promote products derived from
  16. * this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. /* eslint-disable indent */
  31. /**
  32. * @fileoverview This file contains small testing framework along with the
  33. * test suite for the frontend. These tests are a part of the continues build
  34. * and are executed by the devtools_sanity_unittest.cc as a part of the
  35. * Interactive UI Test suite.
  36. * FIXME: change field naming style to use trailing underscore.
  37. */
  38. (function createTestSuite(window) {
  39. /**
  40. * @unrestricted
  41. */
  42. const TestSuite = class {
  43. /**
  44. * Test suite for interactive UI tests.
  45. * @param {Object} domAutomationController DomAutomationController instance.
  46. */
  47. constructor(domAutomationController) {
  48. this.domAutomationController_ = domAutomationController;
  49. this.controlTaken_ = false;
  50. this.timerId_ = -1;
  51. this._asyncInvocationId = 0;
  52. }
  53. /**
  54. * Key event with given key identifier.
  55. */
  56. static createKeyEvent(key) {
  57. return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key});
  58. }
  59. };
  60. /**
  61. * Reports test failure.
  62. * @param {string} message Failure description.
  63. */
  64. TestSuite.prototype.fail = function(message) {
  65. if (this.controlTaken_) {
  66. this.reportFailure_(message);
  67. } else {
  68. throw message;
  69. }
  70. };
  71. /**
  72. * Equals assertion tests that expected === actual.
  73. * @param {!Object|boolean} expected Expected object.
  74. * @param {!Object|boolean} actual Actual object.
  75. * @param {string} opt_message User message to print if the test fails.
  76. */
  77. TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
  78. if (expected !== actual) {
  79. let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
  80. if (opt_message) {
  81. message = opt_message + '(' + message + ')';
  82. }
  83. this.fail(message);
  84. }
  85. };
  86. /**
  87. * True assertion tests that value == true.
  88. * @param {!Object} value Actual object.
  89. * @param {string} opt_message User message to print if the test fails.
  90. */
  91. TestSuite.prototype.assertTrue = function(value, opt_message) {
  92. this.assertEquals(true, !!value, opt_message);
  93. };
  94. /**
  95. * Takes control over execution.
  96. */
  97. TestSuite.prototype.takeControl = function() {
  98. this.controlTaken_ = true;
  99. // Set up guard timer.
  100. const self = this;
  101. this.timerId_ = setTimeout(function() {
  102. self.reportFailure_('Timeout exceeded: 20 sec');
  103. }, 20000);
  104. };
  105. /**
  106. * Releases control over execution.
  107. */
  108. TestSuite.prototype.releaseControl = function() {
  109. if (this.timerId_ !== -1) {
  110. clearTimeout(this.timerId_);
  111. this.timerId_ = -1;
  112. }
  113. this.controlTaken_ = false;
  114. this.reportOk_();
  115. };
  116. /**
  117. * Async tests use this one to report that they are completed.
  118. */
  119. TestSuite.prototype.reportOk_ = function() {
  120. this.domAutomationController_.send('[OK]');
  121. };
  122. /**
  123. * Async tests use this one to report failures.
  124. */
  125. TestSuite.prototype.reportFailure_ = function(error) {
  126. if (this.timerId_ !== -1) {
  127. clearTimeout(this.timerId_);
  128. this.timerId_ = -1;
  129. }
  130. this.domAutomationController_.send('[FAILED] ' + error);
  131. };
  132. /**
  133. * Run specified test on a fresh instance of the test suite.
  134. * @param {Array<string>} args method name followed by its parameters.
  135. */
  136. TestSuite.prototype.dispatchOnTestSuite = function(args) {
  137. const methodName = args.shift();
  138. try {
  139. this[methodName].apply(this, args);
  140. if (!this.controlTaken_) {
  141. this.reportOk_();
  142. }
  143. } catch (e) {
  144. this.reportFailure_(e);
  145. }
  146. };
  147. /**
  148. * Wrap an async method with TestSuite.{takeControl(), releaseControl()}
  149. * and invoke TestSuite.reportOk_ upon completion.
  150. * @param {Array<string>} args method name followed by its parameters.
  151. */
  152. TestSuite.prototype.waitForAsync = function(var_args) {
  153. const args = Array.prototype.slice.call(arguments);
  154. this.takeControl();
  155. args.push(this.releaseControl.bind(this));
  156. this.dispatchOnTestSuite(args);
  157. };
  158. /**
  159. * Overrides the method with specified name until it's called first time.
  160. * @param {!Object} receiver An object whose method to override.
  161. * @param {string} methodName Name of the method to override.
  162. * @param {!Function} override A function that should be called right after the
  163. * overridden method returns.
  164. * @param {?boolean} opt_sticky Whether restore original method after first run
  165. * or not.
  166. */
  167. TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) {
  168. const orig = receiver[methodName];
  169. if (typeof orig !== 'function') {
  170. this.fail('Cannot find method to override: ' + methodName);
  171. }
  172. const test = this;
  173. receiver[methodName] = function(var_args) {
  174. let result;
  175. try {
  176. result = orig.apply(this, arguments);
  177. } finally {
  178. if (!opt_sticky) {
  179. receiver[methodName] = orig;
  180. }
  181. }
  182. // In case of exception the override won't be called.
  183. try {
  184. override.apply(this, arguments);
  185. } catch (e) {
  186. test.fail('Exception in overriden method \'' + methodName + '\': ' + e);
  187. }
  188. return result;
  189. };
  190. };
  191. /**
  192. * Waits for current throttler invocations, if any.
  193. * @param {!Common.Throttler} throttler
  194. * @param {function()} callback
  195. */
  196. TestSuite.prototype.waitForThrottler = function(throttler, callback) {
  197. const test = this;
  198. let scheduleShouldFail = true;
  199. test.addSniffer(throttler, 'schedule', onSchedule);
  200. function hasSomethingScheduled() {
  201. return throttler._isRunningProcess || throttler._process;
  202. }
  203. function checkState() {
  204. if (!hasSomethingScheduled()) {
  205. scheduleShouldFail = false;
  206. callback();
  207. return;
  208. }
  209. test.addSniffer(throttler, '_processCompletedForTests', checkState);
  210. }
  211. function onSchedule() {
  212. if (scheduleShouldFail) {
  213. test.fail('Unexpected Throttler.schedule');
  214. }
  215. }
  216. checkState();
  217. };
  218. /**
  219. * @param {string} panelName Name of the panel to show.
  220. */
  221. TestSuite.prototype.showPanel = function(panelName) {
  222. return UI.inspectorView.showPanel(panelName);
  223. };
  224. // UI Tests
  225. /**
  226. * Tests that scripts tab can be open and populated with inspected scripts.
  227. */
  228. TestSuite.prototype.testShowScriptsTab = function() {
  229. const test = this;
  230. this.showPanel('sources').then(function() {
  231. // There should be at least main page script.
  232. this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
  233. test.releaseControl();
  234. });
  235. }.bind(this));
  236. // Wait until all scripts are added to the debugger.
  237. this.takeControl();
  238. };
  239. /**
  240. * Tests that scripts tab is populated with inspected scripts even if it
  241. * hadn't been shown by the moment inspected paged refreshed.
  242. * @see http://crbug.com/26312
  243. */
  244. TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() {
  245. const test = this;
  246. const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
  247. debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
  248. this.showPanel('elements').then(function() {
  249. // Reload inspected page. It will reset the debugger agent.
  250. test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
  251. });
  252. function waitUntilScriptIsParsed() {
  253. debuggerModel.removeEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
  254. test.showPanel('sources').then(function() {
  255. test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
  256. test.releaseControl();
  257. });
  258. });
  259. }
  260. // Wait until all scripts are added to the debugger.
  261. this.takeControl();
  262. };
  263. /**
  264. * Tests that scripts list contains content scripts.
  265. */
  266. TestSuite.prototype.testContentScriptIsPresent = function() {
  267. const test = this;
  268. this.showPanel('sources').then(function() {
  269. test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() {
  270. test.releaseControl();
  271. });
  272. });
  273. // Wait until all scripts are added to the debugger.
  274. this.takeControl();
  275. };
  276. /**
  277. * Tests that scripts are not duplicaed on Scripts tab switch.
  278. */
  279. TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() {
  280. const test = this;
  281. function switchToElementsTab() {
  282. test.showPanel('elements').then(function() {
  283. setTimeout(switchToScriptsTab, 0);
  284. });
  285. }
  286. function switchToScriptsTab() {
  287. test.showPanel('sources').then(function() {
  288. setTimeout(checkScriptsPanel, 0);
  289. });
  290. }
  291. function checkScriptsPanel() {
  292. test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.');
  293. checkNoDuplicates();
  294. test.releaseControl();
  295. }
  296. function checkNoDuplicates() {
  297. const uiSourceCodes = test.nonAnonymousUISourceCodes_();
  298. for (let i = 0; i < uiSourceCodes.length; i++) {
  299. for (let j = i + 1; j < uiSourceCodes.length; j++) {
  300. test.assertTrue(
  301. uiSourceCodes[i].url() !== uiSourceCodes[j].url(),
  302. 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes));
  303. }
  304. }
  305. }
  306. this.showPanel('sources').then(function() {
  307. test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
  308. checkNoDuplicates();
  309. setTimeout(switchToElementsTab, 0);
  310. });
  311. });
  312. // Wait until all scripts are added to the debugger.
  313. this.takeControl();
  314. };
  315. // Tests that debugger works correctly if pause event occurs when DevTools
  316. // frontend is being loaded.
  317. TestSuite.prototype.testPauseWhenLoadingDevTools = function() {
  318. const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
  319. if (debuggerModel.debuggerPausedDetails) {
  320. return;
  321. }
  322. this.showPanel('sources').then(function() {
  323. // Script execution can already be paused.
  324. this._waitForScriptPause(this.releaseControl.bind(this));
  325. }.bind(this));
  326. this.takeControl();
  327. };
  328. // Tests that pressing "Pause" will pause script execution if the script
  329. // is already running.
  330. TestSuite.prototype.testPauseWhenScriptIsRunning = function() {
  331. this.showPanel('sources').then(function() {
  332. this.evaluateInConsole_('setTimeout("handleClick()", 0)', didEvaluateInConsole.bind(this));
  333. }.bind(this));
  334. function didEvaluateInConsole(resultText) {
  335. this.assertTrue(!isNaN(resultText), 'Failed to get timer id: ' + resultText);
  336. // Wait for some time to make sure that inspected page is running the
  337. // infinite loop.
  338. setTimeout(testScriptPause.bind(this), 300);
  339. }
  340. function testScriptPause() {
  341. // The script should be in infinite loop. Click "Pause" button to
  342. // pause it and wait for the result.
  343. UI.panels.sources._togglePause();
  344. this._waitForScriptPause(this.releaseControl.bind(this));
  345. }
  346. this.takeControl();
  347. };
  348. /**
  349. * Tests network size.
  350. */
  351. TestSuite.prototype.testNetworkSize = function() {
  352. const test = this;
  353. function finishRequest(request, finishTime) {
  354. test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
  355. test.releaseControl();
  356. }
  357. this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
  358. // Reload inspected page to sniff network events
  359. test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
  360. this.takeControl();
  361. };
  362. /**
  363. * Tests network sync size.
  364. */
  365. TestSuite.prototype.testNetworkSyncSize = function() {
  366. const test = this;
  367. function finishRequest(request, finishTime) {
  368. test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
  369. test.releaseControl();
  370. }
  371. this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
  372. // Send synchronous XHR to sniff network events
  373. test.evaluateInConsole_(
  374. 'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {});
  375. this.takeControl();
  376. };
  377. /**
  378. * Tests network raw headers text.
  379. */
  380. TestSuite.prototype.testNetworkRawHeadersText = function() {
  381. const test = this;
  382. function finishRequest(request, finishTime) {
  383. if (!request.responseHeadersText) {
  384. test.fail('Failure: resource does not have response headers text');
  385. }
  386. const index = request.responseHeadersText.indexOf('Date:');
  387. test.assertEquals(
  388. 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length');
  389. test.releaseControl();
  390. }
  391. this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
  392. // Reload inspected page to sniff network events
  393. test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
  394. this.takeControl();
  395. };
  396. /**
  397. * Tests network timing.
  398. */
  399. TestSuite.prototype.testNetworkTiming = function() {
  400. const test = this;
  401. function finishRequest(request, finishTime) {
  402. // Setting relaxed expectations to reduce flakiness.
  403. // Server sends headers after 100ms, then sends data during another 100ms.
  404. // We expect these times to be measured at least as 70ms.
  405. test.assertTrue(
  406. request.timing.receiveHeadersEnd - request.timing.connectStart >= 70,
  407. 'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' +
  408. 'receiveHeadersEnd=' + request.timing.receiveHeadersEnd + ', connectStart=' +
  409. request.timing.connectStart + '.');
  410. test.assertTrue(
  411. request.responseReceivedTime - request.startTime >= 0.07,
  412. 'Time between responseReceivedTime and startTime should be >=0.07s, but was ' +
  413. 'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.');
  414. test.assertTrue(
  415. request.endTime - request.startTime >= 0.14,
  416. 'Time between endTime and startTime should be >=0.14s, but was ' +
  417. 'endtime=' + request.endTime + ', startTime=' + request.startTime + '.');
  418. test.releaseControl();
  419. }
  420. this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
  421. // Reload inspected page to sniff network events
  422. test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
  423. this.takeControl();
  424. };
  425. TestSuite.prototype.testPushTimes = function(url) {
  426. const test = this;
  427. let pendingRequestCount = 2;
  428. function finishRequest(request, finishTime) {
  429. test.assertTrue(
  430. typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0,
  431. `pushStart is invalid: ${request.timing.pushStart}`);
  432. test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`);
  433. test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime');
  434. if (request.url().endsWith('?pushUseNullEndTime')) {
  435. test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`);
  436. } else {
  437. test.assertTrue(
  438. request.timing.pushStart < request.timing.pushEnd,
  439. `pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`);
  440. // The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant.
  441. test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime');
  442. test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime');
  443. }
  444. if (!--pendingRequestCount) {
  445. test.releaseControl();
  446. }
  447. }
  448. this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest, true);
  449. test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {});
  450. test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {});
  451. this.takeControl();
  452. };
  453. TestSuite.prototype.testConsoleOnNavigateBack = function() {
  454. function filteredMessages() {
  455. return SDK.consoleModel.messages().filter(a => a.source !== SDK.ConsoleMessage.MessageSource.Violation);
  456. }
  457. if (filteredMessages().length === 1) {
  458. firstConsoleMessageReceived.call(this, null);
  459. } else {
  460. SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
  461. }
  462. function firstConsoleMessageReceived(event) {
  463. if (event && event.data.source === SDK.ConsoleMessage.MessageSource.Violation) {
  464. return;
  465. }
  466. SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
  467. this.evaluateInConsole_('clickLink();', didClickLink.bind(this));
  468. }
  469. function didClickLink() {
  470. // Check that there are no new messages(command is not a message).
  471. this.assertEquals(3, filteredMessages().length);
  472. this.evaluateInConsole_('history.back();', didNavigateBack.bind(this));
  473. }
  474. function didNavigateBack() {
  475. // Make sure navigation completed and possible console messages were pushed.
  476. this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this));
  477. }
  478. function didCompleteNavigation() {
  479. this.assertEquals(7, filteredMessages().length);
  480. this.releaseControl();
  481. }
  482. this.takeControl();
  483. };
  484. TestSuite.prototype.testSharedWorker = function() {
  485. function didEvaluateInConsole(resultText) {
  486. this.assertEquals('2011', resultText);
  487. this.releaseControl();
  488. }
  489. this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this));
  490. this.takeControl();
  491. };
  492. TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() {
  493. // Make sure the worker is loaded.
  494. this.takeControl();
  495. this._waitForTargets(1, callback.bind(this));
  496. function callback() {
  497. Protocol.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
  498. }
  499. };
  500. TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() {
  501. this.takeControl();
  502. this._waitForTargets(1, callback.bind(this));
  503. function callback() {
  504. const debuggerModel = SDK.targetManager.models(SDK.DebuggerModel)[0];
  505. if (debuggerModel.isPaused()) {
  506. SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
  507. debuggerModel.resume();
  508. return;
  509. }
  510. this._waitForScriptPause(callback.bind(this));
  511. }
  512. function onConsoleMessage(event) {
  513. const message = event.data.messageText;
  514. if (message !== 'connected') {
  515. this.fail('Unexpected message: ' + message);
  516. }
  517. this.releaseControl();
  518. }
  519. };
  520. TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
  521. this.takeControl();
  522. this.showPanel('network').then(() => {
  523. if (!document.querySelector('#network-container')) {
  524. this.fail('unable to find #network-container');
  525. }
  526. this.releaseControl();
  527. });
  528. };
  529. TestSuite.prototype.enableTouchEmulation = function() {
  530. const deviceModeModel = new Emulation.DeviceModeModel(function() {});
  531. deviceModeModel._target = SDK.targetManager.mainTarget();
  532. deviceModeModel._applyTouch(true, true);
  533. };
  534. TestSuite.prototype.waitForDebuggerPaused = function() {
  535. const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
  536. if (debuggerModel.debuggerPausedDetails) {
  537. return;
  538. }
  539. this.takeControl();
  540. this._waitForScriptPause(this.releaseControl.bind(this));
  541. };
  542. TestSuite.prototype.switchToPanel = function(panelName) {
  543. this.showPanel(panelName).then(this.releaseControl.bind(this));
  544. this.takeControl();
  545. };
  546. // Regression test for crbug.com/370035.
  547. TestSuite.prototype.testDeviceMetricsOverrides = function() {
  548. function dumpPageMetrics() {
  549. return JSON.stringify(
  550. {width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
  551. }
  552. const test = this;
  553. async function testOverrides(params, metrics, callback) {
  554. await SDK.targetManager.mainTarget().emulationAgent().invoke_setDeviceMetricsOverride(params);
  555. test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics);
  556. function checkMetrics(consoleResult) {
  557. test.assertEquals(
  558. '"' + JSON.stringify(metrics) + '"', consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params));
  559. callback();
  560. }
  561. }
  562. function step1() {
  563. testOverrides(
  564. {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
  565. {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
  566. }
  567. function step2() {
  568. testOverrides(
  569. {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
  570. {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
  571. }
  572. function step3() {
  573. testOverrides(
  574. {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
  575. {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
  576. }
  577. function step4() {
  578. testOverrides(
  579. {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
  580. {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
  581. }
  582. function finish() {
  583. test.releaseControl();
  584. }
  585. test.takeControl();
  586. step1();
  587. };
  588. TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
  589. const test = this;
  590. let receivedReady = false;
  591. function signalToShowAutofill() {
  592. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  593. {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
  594. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  595. {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
  596. }
  597. function selectTopAutoFill() {
  598. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  599. {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
  600. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  601. {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
  602. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  603. {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
  604. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  605. {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
  606. test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
  607. }
  608. function onResultOfInput(value) {
  609. // Console adds "" around the response.
  610. test.assertEquals('"Abbf"', value);
  611. test.releaseControl();
  612. }
  613. function onConsoleMessage(event) {
  614. const message = event.data.messageText;
  615. if (message === 'ready' && !receivedReady) {
  616. receivedReady = true;
  617. signalToShowAutofill();
  618. }
  619. // This log comes from the browser unittest code.
  620. if (message === 'didShowSuggestions') {
  621. selectTopAutoFill();
  622. }
  623. }
  624. this.takeControl();
  625. // It is possible for the ready console messagage to be already received but not handled
  626. // or received later. This ensures we can catch both cases.
  627. SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
  628. const messages = SDK.consoleModel.messages();
  629. if (messages.length) {
  630. const text = messages[0].messageText;
  631. this.assertEquals('ready', text);
  632. signalToShowAutofill();
  633. }
  634. };
  635. TestSuite.prototype.testKeyEventUnhandled = function() {
  636. function onKeyEventUnhandledKeyDown(event) {
  637. this.assertEquals('keydown', event.data.type);
  638. this.assertEquals('F8', event.data.key);
  639. this.assertEquals(119, event.data.keyCode);
  640. this.assertEquals(0, event.data.modifiers);
  641. this.assertEquals('', event.data.code);
  642. Host.InspectorFrontendHost.events.removeEventListener(
  643. Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
  644. Host.InspectorFrontendHost.events.addEventListener(
  645. Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
  646. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  647. {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
  648. }
  649. function onKeyEventUnhandledKeyUp(event) {
  650. this.assertEquals('keyup', event.data.type);
  651. this.assertEquals('F8', event.data.key);
  652. this.assertEquals(119, event.data.keyCode);
  653. this.assertEquals(0, event.data.modifiers);
  654. this.assertEquals('F8', event.data.code);
  655. this.releaseControl();
  656. }
  657. this.takeControl();
  658. Host.InspectorFrontendHost.events.addEventListener(
  659. Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
  660. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  661. {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
  662. };
  663. TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
  664. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  665. {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
  666. SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
  667. {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
  668. };
  669. // Check that showing the certificate viewer does not crash, crbug.com/954874
  670. TestSuite.prototype.testShowCertificate = function() {
  671. Host.InspectorFrontendHost.showCertificateViewer([
  672. 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
  673. 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
  674. 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
  675. 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
  676. 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
  677. 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
  678. 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
  679. 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
  680. 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
  681. 'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
  682. 'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
  683. 'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOcIA7AVR/Ck22Uj8X' +
  684. 'UOECercjUrKdDyaAPcLp2TThAgMBAAGjggHZMIIB1TATBgNVHSUEDDAKBggr' +
  685. 'BgEFBQcDATCBrwYDVR0RBIGnMIGkgg0qLmFwcHNwb3QuY29tggsqLmEucnVu' +
  686. 'LmFwcIIVKi50aGlua3dpdGhnb29nbGUuY29tghAqLndpdGhnb29nbGUuY29t' +
  687. 'ghEqLndpdGh5b3V0dWJlLmNvbYILYXBwc3BvdC5jb22CB3J1bi5hcHCCE3Ro' +
  688. 'aW5rd2l0aGdvb2dsZS5jb22CDndpdGhnb29nbGUuY29tgg93aXRoeW91dHVi' +
  689. 'ZS5jb20waAYIKwYBBQUHAQEEXDBaMC0GCCsGAQUFBzAChiFodHRwOi8vcGtp' +
  690. 'Lmdvb2cvZ3NyMi9HVFNHSUFHMy5jcnQwKQYIKwYBBQUHMAGGHWh0dHA6Ly9v' +
  691. 'Y3NwLnBraS5nb29nL0dUU0dJQUczMB0GA1UdDgQWBBTGkpE5o0H9+Wjc05rF' +
  692. 'hNQiYDjBFjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFHfCuFCaZ3Z2sS3C' +
  693. 'htCDoH6mfrpLMCEGA1UdIAQaMBgwDAYKKwYBBAHWeQIFAzAIBgZngQwBAgIw' +
  694. 'MQYDVR0fBCowKDAmoCSgIoYgaHR0cDovL2NybC5wa2kuZ29vZy9HVFNHSUFH' +
  695. 'My5jcmwwDQYJKoZIhvcNAQELBQADggEBALqoYGqWtJW/6obEzY+ehsgfyXb+' +
  696. 'qNIuV09wt95cRF93HlLbBlSZ/Iz8HXX44ZT1/tGAkwKnW0gDKSSab3I8U+e9' +
  697. 'LHbC9VXrgAFENzu89MNKNmK5prwv+MPA2HUQPu4Pad3qXmd4+nKc/EUjtg1d' +
  698. '/xKGK1Vn6JX3i5ly/rduowez3LxpSAJuIwseum331aQaKC2z2ri++96B8MPU' +
  699. 'KFXzvV2gVGOe3ZYqmwPaG8y38Tba+OzEh59ygl8ydJJhoI6+R3itPSy0aXUU' +
  700. 'lMvvAbfCobXD5kBRQ28ysgbDSDOPs3fraXpAKL92QUjsABs58XBz5vka4swu' +
  701. 'gg/u+ZxaKOqfIm8=',
  702. 'MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBM' +
  703. 'MSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMK' +
  704. 'R2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAw' +
  705. 'NDJaFw0yMTEyMTUwMDAwNDJaMFQxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVH' +
  706. 'b29nbGUgVHJ1c3QgU2VydmljZXMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5l' +
  707. 'dCBBdXRob3JpdHkgRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB' +
  708. 'AQDKUkvqHv/OJGuo2nIYaNVWXQ5IWi01CXZaz6TIHLGp/lOJ+600/4hbn7vn' +
  709. '6AAB3DVzdQOts7G5pH0rJnnOFUAK71G4nzKMfHCGUksW/mona+Y2emJQ2N+a' +
  710. 'icwJKetPKRSIgAuPOB6Aahh8Hb2XO3h9RUk2T0HNouB2VzxoMXlkyW7XUR5m' +
  711. 'w6JkLHnA52XDVoRTWkNty5oCINLvGmnRsJ1zouAqYGVQMc/7sy+/EYhALrVJ' +
  712. 'EA8KbtyX+r8snwU5C1hUrwaW6MWOARa8qBpNQcWTkaIeoYvy/sGIJEmjR0vF' +
  713. 'EwHdp1cSaWIr6/4g72n7OqXwfinu7ZYW97EfoOSQJeAzAgMBAAGjggEzMIIB' +
  714. 'LzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF' +
  715. 'BwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFHfCuFCaZ3Z2sS3C' +
  716. 'htCDoH6mfrpLMB8GA1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUG' +
  717. 'CCsGAQUFBwEBBCkwJzAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdv' +
  718. 'b2cvZ3NyMjAyBgNVHR8EKzApMCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29n' +
  719. 'L2dzcjIvZ3NyMi5jcmwwPwYDVR0gBDgwNjA0BgZngQwBAgIwKjAoBggrBgEF' +
  720. 'BQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9yZXBvc2l0b3J5LzANBgkqhkiG9w0B' +
  721. 'AQsFAAOCAQEAHLeJluRT7bvs26gyAZ8so81trUISd7O45skDUmAge1cnxhG1' +
  722. 'P2cNmSxbWsoiCt2eux9LSD+PAj2LIYRFHW31/6xoic1k4tbWXkDCjir37xTT' +
  723. 'NqRAMPUyFRWSdvt+nlPqwnb8Oa2I/maSJukcxDjNSfpDh/Bd1lZNgdd/8cLd' +
  724. 'sE3+wypufJ9uXO1iQpnh9zbuFIwsIONGl1p3A8CgxkqI/UAih3JaGOqcpcda' +
  725. 'CIzkBaR9uYQ1X4k2Vg5APRLouzVy7a8IVk6wuy6pm+T7HT4LY8ibS5FEZlfA' +
  726. 'FLSW8NwsVz9SBK2Vqn1N0PIMn5xA6NZVc7o835DLAFshEWfC7TIe3g==',
  727. 'MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEg' +
  728. 'MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkds' +
  729. 'b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAw' +
  730. 'WhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg' +
  731. 'Q0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs' +
  732. 'U2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o' +
  733. 'mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe' +
  734. '+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1' +
  735. 'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
  736. 'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
  737. '4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
  738. 'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
  739. 'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
  740. 'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
  741. 'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
  742. 'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
  743. 'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
  744. 'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
  745. 'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
  746. '9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
  747. 'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
  748. '/H5COEBkEveegeGTLg=='
  749. ]);
  750. };
  751. // Simple sanity check to make sure network throttling is wired up
  752. // See crbug.com/747724
  753. TestSuite.prototype.testOfflineNetworkConditions = async function() {
  754. const test = this;
  755. SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
  756. function finishRequest(request) {
  757. test.assertEquals(
  758. 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
  759. test.releaseControl();
  760. }
  761. this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
  762. test.takeControl();
  763. test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
  764. };
  765. TestSuite.prototype.testEmulateNetworkConditions = function() {
  766. const test = this;
  767. function testPreset(preset, messages, next) {
  768. function onConsoleMessage(event) {
  769. const index = messages.indexOf(event.data.messageText);
  770. if (index === -1) {
  771. test.fail('Unexpected message: ' + event.data.messageText);
  772. return;
  773. }
  774. messages.splice(index, 1);
  775. if (!messages.length) {
  776. SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
  777. next();
  778. }
  779. }
  780. SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
  781. SDK.multitargetNetworkManager.setNetworkConditions(preset);
  782. }
  783. test.takeControl();
  784. step1();
  785. function step1() {
  786. testPreset(
  787. MobileThrottling.networkPresets[2],
  788. [
  789. 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
  790. ],
  791. step2);
  792. }
  793. function step2() {
  794. testPreset(
  795. MobileThrottling.networkPresets[1],
  796. [
  797. 'online event: online = true',
  798. 'connection change event: type = cellular; downlinkMax = 0.390625; effectiveType = 2g'
  799. ],
  800. step3);
  801. }
  802. function step3() {
  803. testPreset(
  804. MobileThrottling.networkPresets[0],
  805. ['connection change event: type = cellular; downlinkMax = 1.4400000000000002; effectiveType = 3g'],
  806. test.releaseControl.bind(test));
  807. }
  808. };
  809. TestSuite.prototype.testScreenshotRecording = function() {
  810. const test = this;
  811. function performActionsInPage(callback) {
  812. let count = 0;
  813. const div = document.createElement('div');
  814. div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
  815. document.body.appendChild(div);
  816. requestAnimationFrame(frame);
  817. function frame() {
  818. const color = [0, 0, 0];
  819. color[count % 3] = 255;
  820. div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
  821. if (++count > 10) {
  822. requestAnimationFrame(callback);
  823. } else {
  824. requestAnimationFrame(frame);
  825. }
  826. }
  827. }
  828. const captureFilmStripSetting = Common.settings.createSetting('timelineCaptureFilmStrip', false);
  829. captureFilmStripSetting.set(true);
  830. test.evaluateInConsole_(performActionsInPage.toString(), function() {});
  831. test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
  832. function onTimelineDone() {
  833. captureFilmStripSetting.set(false);
  834. const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
  835. const frames = filmStripModel.frames();
  836. test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
  837. loadFrameImages(frames);
  838. }
  839. function loadFrameImages(frames) {
  840. const readyImages = [];
  841. for (const frame of frames) {
  842. frame.imageDataPromise().then(onGotImageData);
  843. }
  844. function onGotImageData(data) {
  845. const image = new Image();
  846. test.assertTrue(!!data, 'No image data for frame');
  847. image.addEventListener('load', onLoad);
  848. image.src = 'data:image/jpg;base64,' + data;
  849. }
  850. function onLoad(event) {
  851. readyImages.push(event.target);
  852. if (readyImages.length === frames.length) {
  853. validateImagesAndCompleteTest(readyImages);
  854. }
  855. }
  856. }
  857. function validateImagesAndCompleteTest(images) {
  858. let redCount = 0;
  859. let greenCount = 0;
  860. let blueCount = 0;
  861. const canvas = document.createElement('canvas');
  862. const ctx = canvas.getContext('2d');
  863. for (const image of images) {
  864. test.assertTrue(image.naturalWidth > 10);
  865. test.assertTrue(image.naturalHeight > 10);
  866. canvas.width = image.naturalWidth;
  867. canvas.height = image.naturalHeight;
  868. ctx.drawImage(image, 0, 0);
  869. const data = ctx.getImageData(0, 0, 1, 1);
  870. const color = Array.prototype.join.call(data.data, ',');
  871. if (data.data[0] > 200) {
  872. redCount++;
  873. } else if (data.data[1] > 200) {
  874. greenCount++;
  875. } else if (data.data[2] > 200) {
  876. blueCount++;
  877. } else {
  878. test.fail('Unexpected color: ' + color);
  879. }
  880. }
  881. test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed');
  882. test.releaseControl();
  883. }
  884. test.takeControl();
  885. };
  886. TestSuite.prototype.testSettings = function() {
  887. const test = this;
  888. createSettings();
  889. test.takeControl();
  890. setTimeout(reset, 0);
  891. function createSettings() {
  892. const localSetting = Common.settings.createLocalSetting('local', undefined);
  893. localSetting.set({s: 'local', n: 1});
  894. const globalSetting = Common.settings.createSetting('global', undefined);
  895. globalSetting.set({s: 'global', n: 2});
  896. }
  897. function reset() {
  898. Root.Runtime.experiments.clearForTest();
  899. Host.InspectorFrontendHost.getPreferences(gotPreferences);
  900. }
  901. function gotPreferences(prefs) {
  902. Main.Main._instanceForTest._createSettings(prefs);
  903. const localSetting = Common.settings.createLocalSetting('local', undefined);
  904. test.assertEquals('object', typeof localSetting.get());
  905. test.assertEquals('local', localSetting.get().s);
  906. test.assertEquals(1, localSetting.get().n);
  907. const globalSetting = Common.settings.createSetting('global', undefined);
  908. test.assertEquals('object', typeof globalSetting.get());
  909. test.assertEquals('global', globalSetting.get().s);
  910. test.assertEquals(2, globalSetting.get().n);
  911. test.releaseControl();
  912. }
  913. };
  914. TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
  915. const test = this;
  916. test.takeControl();
  917. const messages = SDK.consoleModel.messages();
  918. if (messages.length === 1) {
  919. checkMessages();
  920. } else {
  921. SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
  922. }
  923. function checkMessages() {
  924. const messages = SDK.consoleModel.messages();
  925. test.assertEquals(1, messages.length);
  926. test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
  927. test.releaseControl();
  928. }
  929. };
  930. TestSuite.prototype.testConsoleContextNames = function() {
  931. const test = this;
  932. test.takeControl();
  933. this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
  934. function onExecutionContexts() {
  935. const consoleView = Console.ConsoleView.instance();
  936. const selector = consoleView._consoleContextSelector;
  937. const values = [];
  938. for (const item of selector._items) {
  939. values.push(selector.titleFor(item));
  940. }
  941. test.assertEquals('top', values[0]);
  942. test.assertEquals('Simple content script', values[1]);
  943. test.releaseControl();
  944. }
  945. };
  946. TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
  947. const test = this;
  948. test.takeControl();
  949. SDK.targetManager.addModelListener(
  950. SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
  951. this.evaluateInConsole_(`
  952. let img = document.createElement('img');
  953. img.src = "${url}";
  954. document.body.appendChild(img);
  955. `, () => {});
  956. let count = 0;
  957. function onResponseReceived(event) {
  958. const networkRequest = event.data;
  959. if (!networkRequest.url().startsWith('http')) {
  960. return;
  961. }
  962. switch (++count) {
  963. case 1: // Original redirect
  964. test.assertEquals(301, networkRequest.statusCode);
  965. test.assertEquals('Moved Permanently', networkRequest.statusText);
  966. test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
  967. break;
  968. case 2: // HSTS internal redirect
  969. test.assertTrue(networkRequest.url().startsWith('http://'));
  970. test.assertEquals(307, networkRequest.statusCode);
  971. test.assertEquals('Internal Redirect', networkRequest.statusText);
  972. test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
  973. test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
  974. break;
  975. case 3: // Final response
  976. test.assertTrue(networkRequest.url().startsWith('https://'));
  977. test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
  978. test.assertEquals(200, networkRequest.statusCode);
  979. test.assertEquals('OK', networkRequest.statusText);
  980. test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
  981. test.releaseControl();
  982. }
  983. }
  984. };
  985. TestSuite.prototype.testDOMWarnings = function() {
  986. const messages = SDK.consoleModel.messages();
  987. this.assertEquals(1, messages.length);
  988. const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
  989. this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
  990. };
  991. TestSuite.prototype.waitForTestResultsInConsole = function() {
  992. const messages = SDK.consoleModel.messages();
  993. for (let i = 0; i < messages.length; ++i) {
  994. const text = messages[i].messageText;
  995. if (text === 'PASS') {
  996. return;
  997. } else if (/^FAIL/.test(text)) {
  998. this.fail(text);
  999. } // This will throw.
  1000. }
  1001. // Neither PASS nor FAIL, so wait for more messages.
  1002. function onConsoleMessage(event) {
  1003. const text = event.data.messageText;
  1004. if (text === 'PASS') {
  1005. this.releaseControl();
  1006. } else if (/^FAIL/.test(text)) {
  1007. this.fail(text);
  1008. }
  1009. }
  1010. SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
  1011. this.takeControl();
  1012. };
  1013. TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
  1014. const original = receiver[methodName];
  1015. if (typeof original !== 'function') {
  1016. this.fail(`TestSuite._overrideMethod: $[methodName] is not a function`);
  1017. return;
  1018. }
  1019. receiver[methodName] = function() {
  1020. let value;
  1021. try {
  1022. value = original.apply(receiver, arguments);
  1023. } finally {
  1024. receiver[methodName] = original;
  1025. }
  1026. override.apply(original, arguments);
  1027. return value;
  1028. };
  1029. };
  1030. TestSuite.prototype.startTimeline = function(callback) {
  1031. const test = this;
  1032. this.showPanel('timeline').then(function() {
  1033. const timeline = UI.panels.timeline;
  1034. test._overrideMethod(timeline, '_recordingStarted', callback);
  1035. timeline._toggleRecording();
  1036. });
  1037. };
  1038. TestSuite.prototype.stopTimeline = function(callback) {
  1039. const timeline = UI.panels.timeline;
  1040. this._overrideMethod(timeline, 'loadingComplete', callback);
  1041. timeline._toggleRecording();
  1042. };
  1043. TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
  1044. const callback = arguments[arguments.length - 1];
  1045. const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
  1046. const argsString = arguments.length < 3 ?
  1047. '' :
  1048. Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
  1049. this.evaluateInConsole_(
  1050. `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
  1051. SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
  1052. function onConsoleMessage(event) {
  1053. const text = event.data.messageText;
  1054. if (text === doneMessage) {
  1055. SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
  1056. callback();
  1057. }
  1058. }
  1059. };
  1060. TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
  1061. const test = this;
  1062. this.startTimeline(onRecordingStarted);
  1063. function onRecordingStarted() {
  1064. test.invokePageFunctionAsync(functionName, pageActionsDone);
  1065. }
  1066. function pageActionsDone() {
  1067. test.stopTimeline(callback);
  1068. }
  1069. };
  1070. TestSuite.prototype.enableExperiment = function(name) {
  1071. Root.Runtime.experiments.enableForTest(name);
  1072. };
  1073. TestSuite.prototype.checkInputEventsPresent = function() {
  1074. const expectedEvents = new Set(arguments);
  1075. const model = UI.panels.timeline._performanceModel.timelineModel();
  1076. const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
  1077. const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
  1078. const prefix = 'InputLatency::';
  1079. for (const e of input) {
  1080. if (!e.name.startsWith(prefix)) {
  1081. continue;
  1082. }
  1083. if (e.steps.length < 2) {
  1084. continue;
  1085. }
  1086. if (e.name.startsWith(prefix + 'Mouse') &&
  1087. typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') {
  1088. throw `Missing timeWaitingForMainThread on ${e.name}`;
  1089. }
  1090. expectedEvents.delete(e.name.substr(prefix.length));
  1091. }
  1092. if (expectedEvents.size) {
  1093. throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
  1094. }
  1095. };
  1096. TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
  1097. this.takeControl();
  1098. await self.runtime.loadModulePromise('elements');
  1099. if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) {
  1100. await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f));
  1101. }
  1102. this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest);
  1103. this.releaseControl();
  1104. };
  1105. TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
  1106. this.takeControl();
  1107. const targetAgent = SDK.targetManager.mainTarget().targetAgent();
  1108. const {browserContextId} = await targetAgent.invoke_createBrowserContext();
  1109. const response1 = await targetAgent.invoke_getBrowserContexts();
  1110. this.assertEquals(response1.browserContextIds.length, 1);
  1111. await targetAgent.invoke_disposeBrowserContext({browserContextId});
  1112. const response2 = await targetAgent.invoke_getBrowserContexts();
  1113. this.assertEquals(response2.browserContextIds.length, 0);
  1114. this.releaseControl();
  1115. };
  1116. TestSuite.prototype.testCreateBrowserContext = async function(url) {
  1117. this.takeControl();
  1118. const browserContextIds = [];
  1119. const targetAgent = SDK.targetManager.mainTarget().targetAgent();
  1120. const target1 = await createIsolatedTarget(url);
  1121. const target2 = await createIsolatedTarget(url);
  1122. const response = await targetAgent.invoke_getBrowserContexts();
  1123. this.assertEquals(response.browserContextIds.length, 2);
  1124. this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
  1125. this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
  1126. await evalCode(target1, 'localStorage.setItem("page1", "page1")');
  1127. await evalCode(target2, 'localStorage.setItem("page2", "page2")');
  1128. this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
  1129. this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
  1130. this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
  1131. this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
  1132. const removedTargets = [];
  1133. SDK.targetManager.observeTargets({targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
  1134. await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
  1135. this.assertEquals(removedTargets.length, 2);
  1136. this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
  1137. this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
  1138. this.releaseControl();
  1139. /**
  1140. * @param {string} url
  1141. * @return {!Promise<!SDK.Target>}
  1142. */
  1143. async function createIsolatedTarget(url) {
  1144. const {browserContextId} = await targetAgent.invoke_createBrowserContext();
  1145. browserContextIds.push(browserContextId);
  1146. const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
  1147. await targetAgent.invoke_attachToTarget({targetId, flatten: true});
  1148. const target = SDK.targetManager.targets().find(target => target.id() === targetId);
  1149. const pageAgent = target.pageAgent();
  1150. await pageAgent.invoke_enable();
  1151. await pageAgent.invoke_navigate({url});
  1152. return target;
  1153. }
  1154. async function disposeBrowserContext(browserContextId) {
  1155. const targetAgent = SDK.targetManager.mainTarget().targetAgent();
  1156. await targetAgent.invoke_disposeBrowserContext({browserContextId});
  1157. }
  1158. async function evalCode(target, code) {
  1159. return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
  1160. }
  1161. };
  1162. TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
  1163. this.takeControl();
  1164. await new Promise(callback => this._waitForTargets(2, callback));
  1165. async function takeLogs(target) {
  1166. const code = `
  1167. (function() {
  1168. var result = window.logs.join(' ');
  1169. window.logs = [];
  1170. return result;
  1171. })()
  1172. `;
  1173. return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
  1174. }
  1175. let parentFrameOutput;
  1176. let childFrameOutput;
  1177. const inputAgent = SDK.targetManager.mainTarget().inputAgent();
  1178. const runtimeAgent = SDK.targetManager.mainTarget().runtimeAgent();
  1179. await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
  1180. await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
  1181. await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
  1182. await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
  1183. await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
  1184. await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
  1185. parentFrameOutput = 'Event type: mousedown button: 0 x: 10 y: 10 Event type: mouseup button: 0 x: 10 y: 20';
  1186. this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0]));
  1187. childFrameOutput = 'Event type: mousedown button: 0 x: 30 y: 40 Event type: mouseup button: 0 x: 30 y: 50';
  1188. this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1]));
  1189. await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
  1190. await runtimeAgent.invoke_evaluate({expression: `document.querySelector('iframe').focus()`});
  1191. await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
  1192. parentFrameOutput = 'Event type: keydown';
  1193. this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0]));
  1194. childFrameOutput = 'Event type: keydown';
  1195. this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1]));
  1196. await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
  1197. await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
  1198. await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
  1199. await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
  1200. parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
  1201. this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0]));
  1202. childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
  1203. this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1]));
  1204. this.releaseControl();
  1205. };
  1206. TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
  1207. const test = this;
  1208. const loggedHeaders = new Set(['cache-control', 'pragma']);
  1209. function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
  1210. return new Promise(fulfill => {
  1211. Host.ResourceLoader.load(url, headers, callback);
  1212. function callback(statusCode, headers, content) {
  1213. test.assertEquals(expectedStatus, statusCode);
  1214. const headersArray = [];
  1215. for (const name in headers) {
  1216. const nameLower = name.toLowerCase();
  1217. if (loggedHeaders.has(nameLower)) {
  1218. headersArray.push(nameLower);
  1219. }
  1220. }
  1221. headersArray.sort();
  1222. test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
  1223. test.assertEquals(expectedContent, content);
  1224. fulfill();
  1225. }
  1226. });
  1227. }
  1228. this.takeControl();
  1229. await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
  1230. await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
  1231. await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
  1232. await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
  1233. await SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
  1234. expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
  1235. {credentials: 'include'})`,
  1236. awaitPromise: true
  1237. });
  1238. await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
  1239. await SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
  1240. expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
  1241. {credentials: 'include'})`,
  1242. awaitPromise: true
  1243. });
  1244. await testCase(
  1245. baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
  1246. await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
  1247. await testCase(fileURL, undefined, 200, [], '<html>\n<body>\nDummy page.\n</body>\n</html>\n');
  1248. await testCase(fileURL + 'thisfileshouldnotbefound', undefined, 404, [], '');
  1249. this.releaseControl();
  1250. };
  1251. TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
  1252. this.takeControl();
  1253. const testUserAgent = 'test user agent';
  1254. SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
  1255. function onRequestUpdated(event) {
  1256. const request = event.data;
  1257. if (request.resourceType() !== Common.resourceTypes.WebSocket) {
  1258. return;
  1259. }
  1260. if (!request.requestHeadersText()) {
  1261. return;
  1262. }
  1263. let actualUserAgent = 'no user-agent header';
  1264. for (const {name, value} of request.requestHeaders()) {
  1265. if (name.toLowerCase() === 'user-agent') {
  1266. actualUserAgent = value;
  1267. }
  1268. }
  1269. this.assertEquals(testUserAgent, actualUserAgent);
  1270. this.releaseControl();
  1271. }
  1272. SDK.targetManager.addModelListener(
  1273. SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
  1274. this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
  1275. };
  1276. /**
  1277. * Serializes array of uiSourceCodes to string.
  1278. * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
  1279. * @return {string}
  1280. */
  1281. TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
  1282. const names = [];
  1283. for (let i = 0; i < uiSourceCodes.length; i++) {
  1284. names.push('"' + uiSourceCodes[i].url() + '"');
  1285. }
  1286. return names.join(',');
  1287. };
  1288. /**
  1289. * Returns all loaded non anonymous uiSourceCodes.
  1290. * @return {!Array.<!Workspace.UISourceCode>}
  1291. */
  1292. TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
  1293. /**
  1294. * @param {!Workspace.UISourceCode} uiSourceCode
  1295. */
  1296. function filterOutService(uiSourceCode) {
  1297. return !uiSourceCode.project().isServiceProject();
  1298. }
  1299. const uiSourceCodes = Workspace.workspace.uiSourceCodes();
  1300. return uiSourceCodes.filter(filterOutService);
  1301. };
  1302. /*
  1303. * Evaluates the code in the console as if user typed it manually and invokes
  1304. * the callback when the result message is received and added to the console.
  1305. * @param {string} code
  1306. * @param {function(string)} callback
  1307. */
  1308. TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
  1309. function innerEvaluate() {
  1310. UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
  1311. const consoleView = Console.ConsoleView.instance();
  1312. consoleView._prompt._appendCommand(code);
  1313. this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) {
  1314. callback(viewMessage.toMessageElement().deepTextContent());
  1315. }.bind(this));
  1316. }
  1317. function showConsoleAndEvaluate() {
  1318. Common.console.showPromise().then(innerEvaluate.bind(this));
  1319. }
  1320. if (!UI.context.flavor(SDK.ExecutionContext)) {
  1321. UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
  1322. return;
  1323. }
  1324. showConsoleAndEvaluate.call(this);
  1325. };
  1326. /**
  1327. * Checks that all expected scripts are present in the scripts list
  1328. * in the Scripts panel.
  1329. * @param {!Array.<string>} expected Regular expressions describing
  1330. * expected script names.
  1331. * @return {boolean} Whether all the scripts are in "scripts-files" select
  1332. * box
  1333. */
  1334. TestSuite.prototype._scriptsAreParsed = function(expected) {
  1335. const uiSourceCodes = this.nonAnonymousUISourceCodes_();
  1336. // Check that at least all the expected scripts are present.
  1337. const missing = expected.slice(0);
  1338. for (let i = 0; i < uiSourceCodes.length; ++i) {
  1339. for (let j = 0; j < missing.length; ++j) {
  1340. if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
  1341. missing.splice(j, 1);
  1342. break;
  1343. }
  1344. }
  1345. }
  1346. return missing.length === 0;
  1347. };
  1348. /**
  1349. * Waits for script pause, checks expectations, and invokes the callback.
  1350. * @param {function():void} callback
  1351. */
  1352. TestSuite.prototype._waitForScriptPause = function(callback) {
  1353. this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback);
  1354. };
  1355. /**
  1356. * Waits until all the scripts are parsed and invokes the callback.
  1357. */
  1358. TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
  1359. const test = this;
  1360. function waitForAllScripts() {
  1361. if (test._scriptsAreParsed(expectedScripts)) {
  1362. callback();
  1363. } else {
  1364. test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts);
  1365. }
  1366. }
  1367. waitForAllScripts();
  1368. };
  1369. TestSuite.prototype._waitForTargets = function(n, callback) {
  1370. checkTargets.call(this);
  1371. function checkTargets() {
  1372. if (SDK.targetManager.targets().length >= n) {
  1373. callback.call(null);
  1374. } else {
  1375. this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
  1376. }
  1377. }
  1378. };
  1379. TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
  1380. const runtimeModel = SDK.targetManager.mainTarget().model(SDK.RuntimeModel);
  1381. checkForExecutionContexts.call(this);
  1382. function checkForExecutionContexts() {
  1383. if (runtimeModel.executionContexts().length >= n) {
  1384. callback.call(null);
  1385. } else {
  1386. this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this));
  1387. }
  1388. }
  1389. };
  1390. window.uiTests = new TestSuite(window.domAutomationController);
  1391. })(window);