blob: 6e89e871eacca373a72b976bcba687855d847ea1 [file] [log] [blame]
Blink Reformat4c46d092018-04-07 15:32:371/*
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/**
33 * @fileoverview This file contains small testing framework along with the
34 * test suite for the frontend. These tests are a part of the continues build
Sigurd Schneider72ac3562021-03-11 10:35:2535 * and are executed by the devtools_browsertest.cc as a part of the
Blink Reformat4c46d092018-04-07 15:32:3736 * Interactive UI Test suite.
37 * FIXME: change field naming style to use trailing underscore.
38 */
39
40(function createTestSuite(window) {
Simon Zünd5111ff42023-08-23 08:46:1741 // 'Tests.js' is loaded as a classic script so we can't use static imports for these modules.
42 /** @type {import('./core/common/common.js')} */
43 let Common;
Simon Zündb4f900e2023-08-23 09:45:5744 /** @type {import('./core/host/host.js')} */
45 let HostModule;
Simon Zünd5111ff42023-08-23 08:46:1746
Blink Reformat4c46d092018-04-07 15:32:3747 const TestSuite = class {
48 /**
49 * Test suite for interactive UI tests.
50 * @param {Object} domAutomationController DomAutomationController instance.
51 */
52 constructor(domAutomationController) {
53 this.domAutomationController_ = domAutomationController;
54 this.controlTaken_ = false;
55 this.timerId_ = -1;
56 this._asyncInvocationId = 0;
57 }
58
59 /**
60 * Key event with given key identifier.
61 */
62 static createKeyEvent(key) {
63 return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key});
64 }
65 };
66
67 /**
68 * Reports test failure.
69 * @param {string} message Failure description.
70 */
71 TestSuite.prototype.fail = function(message) {
Tim van der Lippe1d6e57a2019-09-30 11:55:3472 if (this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:3773 this.reportFailure_(message);
Tim van der Lippe1d6e57a2019-09-30 11:55:3474 } else {
Blink Reformat4c46d092018-04-07 15:32:3775 throw message;
Tim van der Lippe1d6e57a2019-09-30 11:55:3476 }
Blink Reformat4c46d092018-04-07 15:32:3777 };
78
79 /**
80 * Equals assertion tests that expected === actual.
81 * @param {!Object|boolean} expected Expected object.
82 * @param {!Object|boolean} actual Actual object.
83 * @param {string} opt_message User message to print if the test fails.
84 */
85 TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
86 if (expected !== actual) {
87 let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
Tim van der Lippe1d6e57a2019-09-30 11:55:3488 if (opt_message) {
Blink Reformat4c46d092018-04-07 15:32:3789 message = opt_message + '(' + message + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:3490 }
Blink Reformat4c46d092018-04-07 15:32:3791 this.fail(message);
92 }
93 };
94
95 /**
96 * True assertion tests that value == true.
97 * @param {!Object} value Actual object.
98 * @param {string} opt_message User message to print if the test fails.
99 */
100 TestSuite.prototype.assertTrue = function(value, opt_message) {
Tim van der Lipped7cfd142021-01-07 12:17:24101 this.assertEquals(true, Boolean(value), opt_message);
Blink Reformat4c46d092018-04-07 15:32:37102 };
103
104 /**
105 * Takes control over execution.
Sigurd Schneider72ac3562021-03-11 10:35:25106 * @param {{slownessFactor:number}=} options
Blink Reformat4c46d092018-04-07 15:32:37107 */
Sigurd Schneider72ac3562021-03-11 10:35:25108 TestSuite.prototype.takeControl = function(options) {
109 const {slownessFactor} = {slownessFactor: 1, ...options};
Blink Reformat4c46d092018-04-07 15:32:37110 this.controlTaken_ = true;
111 // Set up guard timer.
112 const self = this;
Sigurd Schneider376d2712021-03-12 15:07:51113 const timeoutInSec = 20 * slownessFactor;
Blink Reformat4c46d092018-04-07 15:32:37114 this.timerId_ = setTimeout(function() {
Sigurd Schneider376d2712021-03-12 15:07:51115 self.reportFailure_(`Timeout exceeded: ${timeoutInSec} sec`);
116 }, timeoutInSec * 1000);
Blink Reformat4c46d092018-04-07 15:32:37117 };
118
119 /**
120 * Releases control over execution.
121 */
122 TestSuite.prototype.releaseControl = function() {
123 if (this.timerId_ !== -1) {
124 clearTimeout(this.timerId_);
125 this.timerId_ = -1;
126 }
127 this.controlTaken_ = false;
128 this.reportOk_();
129 };
130
131 /**
132 * Async tests use this one to report that they are completed.
133 */
134 TestSuite.prototype.reportOk_ = function() {
135 this.domAutomationController_.send('[OK]');
136 };
137
138 /**
139 * Async tests use this one to report failures.
140 */
141 TestSuite.prototype.reportFailure_ = function(error) {
142 if (this.timerId_ !== -1) {
143 clearTimeout(this.timerId_);
144 this.timerId_ = -1;
145 }
146 this.domAutomationController_.send('[FAILED] ' + error);
147 };
148
Tim van der Lippe7634cc12021-11-11 15:52:52149 TestSuite.prototype.setupLegacyFilesForTest = async function() {
150 try {
Simon Zünd5111ff42023-08-23 08:46:17151 // 'Tests.js' is executed on 'about:blank' so we can't use `import` directly without
152 // specifying the full devtools://devtools/bundled URL.
153 Common = await self.runtime.loadLegacyModule('core/common/common.js');
Simon Zündb4f900e2023-08-23 09:45:57154 HostModule = await self.runtime.loadLegacyModule('core/host/host.js');
155
156 // We have to map 'Host.InspectorFrontendHost' as the C++ uses it directly.
157 self.Host = {};
158 self.Host.InspectorFrontendHost = HostModule.InspectorFrontendHost.InspectorFrontendHostInstance;
159 self.Host.InspectorFrontendHostAPI = HostModule.InspectorFrontendHostAPI;
160
Tim van der Lippe7634cc12021-11-11 15:52:52161 await Promise.all([
Tim van der Lippe7634cc12021-11-11 15:52:52162 self.runtime.loadLegacyModule('core/sdk/sdk-legacy.js'),
163 self.runtime.loadLegacyModule('ui/legacy/legacy-legacy.js'),
164 self.runtime.loadLegacyModule('models/workspace/workspace-legacy.js'),
Jack Franklin408ed8a2023-07-07 11:05:56165 self.runtime.loadLegacyModule('models/trace/trace-legacy.js'),
Tim van der Lippe7634cc12021-11-11 15:52:52166 ]);
167 this.reportOk_();
168 } catch (e) {
169 this.reportFailure_(e);
170 }
171 };
172
Blink Reformat4c46d092018-04-07 15:32:37173 /**
174 * Run specified test on a fresh instance of the test suite.
175 * @param {Array<string>} args method name followed by its parameters.
176 */
Danil Somsikov266e53e2021-10-25 16:07:42177 TestSuite.prototype.dispatchOnTestSuite = async function(args) {
Blink Reformat4c46d092018-04-07 15:32:37178 const methodName = args.shift();
179 try {
Danil Somsikov266e53e2021-10-25 16:07:42180 await this[methodName].apply(this, args);
Tim van der Lippe1d6e57a2019-09-30 11:55:34181 if (!this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:37182 this.reportOk_();
Tim van der Lippe1d6e57a2019-09-30 11:55:34183 }
Blink Reformat4c46d092018-04-07 15:32:37184 } catch (e) {
185 this.reportFailure_(e);
186 }
187 };
188
189 /**
190 * Wrap an async method with TestSuite.{takeControl(), releaseControl()}
191 * and invoke TestSuite.reportOk_ upon completion.
192 * @param {Array<string>} args method name followed by its parameters.
193 */
194 TestSuite.prototype.waitForAsync = function(var_args) {
195 const args = Array.prototype.slice.call(arguments);
196 this.takeControl();
197 args.push(this.releaseControl.bind(this));
198 this.dispatchOnTestSuite(args);
199 };
200
201 /**
202 * Overrides the method with specified name until it's called first time.
203 * @param {!Object} receiver An object whose method to override.
204 * @param {string} methodName Name of the method to override.
205 * @param {!Function} override A function that should be called right after the
206 * overridden method returns.
207 * @param {?boolean} opt_sticky Whether restore original method after first run
208 * or not.
209 */
210 TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) {
211 const orig = receiver[methodName];
Tim van der Lippe1d6e57a2019-09-30 11:55:34212 if (typeof orig !== 'function') {
Blink Reformat4c46d092018-04-07 15:32:37213 this.fail('Cannot find method to override: ' + methodName);
Tim van der Lippe1d6e57a2019-09-30 11:55:34214 }
Blink Reformat4c46d092018-04-07 15:32:37215 const test = this;
216 receiver[methodName] = function(var_args) {
217 let result;
218 try {
219 result = orig.apply(this, arguments);
220 } finally {
Tim van der Lippe1d6e57a2019-09-30 11:55:34221 if (!opt_sticky) {
Blink Reformat4c46d092018-04-07 15:32:37222 receiver[methodName] = orig;
Tim van der Lippe1d6e57a2019-09-30 11:55:34223 }
Blink Reformat4c46d092018-04-07 15:32:37224 }
225 // In case of exception the override won't be called.
226 try {
227 override.apply(this, arguments);
228 } catch (e) {
229 test.fail('Exception in overriden method \'' + methodName + '\': ' + e);
230 }
231 return result;
232 };
233 };
234
235 /**
236 * Waits for current throttler invocations, if any.
237 * @param {!Common.Throttler} throttler
238 * @param {function()} callback
239 */
240 TestSuite.prototype.waitForThrottler = function(throttler, callback) {
241 const test = this;
242 let scheduleShouldFail = true;
243 test.addSniffer(throttler, 'schedule', onSchedule);
244
245 function hasSomethingScheduled() {
246 return throttler._isRunningProcess || throttler._process;
247 }
248
249 function checkState() {
250 if (!hasSomethingScheduled()) {
251 scheduleShouldFail = false;
252 callback();
253 return;
254 }
255
Sigurd Schneider9e9a51c2021-08-19 12:02:24256 test.addSniffer(throttler, 'processCompletedForTests', checkState);
Blink Reformat4c46d092018-04-07 15:32:37257 }
258
259 function onSchedule() {
Tim van der Lippe1d6e57a2019-09-30 11:55:34260 if (scheduleShouldFail) {
Blink Reformat4c46d092018-04-07 15:32:37261 test.fail('Unexpected Throttler.schedule');
Tim van der Lippe1d6e57a2019-09-30 11:55:34262 }
Blink Reformat4c46d092018-04-07 15:32:37263 }
264
265 checkState();
266 };
267
268 /**
269 * @param {string} panelName Name of the panel to show.
270 */
271 TestSuite.prototype.showPanel = function(panelName) {
Paul Lewis0a7c6b62020-01-23 16:16:22272 return self.UI.inspectorView.showPanel(panelName);
Blink Reformat4c46d092018-04-07 15:32:37273 };
274
275 // UI Tests
276
277 /**
278 * Tests that scripts tab can be open and populated with inspected scripts.
279 */
280 TestSuite.prototype.testShowScriptsTab = function() {
281 const test = this;
282 this.showPanel('sources').then(function() {
283 // There should be at least main page script.
284 this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
285 test.releaseControl();
286 });
287 }.bind(this));
288 // Wait until all scripts are added to the debugger.
289 this.takeControl();
290 };
291
292 /**
Alex Rudenkob6eac402023-08-10 07:41:53293 * Tests that Recorder tab can be open.
294 */
295 TestSuite.prototype.testShowRecorderTab = function() {
296 this.showPanel('chrome_recorder')
297 .then(() => {
298 this.releaseControl();
299 })
300 .catch(err => {
301 this.fail('Loading Recorder panel failed: ' + err.message);
302 });
303 this.takeControl();
304 };
305
306 /**
Blink Reformat4c46d092018-04-07 15:32:37307 * Tests that scripts list contains content scripts.
308 */
309 TestSuite.prototype.testContentScriptIsPresent = function() {
310 const test = this;
311 this.showPanel('sources').then(function() {
312 test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() {
313 test.releaseControl();
314 });
315 });
316
317 // Wait until all scripts are added to the debugger.
318 this.takeControl();
319 };
320
321 /**
322 * Tests that scripts are not duplicaed on Scripts tab switch.
323 */
324 TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() {
325 const test = this;
326
327 function switchToElementsTab() {
328 test.showPanel('elements').then(function() {
329 setTimeout(switchToScriptsTab, 0);
330 });
331 }
332
333 function switchToScriptsTab() {
334 test.showPanel('sources').then(function() {
335 setTimeout(checkScriptsPanel, 0);
336 });
337 }
338
339 function checkScriptsPanel() {
340 test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.');
341 checkNoDuplicates();
342 test.releaseControl();
343 }
344
345 function checkNoDuplicates() {
346 const uiSourceCodes = test.nonAnonymousUISourceCodes_();
347 for (let i = 0; i < uiSourceCodes.length; i++) {
348 for (let j = i + 1; j < uiSourceCodes.length; j++) {
349 test.assertTrue(
350 uiSourceCodes[i].url() !== uiSourceCodes[j].url(),
351 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes));
352 }
353 }
354 }
355
356 this.showPanel('sources').then(function() {
357 test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
358 checkNoDuplicates();
359 setTimeout(switchToElementsTab, 0);
360 });
361 });
362
363 // Wait until all scripts are added to the debugger.
Sigurd Schneiderd8d7e822021-03-16 09:34:19364 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37365 };
366
367 // Tests that debugger works correctly if pause event occurs when DevTools
368 // frontend is being loaded.
369 TestSuite.prototype.testPauseWhenLoadingDevTools = function() {
Danil Somsikov494f09a2023-04-17 11:08:41370 const debuggerModel = self.SDK.targetManager.primaryPageTarget().model(SDK.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34371 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37372 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34373 }
Blink Reformat4c46d092018-04-07 15:32:37374
375 this.showPanel('sources').then(function() {
376 // Script execution can already be paused.
377
378 this._waitForScriptPause(this.releaseControl.bind(this));
379 }.bind(this));
380
381 this.takeControl();
382 };
383
Blink Reformat4c46d092018-04-07 15:32:37384 /**
385 * Tests network size.
386 */
387 TestSuite.prototype.testNetworkSize = function() {
388 const test = this;
389
390 function finishRequest(request, finishTime) {
391 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
392 test.releaseControl();
393 }
394
Jan Scheffler4ada3312021-08-06 09:51:21395 this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37396
397 // Reload inspected page to sniff network events
398 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
399
Sigurd Schneiderd8d7e822021-03-16 09:34:19400 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37401 };
402
403 /**
404 * Tests network sync size.
405 */
406 TestSuite.prototype.testNetworkSyncSize = function() {
407 const test = this;
408
409 function finishRequest(request, finishTime) {
410 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
411 test.releaseControl();
412 }
413
Jan Scheffler4ada3312021-08-06 09:51:21414 this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37415
416 // Send synchronous XHR to sniff network events
417 test.evaluateInConsole_(
418 'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {});
419
Sigurd Schneiderd8d7e822021-03-16 09:34:19420 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37421 };
422
423 /**
424 * Tests network raw headers text.
425 */
426 TestSuite.prototype.testNetworkRawHeadersText = function() {
427 const test = this;
428
429 function finishRequest(request, finishTime) {
Tim van der Lippe1d6e57a2019-09-30 11:55:34430 if (!request.responseHeadersText) {
Blink Reformat4c46d092018-04-07 15:32:37431 test.fail('Failure: resource does not have response headers text');
Tim van der Lippe1d6e57a2019-09-30 11:55:34432 }
Blink Reformat4c46d092018-04-07 15:32:37433 const index = request.responseHeadersText.indexOf('Date:');
434 test.assertEquals(
435 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length');
436 test.releaseControl();
437 }
438
Jan Scheffler4ada3312021-08-06 09:51:21439 this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37440
441 // Reload inspected page to sniff network events
442 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
443
Sigurd Schneiderd8d7e822021-03-16 09:34:19444 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37445 };
446
447 /**
448 * Tests network timing.
449 */
450 TestSuite.prototype.testNetworkTiming = function() {
451 const test = this;
452
453 function finishRequest(request, finishTime) {
454 // Setting relaxed expectations to reduce flakiness.
455 // Server sends headers after 100ms, then sends data during another 100ms.
456 // We expect these times to be measured at least as 70ms.
457 test.assertTrue(
458 request.timing.receiveHeadersEnd - request.timing.connectStart >= 70,
459 'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' +
Jack Franklin408ed8a2023-07-07 11:05:56460 'receiveHeadersEnd=' + request.timing.receiveHeadersEnd +
461 ', connectStart=' + request.timing.connectStart + '.');
Blink Reformat4c46d092018-04-07 15:32:37462 test.assertTrue(
463 request.responseReceivedTime - request.startTime >= 0.07,
464 'Time between responseReceivedTime and startTime should be >=0.07s, but was ' +
465 'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.');
466 test.assertTrue(
467 request.endTime - request.startTime >= 0.14,
468 'Time between endTime and startTime should be >=0.14s, but was ' +
469 'endtime=' + request.endTime + ', startTime=' + request.startTime + '.');
470
471 test.releaseControl();
472 }
473
Jan Scheffler4ada3312021-08-06 09:51:21474 this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37475
476 // Reload inspected page to sniff network events
477 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
478
Sigurd Schneiderd8d7e822021-03-16 09:34:19479 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37480 };
481
482 TestSuite.prototype.testPushTimes = function(url) {
483 const test = this;
484 let pendingRequestCount = 2;
485
486 function finishRequest(request, finishTime) {
487 test.assertTrue(
488 typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0,
489 `pushStart is invalid: ${request.timing.pushStart}`);
490 test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`);
491 test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime');
492 if (request.url().endsWith('?pushUseNullEndTime')) {
493 test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`);
494 } else {
495 test.assertTrue(
496 request.timing.pushStart < request.timing.pushEnd,
497 `pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`);
498 // The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant.
499 test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime');
500 test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime');
501 }
Tim van der Lippe1d6e57a2019-09-30 11:55:34502 if (!--pendingRequestCount) {
Blink Reformat4c46d092018-04-07 15:32:37503 test.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:34504 }
Blink Reformat4c46d092018-04-07 15:32:37505 }
506
Jan Scheffler4ada3312021-08-06 09:51:21507 this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest, true);
Blink Reformat4c46d092018-04-07 15:32:37508
509 test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {});
510 test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {});
511 this.takeControl();
512 };
513
514 TestSuite.prototype.testConsoleOnNavigateBack = function() {
Blink Reformat4c46d092018-04-07 15:32:37515 function filteredMessages() {
Wolfgang Beyer5a872a22023-03-02 10:46:15516 return SDK.ConsoleModel.allMessagesUnordered().filter(a => a.source !== Protocol.Log.LogEntrySource.Violation);
Blink Reformat4c46d092018-04-07 15:32:37517 }
518
Tim van der Lippe1d6e57a2019-09-30 11:55:34519 if (filteredMessages().length === 1) {
Blink Reformat4c46d092018-04-07 15:32:37520 firstConsoleMessageReceived.call(this, null);
Tim van der Lippe1d6e57a2019-09-30 11:55:34521 } else {
Wolfgang Beyer5a872a22023-03-02 10:46:15522 self.SDK.targetManager.addModelListener(
523 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Tim van der Lippe1d6e57a2019-09-30 11:55:34524 }
Blink Reformat4c46d092018-04-07 15:32:37525
Blink Reformat4c46d092018-04-07 15:32:37526 function firstConsoleMessageReceived(event) {
Tim van der Lippeeb876c62021-05-14 15:02:11527 if (event && event.data.source === Protocol.Log.LogEntrySource.Violation) {
Blink Reformat4c46d092018-04-07 15:32:37528 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34529 }
Wolfgang Beyer5a872a22023-03-02 10:46:15530 self.SDK.targetManager.removeModelListener(
531 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Blink Reformat4c46d092018-04-07 15:32:37532 this.evaluateInConsole_('clickLink();', didClickLink.bind(this));
533 }
534
535 function didClickLink() {
536 // Check that there are no new messages(command is not a message).
537 this.assertEquals(3, filteredMessages().length);
538 this.evaluateInConsole_('history.back();', didNavigateBack.bind(this));
539 }
540
541 function didNavigateBack() {
542 // Make sure navigation completed and possible console messages were pushed.
543 this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this));
544 }
545
546 function didCompleteNavigation() {
547 this.assertEquals(7, filteredMessages().length);
548 this.releaseControl();
549 }
550
551 this.takeControl();
552 };
553
554 TestSuite.prototype.testSharedWorker = function() {
555 function didEvaluateInConsole(resultText) {
556 this.assertEquals('2011', resultText);
557 this.releaseControl();
558 }
559 this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this));
560 this.takeControl();
561 };
562
563 TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() {
564 // Make sure the worker is loaded.
565 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00566 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37567
568 function callback() {
Simon Zündb6414c92020-03-19 07:16:40569 ProtocolClient.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37570 }
571 };
572
573 TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() {
574 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00575 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37576
577 function callback() {
Paul Lewis4ae5f4f2020-01-23 10:19:33578 const debuggerModel = self.SDK.targetManager.models(SDK.DebuggerModel)[0];
Blink Reformat4c46d092018-04-07 15:32:37579 if (debuggerModel.isPaused()) {
Wolfgang Beyer5a872a22023-03-02 10:46:15580 self.SDK.targetManager.addModelListener(
581 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31582 debuggerModel.resume();
Blink Reformat4c46d092018-04-07 15:32:37583 return;
584 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31585 this._waitForScriptPause(callback.bind(this));
586 }
587
588 function onConsoleMessage(event) {
589 const message = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:34590 if (message !== 'connected') {
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31591 this.fail('Unexpected message: ' + message);
Tim van der Lippe1d6e57a2019-09-30 11:55:34592 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31593 this.releaseControl();
Blink Reformat4c46d092018-04-07 15:32:37594 }
595 };
596
Joey Arhar0585e6f2018-10-30 23:11:18597 TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
598 this.takeControl();
599 this.showPanel('network').then(() => {
Tim van der Lippe1d6e57a2019-09-30 11:55:34600 if (!document.querySelector('#network-container')) {
Joey Arhar0585e6f2018-10-30 23:11:18601 this.fail('unable to find #network-container');
Tim van der Lippe1d6e57a2019-09-30 11:55:34602 }
Joey Arhar0585e6f2018-10-30 23:11:18603 this.releaseControl();
604 });
605 };
606
Blink Reformat4c46d092018-04-07 15:32:37607 TestSuite.prototype.enableTouchEmulation = function() {
608 const deviceModeModel = new Emulation.DeviceModeModel(function() {});
Danil Somsikov494f09a2023-04-17 11:08:41609 deviceModeModel._target = self.SDK.targetManager.primaryPageTarget();
Blink Reformat4c46d092018-04-07 15:32:37610 deviceModeModel._applyTouch(true, true);
611 };
612
613 TestSuite.prototype.waitForDebuggerPaused = function() {
Danil Somsikov494f09a2023-04-17 11:08:41614 const debuggerModel = self.SDK.targetManager.primaryPageTarget().model(SDK.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34615 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37616 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34617 }
Blink Reformat4c46d092018-04-07 15:32:37618
619 this.takeControl();
620 this._waitForScriptPause(this.releaseControl.bind(this));
621 };
622
623 TestSuite.prototype.switchToPanel = function(panelName) {
624 this.showPanel(panelName).then(this.releaseControl.bind(this));
625 this.takeControl();
626 };
627
628 // Regression test for crbug.com/370035.
629 TestSuite.prototype.testDeviceMetricsOverrides = function() {
630 function dumpPageMetrics() {
631 return JSON.stringify(
632 {width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
633 }
634
635 const test = this;
636
637 async function testOverrides(params, metrics, callback) {
Danil Somsikov494f09a2023-04-17 11:08:41638 await self.SDK.targetManager.primaryPageTarget().emulationAgent().invoke_setDeviceMetricsOverride(params);
Blink Reformat4c46d092018-04-07 15:32:37639 test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics);
640
641 function checkMetrics(consoleResult) {
642 test.assertEquals(
Johan Bay9ea04a82021-06-22 09:20:15643 `'${JSON.stringify(metrics)}'`, consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params));
Blink Reformat4c46d092018-04-07 15:32:37644 callback();
645 }
646 }
647
648 function step1() {
649 testOverrides(
650 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
651 {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
652 }
653
654 function step2() {
655 testOverrides(
656 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
657 {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
658 }
659
660 function step3() {
661 testOverrides(
662 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
663 {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
664 }
665
666 function step4() {
667 testOverrides(
668 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
669 {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
670 }
671
672 function finish() {
673 test.releaseControl();
674 }
675
676 test.takeControl();
677 step1();
678 };
679
680 TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
681 const test = this;
682 let receivedReady = false;
683
684 function signalToShowAutofill() {
Danil Somsikov494f09a2023-04-17 11:08:41685 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37686 {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Danil Somsikov494f09a2023-04-17 11:08:41687 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37688 {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
689 }
690
691 function selectTopAutoFill() {
Danil Somsikov494f09a2023-04-17 11:08:41692 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37693 {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
Danil Somsikov494f09a2023-04-17 11:08:41694 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37695 {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
696
697 test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
698 }
699
700 function onResultOfInput(value) {
Johan Bay9ea04a82021-06-22 09:20:15701 // Console adds '' around the response.
702 test.assertEquals('\'Abbf\'', value);
Blink Reformat4c46d092018-04-07 15:32:37703 test.releaseControl();
704 }
705
706 function onConsoleMessage(event) {
707 const message = event.data.messageText;
708 if (message === 'ready' && !receivedReady) {
709 receivedReady = true;
710 signalToShowAutofill();
711 }
712 // This log comes from the browser unittest code.
Tim van der Lippe1d6e57a2019-09-30 11:55:34713 if (message === 'didShowSuggestions') {
Blink Reformat4c46d092018-04-07 15:32:37714 selectTopAutoFill();
Tim van der Lippe1d6e57a2019-09-30 11:55:34715 }
Blink Reformat4c46d092018-04-07 15:32:37716 }
717
Sigurd Schneider5cfca2e2021-03-22 12:09:28718 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37719
720 // It is possible for the ready console messagage to be already received but not handled
721 // or received later. This ensures we can catch both cases.
Wolfgang Beyer5a872a22023-03-02 10:46:15722 self.SDK.targetManager.addModelListener(
723 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37724
Wolfgang Beyer5a872a22023-03-02 10:46:15725 const messages = SDK.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:37726 if (messages.length) {
727 const text = messages[0].messageText;
728 this.assertEquals('ready', text);
729 signalToShowAutofill();
730 }
731 };
732
Pâris MEULEMANd4709cb2019-04-17 08:32:48733 TestSuite.prototype.testKeyEventUnhandled = function() {
734 function onKeyEventUnhandledKeyDown(event) {
735 this.assertEquals('keydown', event.data.type);
736 this.assertEquals('F8', event.data.key);
737 this.assertEquals(119, event.data.keyCode);
738 this.assertEquals(0, event.data.modifiers);
739 this.assertEquals('', event.data.code);
Tim van der Lippe50cfa9b2019-10-01 10:40:58740 Host.InspectorFrontendHost.events.removeEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44741 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Tim van der Lippe50cfa9b2019-10-01 10:40:58742 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44743 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
Danil Somsikov494f09a2023-04-17 11:08:41744 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48745 {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
746 }
747 function onKeyEventUnhandledKeyUp(event) {
748 this.assertEquals('keyup', event.data.type);
749 this.assertEquals('F8', event.data.key);
750 this.assertEquals(119, event.data.keyCode);
751 this.assertEquals(0, event.data.modifiers);
752 this.assertEquals('F8', event.data.code);
753 this.releaseControl();
754 }
755 this.takeControl();
Tim van der Lippe50cfa9b2019-10-01 10:40:58756 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44757 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Danil Somsikov494f09a2023-04-17 11:08:41758 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48759 {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
760 };
761
Jack Lynchb514f9f2020-06-19 21:16:45762 // Tests that the keys that are forwarded from the browser update
763 // when their shortcuts change
764 TestSuite.prototype.testForwardedKeysChanged = function() {
Jack Lynch080a0fd2020-06-15 19:55:19765 this.takeControl();
766
Jan Scheffler01eab3c2021-08-16 17:18:07767 this.addSniffer(self.UI.shortcutRegistry, 'registerBindings', () => {
Danil Somsikov494f09a2023-04-17 11:08:41768 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Jack Lynch080a0fd2020-06-15 19:55:19769 {type: 'rawKeyDown', key: 'F1', windowsVirtualKeyCode: 112, nativeVirtualKeyCode: 112});
770 });
771 this.addSniffer(self.UI.shortcutRegistry, 'handleKey', key => {
772 this.assertEquals(112, key);
773 this.releaseControl();
774 });
775
Simon Zünd5111ff42023-08-23 08:46:17776 Common.Settings.moduleSetting('activeKeybindSet').set('vsCode');
Jack Lynch080a0fd2020-06-15 19:55:19777 };
778
Blink Reformat4c46d092018-04-07 15:32:37779 TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
Danil Somsikov494f09a2023-04-17 11:08:41780 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37781 {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
Danil Somsikov494f09a2023-04-17 11:08:41782 self.SDK.targetManager.primaryPageTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37783 {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
784 };
785
Pâris MEULEMANd81f35f2019-05-07 09:04:34786 // Check that showing the certificate viewer does not crash, crbug.com/954874
787 TestSuite.prototype.testShowCertificate = function() {
Tim van der Lippe50cfa9b2019-10-01 10:40:58788 Host.InspectorFrontendHost.showCertificateViewer([
Pâris MEULEMANd81f35f2019-05-07 09:04:34789 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
790 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
791 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
792 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
793 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
794 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
795 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
796 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
797 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
798 'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
799 'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
800 'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOcIA7AVR/Ck22Uj8X' +
801 'UOECercjUrKdDyaAPcLp2TThAgMBAAGjggHZMIIB1TATBgNVHSUEDDAKBggr' +
802 'BgEFBQcDATCBrwYDVR0RBIGnMIGkgg0qLmFwcHNwb3QuY29tggsqLmEucnVu' +
803 'LmFwcIIVKi50aGlua3dpdGhnb29nbGUuY29tghAqLndpdGhnb29nbGUuY29t' +
804 'ghEqLndpdGh5b3V0dWJlLmNvbYILYXBwc3BvdC5jb22CB3J1bi5hcHCCE3Ro' +
805 'aW5rd2l0aGdvb2dsZS5jb22CDndpdGhnb29nbGUuY29tgg93aXRoeW91dHVi' +
806 'ZS5jb20waAYIKwYBBQUHAQEEXDBaMC0GCCsGAQUFBzAChiFodHRwOi8vcGtp' +
807 'Lmdvb2cvZ3NyMi9HVFNHSUFHMy5jcnQwKQYIKwYBBQUHMAGGHWh0dHA6Ly9v' +
808 'Y3NwLnBraS5nb29nL0dUU0dJQUczMB0GA1UdDgQWBBTGkpE5o0H9+Wjc05rF' +
809 'hNQiYDjBFjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFHfCuFCaZ3Z2sS3C' +
810 'htCDoH6mfrpLMCEGA1UdIAQaMBgwDAYKKwYBBAHWeQIFAzAIBgZngQwBAgIw' +
811 'MQYDVR0fBCowKDAmoCSgIoYgaHR0cDovL2NybC5wa2kuZ29vZy9HVFNHSUFH' +
812 'My5jcmwwDQYJKoZIhvcNAQELBQADggEBALqoYGqWtJW/6obEzY+ehsgfyXb+' +
813 'qNIuV09wt95cRF93HlLbBlSZ/Iz8HXX44ZT1/tGAkwKnW0gDKSSab3I8U+e9' +
814 'LHbC9VXrgAFENzu89MNKNmK5prwv+MPA2HUQPu4Pad3qXmd4+nKc/EUjtg1d' +
815 '/xKGK1Vn6JX3i5ly/rduowez3LxpSAJuIwseum331aQaKC2z2ri++96B8MPU' +
816 'KFXzvV2gVGOe3ZYqmwPaG8y38Tba+OzEh59ygl8ydJJhoI6+R3itPSy0aXUU' +
817 'lMvvAbfCobXD5kBRQ28ysgbDSDOPs3fraXpAKL92QUjsABs58XBz5vka4swu' +
818 'gg/u+ZxaKOqfIm8=',
819 'MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBM' +
820 'MSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMK' +
821 'R2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAw' +
822 'NDJaFw0yMTEyMTUwMDAwNDJaMFQxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVH' +
823 'b29nbGUgVHJ1c3QgU2VydmljZXMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5l' +
824 'dCBBdXRob3JpdHkgRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB' +
825 'AQDKUkvqHv/OJGuo2nIYaNVWXQ5IWi01CXZaz6TIHLGp/lOJ+600/4hbn7vn' +
826 '6AAB3DVzdQOts7G5pH0rJnnOFUAK71G4nzKMfHCGUksW/mona+Y2emJQ2N+a' +
827 'icwJKetPKRSIgAuPOB6Aahh8Hb2XO3h9RUk2T0HNouB2VzxoMXlkyW7XUR5m' +
828 'w6JkLHnA52XDVoRTWkNty5oCINLvGmnRsJ1zouAqYGVQMc/7sy+/EYhALrVJ' +
829 'EA8KbtyX+r8snwU5C1hUrwaW6MWOARa8qBpNQcWTkaIeoYvy/sGIJEmjR0vF' +
830 'EwHdp1cSaWIr6/4g72n7OqXwfinu7ZYW97EfoOSQJeAzAgMBAAGjggEzMIIB' +
831 'LzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF' +
832 'BwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFHfCuFCaZ3Z2sS3C' +
833 'htCDoH6mfrpLMB8GA1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUG' +
834 'CCsGAQUFBwEBBCkwJzAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdv' +
835 'b2cvZ3NyMjAyBgNVHR8EKzApMCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29n' +
836 'L2dzcjIvZ3NyMi5jcmwwPwYDVR0gBDgwNjA0BgZngQwBAgIwKjAoBggrBgEF' +
837 'BQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9yZXBvc2l0b3J5LzANBgkqhkiG9w0B' +
838 'AQsFAAOCAQEAHLeJluRT7bvs26gyAZ8so81trUISd7O45skDUmAge1cnxhG1' +
839 'P2cNmSxbWsoiCt2eux9LSD+PAj2LIYRFHW31/6xoic1k4tbWXkDCjir37xTT' +
840 'NqRAMPUyFRWSdvt+nlPqwnb8Oa2I/maSJukcxDjNSfpDh/Bd1lZNgdd/8cLd' +
841 'sE3+wypufJ9uXO1iQpnh9zbuFIwsIONGl1p3A8CgxkqI/UAih3JaGOqcpcda' +
842 'CIzkBaR9uYQ1X4k2Vg5APRLouzVy7a8IVk6wuy6pm+T7HT4LY8ibS5FEZlfA' +
843 'FLSW8NwsVz9SBK2Vqn1N0PIMn5xA6NZVc7o835DLAFshEWfC7TIe3g==',
844 'MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEg' +
845 'MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkds' +
846 'b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAw' +
847 'WhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg' +
848 'Q0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs' +
849 'U2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o' +
850 'mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe' +
851 '+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1' +
852 'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
853 'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
854 '4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
855 'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
856 'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
857 'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
858 'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
859 'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
860 'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
861 'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
862 'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
863 '9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
864 'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
865 '/H5COEBkEveegeGTLg=='
866 ]);
867 };
868
Paul Lewise407fce2021-02-26 09:59:31869 // Simple check to make sure network throttling is wired up
Blink Reformat4c46d092018-04-07 15:32:37870 // See crbug.com/747724
871 TestSuite.prototype.testOfflineNetworkConditions = async function() {
872 const test = this;
Paul Lewis5a922e72020-01-24 11:58:08873 self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Blink Reformat4c46d092018-04-07 15:32:37874
875 function finishRequest(request) {
876 test.assertEquals(
877 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
878 test.releaseControl();
879 }
880
Jan Scheffler4ada3312021-08-06 09:51:21881 this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37882
Danil Somsikovf9a63312021-10-01 13:21:08883 test.takeControl();
884 test.evaluateInConsole_('await fetch("/");', function(resultText) {});
Blink Reformat4c46d092018-04-07 15:32:37885 };
886
887 TestSuite.prototype.testEmulateNetworkConditions = function() {
888 const test = this;
889
890 function testPreset(preset, messages, next) {
891 function onConsoleMessage(event) {
892 const index = messages.indexOf(event.data.messageText);
893 if (index === -1) {
894 test.fail('Unexpected message: ' + event.data.messageText);
895 return;
896 }
897
898 messages.splice(index, 1);
899 if (!messages.length) {
Wolfgang Beyer5a872a22023-03-02 10:46:15900 self.SDK.targetManager.removeModelListener(
901 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37902 next();
903 }
904 }
905
Wolfgang Beyer5a872a22023-03-02 10:46:15906 self.SDK.targetManager.addModelListener(
907 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Paul Lewis5a922e72020-01-24 11:58:08908 self.SDK.multitargetNetworkManager.setNetworkConditions(preset);
Blink Reformat4c46d092018-04-07 15:32:37909 }
910
911 test.takeControl();
912 step1();
913
914 function step1() {
915 testPreset(
916 MobileThrottling.networkPresets[2],
917 [
918 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
919 ],
920 step2);
921 }
922
923 function step2() {
924 testPreset(
925 MobileThrottling.networkPresets[1],
926 [
927 'online event: online = true',
Wolfgang Beyerd451ecd2020-10-23 08:35:54928 'connection change event: type = cellular; downlinkMax = 0.3814697265625; effectiveType = 2g'
Blink Reformat4c46d092018-04-07 15:32:37929 ],
930 step3);
931 }
932
933 function step3() {
934 testPreset(
935 MobileThrottling.networkPresets[0],
Wolfgang Beyerd451ecd2020-10-23 08:35:54936 ['connection change event: type = cellular; downlinkMax = 1.373291015625; effectiveType = 3g'],
Blink Reformat4c46d092018-04-07 15:32:37937 test.releaseControl.bind(test));
938 }
939 };
940
941 TestSuite.prototype.testScreenshotRecording = function() {
942 const test = this;
943
944 function performActionsInPage(callback) {
945 let count = 0;
946 const div = document.createElement('div');
947 div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
948 document.body.appendChild(div);
949 requestAnimationFrame(frame);
950 function frame() {
951 const color = [0, 0, 0];
952 color[count % 3] = 255;
953 div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34954 if (++count > 10) {
Blink Reformat4c46d092018-04-07 15:32:37955 requestAnimationFrame(callback);
Tim van der Lippe1d6e57a2019-09-30 11:55:34956 } else {
Blink Reformat4c46d092018-04-07 15:32:37957 requestAnimationFrame(frame);
Tim van der Lippe1d6e57a2019-09-30 11:55:34958 }
Blink Reformat4c46d092018-04-07 15:32:37959 }
960 }
961
Simon Zünd5111ff42023-08-23 08:46:17962 const captureFilmStripSetting =
963 Common.Settings.Settings.instance().createSetting('timelineCaptureFilmStrip', false);
Blink Reformat4c46d092018-04-07 15:32:37964 captureFilmStripSetting.set(true);
965 test.evaluateInConsole_(performActionsInPage.toString(), function() {});
966 test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
967
968 function onTimelineDone() {
969 captureFilmStripSetting.set(false);
970 const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
971 const frames = filmStripModel.frames();
972 test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
973 loadFrameImages(frames);
974 }
975
976 function loadFrameImages(frames) {
977 const readyImages = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:34978 for (const frame of frames) {
Blink Reformat4c46d092018-04-07 15:32:37979 frame.imageDataPromise().then(onGotImageData);
Tim van der Lippe1d6e57a2019-09-30 11:55:34980 }
Blink Reformat4c46d092018-04-07 15:32:37981
982 function onGotImageData(data) {
983 const image = new Image();
Tim van der Lipped7cfd142021-01-07 12:17:24984 test.assertTrue(Boolean(data), 'No image data for frame');
Blink Reformat4c46d092018-04-07 15:32:37985 image.addEventListener('load', onLoad);
986 image.src = 'data:image/jpg;base64,' + data;
987 }
988
989 function onLoad(event) {
990 readyImages.push(event.target);
Tim van der Lippe1d6e57a2019-09-30 11:55:34991 if (readyImages.length === frames.length) {
Blink Reformat4c46d092018-04-07 15:32:37992 validateImagesAndCompleteTest(readyImages);
Tim van der Lippe1d6e57a2019-09-30 11:55:34993 }
Blink Reformat4c46d092018-04-07 15:32:37994 }
995 }
996
997 function validateImagesAndCompleteTest(images) {
998 let redCount = 0;
999 let greenCount = 0;
1000 let blueCount = 0;
1001
1002 const canvas = document.createElement('canvas');
1003 const ctx = canvas.getContext('2d');
1004 for (const image of images) {
1005 test.assertTrue(image.naturalWidth > 10);
1006 test.assertTrue(image.naturalHeight > 10);
1007 canvas.width = image.naturalWidth;
1008 canvas.height = image.naturalHeight;
1009 ctx.drawImage(image, 0, 0);
1010 const data = ctx.getImageData(0, 0, 1, 1);
1011 const color = Array.prototype.join.call(data.data, ',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341012 if (data.data[0] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371013 redCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341014 } else if (data.data[1] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371015 greenCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341016 } else if (data.data[2] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371017 blueCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341018 } else {
Blink Reformat4c46d092018-04-07 15:32:371019 test.fail('Unexpected color: ' + color);
Tim van der Lippe1d6e57a2019-09-30 11:55:341020 }
Blink Reformat4c46d092018-04-07 15:32:371021 }
Paul Lewise407fce2021-02-26 09:59:311022 test.assertTrue(redCount && greenCount && blueCount, 'Color check failed');
Blink Reformat4c46d092018-04-07 15:32:371023 test.releaseControl();
1024 }
1025
1026 test.takeControl();
1027 };
1028
1029 TestSuite.prototype.testSettings = function() {
1030 const test = this;
1031
1032 createSettings();
1033 test.takeControl();
1034 setTimeout(reset, 0);
1035
1036 function createSettings() {
Simon Zünd5111ff42023-08-23 08:46:171037 const localSetting = Common.Settings.Settings.instance().createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371038 localSetting.set({s: 'local', n: 1});
Simon Zünd5111ff42023-08-23 08:46:171039 const globalSetting = Common.Settings.Settings.instance().createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371040 globalSetting.set({s: 'global', n: 2});
1041 }
1042
1043 function reset() {
Tim van der Lippe99e59b82019-09-30 20:00:591044 Root.Runtime.experiments.clearForTest();
Tim van der Lippe50cfa9b2019-10-01 10:40:581045 Host.InspectorFrontendHost.getPreferences(gotPreferences);
Blink Reformat4c46d092018-04-07 15:32:371046 }
1047
1048 function gotPreferences(prefs) {
Jan Schefflerd5bf8792021-08-07 15:09:581049 Main.Main.instanceForTest.createSettings(prefs);
Blink Reformat4c46d092018-04-07 15:32:371050
Simon Zünd5111ff42023-08-23 08:46:171051 const localSetting = Common.Settings.Settings.instance().createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371052 test.assertEquals('object', typeof localSetting.get());
1053 test.assertEquals('local', localSetting.get().s);
1054 test.assertEquals(1, localSetting.get().n);
Simon Zünd5111ff42023-08-23 08:46:171055 const globalSetting = Common.Settings.Settings.instance().createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371056 test.assertEquals('object', typeof globalSetting.get());
1057 test.assertEquals('global', globalSetting.get().s);
1058 test.assertEquals(2, globalSetting.get().n);
1059 test.releaseControl();
1060 }
1061 };
1062
1063 TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
1064 const test = this;
1065 test.takeControl();
Wolfgang Beyer5a872a22023-03-02 10:46:151066 const messages = SDK.ConsoleModel.allMessagesUnordered();
Tim van der Lippe1d6e57a2019-09-30 11:55:341067 if (messages.length === 1) {
Blink Reformat4c46d092018-04-07 15:32:371068 checkMessages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341069 } else {
Wolfgang Beyer5a872a22023-03-02 10:46:151070 self.SDK.targetManager.addModelListener(
1071 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
Tim van der Lippe1d6e57a2019-09-30 11:55:341072 }
Blink Reformat4c46d092018-04-07 15:32:371073
1074 function checkMessages() {
Wolfgang Beyer5a872a22023-03-02 10:46:151075 const messages = SDK.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:371076 test.assertEquals(1, messages.length);
1077 test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
1078 test.releaseControl();
1079 }
1080 };
1081
1082 TestSuite.prototype.testConsoleContextNames = function() {
1083 const test = this;
1084 test.takeControl();
1085 this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
1086
1087 function onExecutionContexts() {
1088 const consoleView = Console.ConsoleView.instance();
Jan Scheffler9befd492021-08-12 13:44:261089 const selector = consoleView.consoleContextSelector;
Blink Reformat4c46d092018-04-07 15:32:371090 const values = [];
Jan Scheffler9befd492021-08-12 13:44:261091 for (const item of selector.items) {
Blink Reformat4c46d092018-04-07 15:32:371092 values.push(selector.titleFor(item));
Tim van der Lippe1d6e57a2019-09-30 11:55:341093 }
Blink Reformat4c46d092018-04-07 15:32:371094 test.assertEquals('top', values[0]);
1095 test.assertEquals('Simple content script', values[1]);
1096 test.releaseControl();
1097 }
1098 };
1099
1100 TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
1101 const test = this;
Sigurd Schneider5cfca2e2021-03-22 12:09:281102 test.takeControl({slownessFactor: 10});
Paul Lewis4ae5f4f2020-01-23 10:19:331103 self.SDK.targetManager.addModelListener(
Blink Reformat4c46d092018-04-07 15:32:371104 SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
1105
Jack Franklin408ed8a2023-07-07 11:05:561106 this.evaluateInConsole_(
1107 `
Blink Reformat4c46d092018-04-07 15:32:371108 let img = document.createElement('img');
1109 img.src = "${url}";
1110 document.body.appendChild(img);
Jack Franklin408ed8a2023-07-07 11:05:561111 `,
1112 () => {});
Blink Reformat4c46d092018-04-07 15:32:371113
1114 let count = 0;
1115 function onResponseReceived(event) {
Songtao Xia1e692682020-06-19 13:56:391116 const networkRequest = event.data.request;
Tim van der Lippe1d6e57a2019-09-30 11:55:341117 if (!networkRequest.url().startsWith('http')) {
Blink Reformat4c46d092018-04-07 15:32:371118 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341119 }
Blink Reformat4c46d092018-04-07 15:32:371120 switch (++count) {
1121 case 1: // Original redirect
1122 test.assertEquals(301, networkRequest.statusCode);
1123 test.assertEquals('Moved Permanently', networkRequest.statusText);
1124 test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
1125 break;
1126
1127 case 2: // HSTS internal redirect
1128 test.assertTrue(networkRequest.url().startsWith('http://'));
Blink Reformat4c46d092018-04-07 15:32:371129 test.assertEquals(307, networkRequest.statusCode);
1130 test.assertEquals('Internal Redirect', networkRequest.statusText);
1131 test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
1132 test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
1133 break;
1134
1135 case 3: // Final response
1136 test.assertTrue(networkRequest.url().startsWith('https://'));
1137 test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
1138 test.assertEquals(200, networkRequest.statusCode);
1139 test.assertEquals('OK', networkRequest.statusText);
1140 test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
1141 test.releaseControl();
1142 }
1143 }
1144 };
1145
1146 TestSuite.prototype.testDOMWarnings = function() {
Wolfgang Beyer5a872a22023-03-02 10:46:151147 const messages = SDK.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:371148 this.assertEquals(1, messages.length);
1149 const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
1150 this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
1151 };
1152
1153 TestSuite.prototype.waitForTestResultsInConsole = function() {
Wolfgang Beyer5a872a22023-03-02 10:46:151154 const messages = SDK.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:371155 for (let i = 0; i < messages.length; ++i) {
1156 const text = messages[i].messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341157 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371158 return;
Mathias Bynensf06e8c02020-02-28 13:58:281159 }
1160 if (/^FAIL/.test(text)) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341161 this.fail(text);
1162 } // This will throw.
Blink Reformat4c46d092018-04-07 15:32:371163 }
1164 // Neither PASS nor FAIL, so wait for more messages.
1165 function onConsoleMessage(event) {
1166 const text = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341167 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371168 this.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:341169 } else if (/^FAIL/.test(text)) {
Blink Reformat4c46d092018-04-07 15:32:371170 this.fail(text);
Tim van der Lippe1d6e57a2019-09-30 11:55:341171 }
Blink Reformat4c46d092018-04-07 15:32:371172 }
1173
Wolfgang Beyer5a872a22023-03-02 10:46:151174 self.SDK.targetManager.addModelListener(
1175 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Sigurd Schneiderbf7f1602021-03-18 07:51:571176 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:371177 };
1178
Andrey Kosyakova08cb9b2020-04-01 21:49:521179 TestSuite.prototype.waitForTestResultsAsMessage = function() {
1180 const onMessage = event => {
1181 if (!event.data.testOutput) {
1182 return;
1183 }
1184 top.removeEventListener('message', onMessage);
1185 const text = event.data.testOutput;
1186 if (text === 'PASS') {
1187 this.releaseControl();
1188 } else {
1189 this.fail(text);
1190 }
1191 };
1192 top.addEventListener('message', onMessage);
1193 this.takeControl();
1194 };
1195
Blink Reformat4c46d092018-04-07 15:32:371196 TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
1197 const original = receiver[methodName];
1198 if (typeof original !== 'function') {
Mathias Bynens23ee1aa2020-03-02 12:06:381199 this.fail(`TestSuite._overrideMethod: ${methodName} is not a function`);
Blink Reformat4c46d092018-04-07 15:32:371200 return;
1201 }
1202 receiver[methodName] = function() {
1203 let value;
1204 try {
1205 value = original.apply(receiver, arguments);
1206 } finally {
1207 receiver[methodName] = original;
1208 }
1209 override.apply(original, arguments);
1210 return value;
1211 };
1212 };
1213
1214 TestSuite.prototype.startTimeline = function(callback) {
1215 const test = this;
1216 this.showPanel('timeline').then(function() {
1217 const timeline = UI.panels.timeline;
Sigurd Schneider5c917812021-08-16 07:42:131218 test._overrideMethod(timeline, 'recordingStarted', callback);
Blink Reformat4c46d092018-04-07 15:32:371219 timeline._toggleRecording();
1220 });
1221 };
1222
1223 TestSuite.prototype.stopTimeline = function(callback) {
1224 const timeline = UI.panels.timeline;
1225 this._overrideMethod(timeline, 'loadingComplete', callback);
1226 timeline._toggleRecording();
1227 };
1228
1229 TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
1230 const callback = arguments[arguments.length - 1];
1231 const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
1232 const argsString = arguments.length < 3 ?
1233 '' :
1234 Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
1235 this.evaluateInConsole_(
1236 `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
Wolfgang Beyer5a872a22023-03-02 10:46:151237 self.SDK.targetManager.addModelListener(SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371238
1239 function onConsoleMessage(event) {
1240 const text = event.data.messageText;
1241 if (text === doneMessage) {
Wolfgang Beyer5a872a22023-03-02 10:46:151242 self.SDK.targetManager.removeModelListener(
1243 SDK.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371244 callback();
1245 }
1246 }
1247 };
1248
1249 TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
1250 const test = this;
1251
1252 this.startTimeline(onRecordingStarted);
1253
1254 function onRecordingStarted() {
1255 test.invokePageFunctionAsync(functionName, pageActionsDone);
1256 }
1257
1258 function pageActionsDone() {
1259 test.stopTimeline(callback);
1260 }
1261 };
1262
1263 TestSuite.prototype.enableExperiment = function(name) {
Tim van der Lippe99e59b82019-09-30 20:00:591264 Root.Runtime.experiments.enableForTest(name);
Blink Reformat4c46d092018-04-07 15:32:371265 };
1266
1267 TestSuite.prototype.checkInputEventsPresent = function() {
1268 const expectedEvents = new Set(arguments);
1269 const model = UI.panels.timeline._performanceModel.timelineModel();
1270 const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
1271 const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
1272 const prefix = 'InputLatency::';
1273 for (const e of input) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341274 if (!e.name.startsWith(prefix)) {
Blink Reformat4c46d092018-04-07 15:32:371275 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341276 }
1277 if (e.steps.length < 2) {
Blink Reformat4c46d092018-04-07 15:32:371278 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341279 }
Blink Reformat4c46d092018-04-07 15:32:371280 if (e.name.startsWith(prefix + 'Mouse') &&
Tim van der Lippe1d6e57a2019-09-30 11:55:341281 typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') {
Blink Reformat4c46d092018-04-07 15:32:371282 throw `Missing timeWaitingForMainThread on ${e.name}`;
Tim van der Lippe1d6e57a2019-09-30 11:55:341283 }
Blink Reformat4c46d092018-04-07 15:32:371284 expectedEvents.delete(e.name.substr(prefix.length));
1285 }
Tim van der Lippe1d6e57a2019-09-30 11:55:341286 if (expectedEvents.size) {
Blink Reformat4c46d092018-04-07 15:32:371287 throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341288 }
Blink Reformat4c46d092018-04-07 15:32:371289 };
1290
1291 TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
1292 this.takeControl();
Tim van der Lippe264703f2021-11-04 11:53:511293 await self.runtime.loadLegacyModule('panels/elements/elements-legacy.js');
Jan Scheffler77646c72021-08-13 18:40:381294 if (!Elements.ElementsPanel.firstInspectElementNodeNameForTest) {
1295 await new Promise(f => this.addSniffer(Elements.ElementsPanel, 'firstInspectElementCompletedForTest', f));
Tim van der Lippe1d6e57a2019-09-30 11:55:341296 }
Jan Scheffler77646c72021-08-13 18:40:381297 this.assertEquals(nodeName, Elements.ElementsPanel.firstInspectElementNodeNameForTest);
Blink Reformat4c46d092018-04-07 15:32:371298 this.releaseControl();
1299 };
1300
Andrey Lushnikovd92662b2018-05-09 03:57:001301 TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
1302 this.takeControl();
Danil Somsikov8f500502023-02-23 17:06:181303 const targetAgent = self.SDK.targetManager.rootTarget().targetAgent();
Andrey Lushnikovd92662b2018-05-09 03:57:001304 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1305 const response1 = await targetAgent.invoke_getBrowserContexts();
1306 this.assertEquals(response1.browserContextIds.length, 1);
1307 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1308 const response2 = await targetAgent.invoke_getBrowserContexts();
1309 this.assertEquals(response2.browserContextIds.length, 0);
1310 this.releaseControl();
1311 };
1312
Peter Marshalld2f58c32020-04-21 13:23:131313 TestSuite.prototype.testNewWindowFromBrowserContext = async function(url) {
1314 this.takeControl();
1315 // Create a BrowserContext.
Danil Somsikov8f500502023-02-23 17:06:181316 const targetAgent = self.SDK.targetManager.rootTarget().targetAgent();
Peter Marshalld2f58c32020-04-21 13:23:131317 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1318
1319 // Cause a Browser to be created with the temp profile.
Sigurd Schneider3fec5ca2021-05-14 10:18:341320 const {targetId} = await targetAgent.invoke_createTarget(
1321 {url: 'data:text/html,<!DOCTYPE html>', browserContextId, newWindow: true});
Peter Marshalld2f58c32020-04-21 13:23:131322 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
1323
1324 // Destroy the temp profile.
1325 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1326
1327 this.releaseControl();
1328 };
1329
Andrey Lushnikov0eea25e2018-04-24 22:29:511330 TestSuite.prototype.testCreateBrowserContext = async function(url) {
1331 this.takeControl();
1332 const browserContextIds = [];
Danil Somsikov8f500502023-02-23 17:06:181333 const targetAgent = self.SDK.targetManager.rootTarget().targetAgent();
Andrey Lushnikov0eea25e2018-04-24 22:29:511334
Danil Somsikove2101812021-11-05 13:58:561335 const target1 = await createIsolatedTarget(url, browserContextIds);
1336 const target2 = await createIsolatedTarget(url, browserContextIds);
Andrey Lushnikov0eea25e2018-04-24 22:29:511337
Andrey Lushnikov07477b42018-05-08 22:00:521338 const response = await targetAgent.invoke_getBrowserContexts();
1339 this.assertEquals(response.browserContextIds.length, 2);
1340 this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
1341 this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
1342
Andrey Lushnikov0eea25e2018-04-24 22:29:511343 await evalCode(target1, 'localStorage.setItem("page1", "page1")');
1344 await evalCode(target2, 'localStorage.setItem("page2", "page2")');
1345
1346 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
1347 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
1348 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
1349 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
1350
Andrey Lushnikov69499702018-05-08 18:20:471351 const removedTargets = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331352 self.SDK.targetManager.observeTargets(
1353 {targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
Andrey Lushnikov69499702018-05-08 18:20:471354 await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
1355 this.assertEquals(removedTargets.length, 2);
1356 this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
1357 this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
Andrey Lushnikov0eea25e2018-04-24 22:29:511358
1359 this.releaseControl();
Andrey Lushnikov0eea25e2018-04-24 22:29:511360 };
1361
Danil Somsikove2101812021-11-05 13:58:561362 /**
1363 * @param {string} url
1364 * @return {!Promise<!SDK.Target>}
1365 */
1366 async function createIsolatedTarget(url, opt_browserContextIds) {
Danil Somsikov8f500502023-02-23 17:06:181367 const targetAgent = self.SDK.targetManager.rootTarget().targetAgent();
Danil Somsikove2101812021-11-05 13:58:561368 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1369 if (opt_browserContextIds) {
1370 opt_browserContextIds.push(browserContextId);
1371 }
1372
1373 const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
1374 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
1375
1376 const target = self.SDK.targetManager.targets().find(target => target.id() === targetId);
1377 const pageAgent = target.pageAgent();
1378 await pageAgent.invoke_enable();
1379 await pageAgent.invoke_navigate({url});
1380 return target;
1381 }
1382
1383 async function disposeBrowserContext(browserContextId) {
Danil Somsikov8f500502023-02-23 17:06:181384 const targetAgent = self.SDK.targetManager.rootTarget().targetAgent();
Danil Somsikove2101812021-11-05 13:58:561385 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1386 }
1387
1388 async function evalCode(target, code) {
1389 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1390 }
1391
Blink Reformat4c46d092018-04-07 15:32:371392 TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
1393 this.takeControl();
1394
1395 await new Promise(callback => this._waitForTargets(2, callback));
1396
1397 async function takeLogs(target) {
Danil Somsikove2101812021-11-05 13:58:561398 return await evalCode(target, `
Blink Reformat4c46d092018-04-07 15:32:371399 (function() {
1400 var result = window.logs.join(' ');
1401 window.logs = [];
1402 return result;
Danil Somsikove2101812021-11-05 13:58:561403 })()`);
Blink Reformat4c46d092018-04-07 15:32:371404 }
1405
1406 let parentFrameOutput;
1407 let childFrameOutput;
1408
Danil Somsikov494f09a2023-04-17 11:08:411409 const inputAgent = self.SDK.targetManager.primaryPageTarget().inputAgent();
1410 const runtimeAgent = self.SDK.targetManager.primaryPageTarget().runtimeAgent();
Blink Reformat4c46d092018-04-07 15:32:371411 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
1412 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
1413 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
1414 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
1415 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
1416 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
1417 parentFrameOutput = 'Event type: mousedown button: 0 x: 10 y: 10 Event type: mouseup button: 0 x: 10 y: 20';
Paul Lewis4ae5f4f2020-01-23 10:19:331418 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371419 childFrameOutput = 'Event type: mousedown button: 0 x: 30 y: 40 Event type: mouseup button: 0 x: 30 y: 50';
Paul Lewis4ae5f4f2020-01-23 10:19:331420 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371421
Blink Reformat4c46d092018-04-07 15:32:371422 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
Jack Franklin408ed8a2023-07-07 11:05:561423 await runtimeAgent.invoke_evaluate({expression: 'document.querySelector(\'iframe\').focus()'});
Blink Reformat4c46d092018-04-07 15:32:371424 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
1425 parentFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331426 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371427 childFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331428 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371429
1430 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
1431 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1432 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
1433 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1434 parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
Paul Lewis4ae5f4f2020-01-23 10:19:331435 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371436 childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
Paul Lewis4ae5f4f2020-01-23 10:19:331437 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371438
1439 this.releaseControl();
1440 };
1441
Andrey Kosyakov4f7fb052019-03-19 15:53:431442 TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
Blink Reformat4c46d092018-04-07 15:32:371443 const test = this;
1444 const loggedHeaders = new Set(['cache-control', 'pragma']);
1445 function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
1446 return new Promise(fulfill => {
Simon Zündb4f900e2023-08-23 09:45:571447 HostModule.ResourceLoader.load(url, headers, callback);
Blink Reformat4c46d092018-04-07 15:32:371448
Sigurd Schneidera327cde2020-01-21 15:48:121449 function callback(success, headers, content, errorDescription) {
1450 test.assertEquals(expectedStatus, errorDescription.statusCode);
Blink Reformat4c46d092018-04-07 15:32:371451
1452 const headersArray = [];
1453 for (const name in headers) {
1454 const nameLower = name.toLowerCase();
Tim van der Lippe1d6e57a2019-09-30 11:55:341455 if (loggedHeaders.has(nameLower)) {
Blink Reformat4c46d092018-04-07 15:32:371456 headersArray.push(nameLower);
Tim van der Lippe1d6e57a2019-09-30 11:55:341457 }
Blink Reformat4c46d092018-04-07 15:32:371458 }
1459 headersArray.sort();
1460 test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
1461 test.assertEquals(expectedContent, content);
1462 fulfill();
1463 }
1464 });
1465 }
1466
Sigurd Schneider5cfca2e2021-03-22 12:09:281467 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:371468 await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
1469 await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
1470 await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
1471 await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
1472
Danil Somsikov494f09a2023-04-17 11:08:411473 await self.SDK.targetManager.primaryPageTarget().runtimeAgent().invoke_evaluate({
Blink Reformat4c46d092018-04-07 15:32:371474 expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
1475 {credentials: 'include'})`,
1476 awaitPromise: true
1477 });
1478 await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
1479
Danil Somsikov494f09a2023-04-17 11:08:411480 await self.SDK.targetManager.primaryPageTarget().runtimeAgent().invoke_evaluate({
Andrey Kosyakov73081cc2019-01-08 03:50:591481 expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
1482 {credentials: 'include'})`,
1483 awaitPromise: true
1484 });
1485 await testCase(
1486 baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
Andrey Kosyakov4f7fb052019-03-19 15:53:431487 await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
Changhao Hanaf7ba132021-05-10 12:44:541488 await testCase(fileURL, undefined, 200, [], '<!DOCTYPE html>\n<html>\n<body>\nDummy page.\n</body>\n</html>\n');
Rob Paveza30df0482019-10-09 23:15:491489 await testCase(fileURL + 'thisfileshouldnotbefound', undefined, 404, [], '');
Andrey Kosyakov73081cc2019-01-08 03:50:591490
Blink Reformat4c46d092018-04-07 15:32:371491 this.releaseControl();
1492 };
1493
Joey Arhar723d5b52019-04-19 01:31:391494 TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
1495 this.takeControl();
1496
1497 const testUserAgent = 'test user agent';
Paul Lewis5a922e72020-01-24 11:58:081498 self.SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
Joey Arhar723d5b52019-04-19 01:31:391499
1500 function onRequestUpdated(event) {
1501 const request = event.data;
Tim van der Lippe1d6e57a2019-09-30 11:55:341502 if (request.resourceType() !== Common.resourceTypes.WebSocket) {
Joey Arhar723d5b52019-04-19 01:31:391503 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341504 }
1505 if (!request.requestHeadersText()) {
Joey Arhar723d5b52019-04-19 01:31:391506 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341507 }
Joey Arhar723d5b52019-04-19 01:31:391508
1509 let actualUserAgent = 'no user-agent header';
1510 for (const {name, value} of request.requestHeaders()) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341511 if (name.toLowerCase() === 'user-agent') {
Joey Arhar723d5b52019-04-19 01:31:391512 actualUserAgent = value;
Tim van der Lippe1d6e57a2019-09-30 11:55:341513 }
Joey Arhar723d5b52019-04-19 01:31:391514 }
1515 this.assertEquals(testUserAgent, actualUserAgent);
1516 this.releaseControl();
1517 }
Paul Lewis4ae5f4f2020-01-23 10:19:331518 self.SDK.targetManager.addModelListener(
Joey Arhar723d5b52019-04-19 01:31:391519 SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
1520
1521 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
1522 };
1523
Danil Somsikov7ee05592021-10-26 09:42:111524 TestSuite.prototype.testExtensionWebSocketOfflineNetworkConditions = async function(websocketPort) {
1525 self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
1526
1527 // TODO(crbug.com/1263900): Currently we don't send loadingFailed for web sockets.
1528 // Update this once we do.
1529 this.addSniffer(SDK.NetworkDispatcher.prototype, 'webSocketClosed', () => {
1530 this.releaseControl();
1531 });
1532
1533 this.takeControl();
1534 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}/echo-with-no-extension')`, () => {});
1535 };
1536
Blink Reformat4c46d092018-04-07 15:32:371537 /**
1538 * Serializes array of uiSourceCodes to string.
1539 * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
1540 * @return {string}
1541 */
1542 TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
1543 const names = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341544 for (let i = 0; i < uiSourceCodes.length; i++) {
Blink Reformat4c46d092018-04-07 15:32:371545 names.push('"' + uiSourceCodes[i].url() + '"');
Tim van der Lippe1d6e57a2019-09-30 11:55:341546 }
Blink Reformat4c46d092018-04-07 15:32:371547 return names.join(',');
1548 };
1549
Danil Somsikov338debd2021-12-14 11:42:001550 TestSuite.prototype.testSourceMapsFromExtension = function(extensionId) {
1551 this.takeControl();
Danil Somsikov494f09a2023-04-17 11:08:411552 const debuggerModel = self.SDK.targetManager.primaryPageTarget().model(SDK.DebuggerModel);
Danil Somsikov338debd2021-12-14 11:42:001553 debuggerModel.sourceMapManager().addEventListener(
1554 SDK.SourceMapManager.Events.SourceMapAttached, this.releaseControl.bind(this));
1555
1556 this.evaluateInConsole_(
1557 `console.log(1) //# sourceMappingURL=chrome-extension://${extensionId}/source.map`, () => {});
1558 };
1559
Danil Somsikov98c7a812022-01-11 09:03:351560 TestSuite.prototype.testSourceMapsFromDevtools = function() {
1561 this.takeControl();
Danil Somsikov494f09a2023-04-17 11:08:411562 const debuggerModel = self.SDK.targetManager.primaryPageTarget().model(SDK.DebuggerModel);
Danil Somsikov98c7a812022-01-11 09:03:351563 debuggerModel.sourceMapManager().addEventListener(
1564 SDK.SourceMapManager.Events.SourceMapWillAttach, this.releaseControl.bind(this));
1565
1566 this.evaluateInConsole_(
1567 'console.log(1) //# sourceMappingURL=devtools://devtools/bundled/devtools_compatibility.js', () => {});
1568 };
1569
1570 TestSuite.prototype.testDoesNotCrashOnSourceMapsFromUnknownScheme = function() {
1571 this.evaluateInConsole_('console.log(1) //# sourceMappingURL=invalid-scheme://source.map', () => {});
1572 };
1573
Blink Reformat4c46d092018-04-07 15:32:371574 /**
1575 * Returns all loaded non anonymous uiSourceCodes.
1576 * @return {!Array.<!Workspace.UISourceCode>}
1577 */
1578 TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
1579 /**
1580 * @param {!Workspace.UISourceCode} uiSourceCode
1581 */
1582 function filterOutService(uiSourceCode) {
1583 return !uiSourceCode.project().isServiceProject();
1584 }
1585
Paul Lewis10e83a92020-01-23 14:07:581586 const uiSourceCodes = self.Workspace.workspace.uiSourceCodes();
Blink Reformat4c46d092018-04-07 15:32:371587 return uiSourceCodes.filter(filterOutService);
1588 };
1589
1590 /*
1591 * Evaluates the code in the console as if user typed it manually and invokes
1592 * the callback when the result message is received and added to the console.
1593 * @param {string} code
1594 * @param {function(string)} callback
1595 */
1596 TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
1597 function innerEvaluate() {
Paul Lewisd9907342020-01-24 13:49:471598 self.UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371599 const consoleView = Console.ConsoleView.instance();
Jan Scheffler9befd492021-08-12 13:44:261600 consoleView.prompt.appendCommand(code);
Blink Reformat4c46d092018-04-07 15:32:371601
Jan Scheffler9befd492021-08-12 13:44:261602 this.addSniffer(Console.ConsoleView.prototype, 'consoleMessageAddedForTest', function(viewMessage) {
Blink Reformat4c46d092018-04-07 15:32:371603 callback(viewMessage.toMessageElement().deepTextContent());
1604 }.bind(this));
1605 }
1606
1607 function showConsoleAndEvaluate() {
Simon Zünd5111ff42023-08-23 08:46:171608 Common.Console.Console.instance().showPromise().then(innerEvaluate.bind(this));
Blink Reformat4c46d092018-04-07 15:32:371609 }
1610
Paul Lewisd9907342020-01-24 13:49:471611 if (!self.UI.context.flavor(SDK.ExecutionContext)) {
1612 self.UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371613 return;
1614 }
1615 showConsoleAndEvaluate.call(this);
1616 };
1617
1618 /**
1619 * Checks that all expected scripts are present in the scripts list
1620 * in the Scripts panel.
1621 * @param {!Array.<string>} expected Regular expressions describing
1622 * expected script names.
1623 * @return {boolean} Whether all the scripts are in "scripts-files" select
1624 * box
1625 */
1626 TestSuite.prototype._scriptsAreParsed = function(expected) {
1627 const uiSourceCodes = this.nonAnonymousUISourceCodes_();
1628 // Check that at least all the expected scripts are present.
1629 const missing = expected.slice(0);
1630 for (let i = 0; i < uiSourceCodes.length; ++i) {
1631 for (let j = 0; j < missing.length; ++j) {
1632 if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
1633 missing.splice(j, 1);
1634 break;
1635 }
1636 }
1637 }
1638 return missing.length === 0;
1639 };
1640
1641 /**
1642 * Waits for script pause, checks expectations, and invokes the callback.
1643 * @param {function():void} callback
1644 */
1645 TestSuite.prototype._waitForScriptPause = function(callback) {
Jan Scheffler70f898c2021-08-06 09:40:021646 this.addSniffer(SDK.DebuggerModel.prototype, 'pausedScript', callback);
Blink Reformat4c46d092018-04-07 15:32:371647 };
1648
1649 /**
1650 * Waits until all the scripts are parsed and invokes the callback.
1651 */
1652 TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
1653 const test = this;
1654
1655 function waitForAllScripts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341656 if (test._scriptsAreParsed(expectedScripts)) {
Blink Reformat4c46d092018-04-07 15:32:371657 callback();
Tim van der Lippe1d6e57a2019-09-30 11:55:341658 } else {
Sigurd Schneider9e9a51c2021-08-19 12:02:241659 test.addSniffer(UI.panels.sources.sourcesView(), 'addUISourceCode', waitForAllScripts);
Tim van der Lippe1d6e57a2019-09-30 11:55:341660 }
Blink Reformat4c46d092018-04-07 15:32:371661 }
1662
1663 waitForAllScripts();
1664 };
1665
1666 TestSuite.prototype._waitForTargets = function(n, callback) {
1667 checkTargets.call(this);
1668
1669 function checkTargets() {
Paul Lewis4ae5f4f2020-01-23 10:19:331670 if (self.SDK.targetManager.targets().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371671 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341672 } else {
Blink Reformat4c46d092018-04-07 15:32:371673 this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341674 }
Blink Reformat4c46d092018-04-07 15:32:371675 }
1676 };
1677
1678 TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
Danil Somsikov494f09a2023-04-17 11:08:411679 const runtimeModel = self.SDK.targetManager.primaryPageTarget().model(SDK.RuntimeModel);
Blink Reformat4c46d092018-04-07 15:32:371680 checkForExecutionContexts.call(this);
1681
1682 function checkForExecutionContexts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341683 if (runtimeModel.executionContexts().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371684 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341685 } else {
Sigurd Schneider9e9a51c2021-08-19 12:02:241686 this.addSniffer(SDK.RuntimeModel.prototype, 'executionContextCreated', checkForExecutionContexts.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341687 }
Blink Reformat4c46d092018-04-07 15:32:371688 }
1689 };
1690
Blink Reformat4c46d092018-04-07 15:32:371691 window.uiTests = new TestSuite(window.domAutomationController);
1692})(window);