blob: e1f8fbc70f9eaf72060703e6ebb9ae521f6d8acd [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 */
Blink Reformat4c46d092018-04-07 15:32:3730
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
Sigurd Schneider72ac3562021-03-11 10:35:2534 * and are executed by the devtools_browsertest.cc as a part of the
Blink Reformat4c46d092018-04-07 15:32:3735 * Interactive UI Test suite.
36 * FIXME: change field naming style to use trailing underscore.
37 */
38
39(function createTestSuite(window) {
Simon Zünd5111ff42023-08-23 08:46:1740 // 'Tests.js' is loaded as a classic script so we can't use static imports for these modules.
41 /** @type {import('./core/common/common.js')} */
42 let Common;
Simon Zündb4f900e2023-08-23 09:45:5743 /** @type {import('./core/host/host.js')} */
44 let HostModule;
Simon Zünd182f0772023-08-29 10:47:5545 /** @type {import('./core/root/root.js')} */
46 let Root;
Simon Zünd1cf335c2023-08-23 12:16:5047 /** @type {import('./core/sdk/sdk.js')} */
48 let SDK;
Simon Zündeb6e27f2023-08-25 07:27:3449 /** @type {import('./panels/sources/sources.js')} */
50 let Sources;
51 /** @type {import('./panels/timeline/timeline.js')} */
52 let Timeline;
53 /** @type {import('./ui/legacy/legacy.js')} */
54 let UI;
Simon Zünddf37f272023-08-25 07:45:0455 /** @type {import('./models/workspace/workspace.js')} */
56 let Workspace;
Blink Reformat4c46d092018-04-07 15:32:3757 const TestSuite = class {
58 /**
59 * Test suite for interactive UI tests.
60 * @param {Object} domAutomationController DomAutomationController instance.
61 */
62 constructor(domAutomationController) {
63 this.domAutomationController_ = domAutomationController;
64 this.controlTaken_ = false;
65 this.timerId_ = -1;
66 this._asyncInvocationId = 0;
67 }
68
69 /**
70 * Key event with given key identifier.
71 */
72 static createKeyEvent(key) {
Paul Irish9657a012024-09-04 18:37:3773 return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key});
Blink Reformat4c46d092018-04-07 15:32:3774 }
75 };
76
77 /**
78 * Reports test failure.
79 * @param {string} message Failure description.
80 */
81 TestSuite.prototype.fail = function(message) {
Tim van der Lippe1d6e57a2019-09-30 11:55:3482 if (this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:3783 this.reportFailure_(message);
Tim van der Lippe1d6e57a2019-09-30 11:55:3484 } else {
Blink Reformat4c46d092018-04-07 15:32:3785 throw message;
Tim van der Lippe1d6e57a2019-09-30 11:55:3486 }
Blink Reformat4c46d092018-04-07 15:32:3787 };
88
89 /**
90 * Equals assertion tests that expected === actual.
91 * @param {!Object|boolean} expected Expected object.
92 * @param {!Object|boolean} actual Actual object.
93 * @param {string} opt_message User message to print if the test fails.
94 */
95 TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
96 if (expected !== actual) {
97 let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
Tim van der Lippe1d6e57a2019-09-30 11:55:3498 if (opt_message) {
Blink Reformat4c46d092018-04-07 15:32:3799 message = opt_message + '(' + message + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34100 }
Blink Reformat4c46d092018-04-07 15:32:37101 this.fail(message);
102 }
103 };
104
105 /**
106 * True assertion tests that value == true.
107 * @param {!Object} value Actual object.
108 * @param {string} opt_message User message to print if the test fails.
109 */
110 TestSuite.prototype.assertTrue = function(value, opt_message) {
Tim van der Lipped7cfd142021-01-07 12:17:24111 this.assertEquals(true, Boolean(value), opt_message);
Blink Reformat4c46d092018-04-07 15:32:37112 };
113
114 /**
115 * Takes control over execution.
Sigurd Schneider72ac3562021-03-11 10:35:25116 * @param {{slownessFactor:number}=} options
Blink Reformat4c46d092018-04-07 15:32:37117 */
Sigurd Schneider72ac3562021-03-11 10:35:25118 TestSuite.prototype.takeControl = function(options) {
119 const {slownessFactor} = {slownessFactor: 1, ...options};
Blink Reformat4c46d092018-04-07 15:32:37120 this.controlTaken_ = true;
121 // Set up guard timer.
122 const self = this;
Sigurd Schneider376d2712021-03-12 15:07:51123 const timeoutInSec = 20 * slownessFactor;
Blink Reformat4c46d092018-04-07 15:32:37124 this.timerId_ = setTimeout(function() {
Sigurd Schneider376d2712021-03-12 15:07:51125 self.reportFailure_(`Timeout exceeded: ${timeoutInSec} sec`);
126 }, timeoutInSec * 1000);
Blink Reformat4c46d092018-04-07 15:32:37127 };
128
129 /**
130 * Releases control over execution.
131 */
132 TestSuite.prototype.releaseControl = function() {
133 if (this.timerId_ !== -1) {
134 clearTimeout(this.timerId_);
135 this.timerId_ = -1;
136 }
137 this.controlTaken_ = false;
138 this.reportOk_();
139 };
140
141 /**
142 * Async tests use this one to report that they are completed.
143 */
144 TestSuite.prototype.reportOk_ = function() {
145 this.domAutomationController_.send('[OK]');
146 };
147
148 /**
149 * Async tests use this one to report failures.
150 */
151 TestSuite.prototype.reportFailure_ = function(error) {
152 if (this.timerId_ !== -1) {
153 clearTimeout(this.timerId_);
154 this.timerId_ = -1;
155 }
156 this.domAutomationController_.send('[FAILED] ' + error);
157 };
158
Tim van der Lippe7634cc12021-11-11 15:52:52159 TestSuite.prototype.setupLegacyFilesForTest = async function() {
Simon Zünd16c34412024-12-05 05:48:03160 // 'Tests.js' is executed on 'about:blank' so we can't use `import` directly without
161 // specifying the full devtools://devtools/bundled URL.
162 ([
163 Common,
164 HostModule,
165 Root,
166 SDK,
167 Sources,
168 Timeline,
169 UI,
170 Workspace,
171 ] =
172 await Promise.all([
173 self.runtime.loadLegacyModule('core/common/common.js'),
174 self.runtime.loadLegacyModule('core/host/host.js'),
175 self.runtime.loadLegacyModule('core/root/root.js'),
176 self.runtime.loadLegacyModule('core/sdk/sdk.js'),
177 self.runtime.loadLegacyModule('panels/sources/sources.js'),
178 self.runtime.loadLegacyModule('panels/timeline/timeline.js'),
179 self.runtime.loadLegacyModule('ui/legacy/legacy.js'),
180 self.runtime.loadLegacyModule('models/workspace/workspace.js'),
181 ]));
Simon Zündb4f900e2023-08-23 09:45:57182
Simon Zünd16c34412024-12-05 05:48:03183 // We have to map 'Host.InspectorFrontendHost' as the C++ uses it directly.
184 self.Host = {};
185 self.Host.InspectorFrontendHost = HostModule.InspectorFrontendHost.InspectorFrontendHostInstance;
186 self.Host.InspectorFrontendHostAPI = HostModule.InspectorFrontendHostAPI;
Tim van der Lippe7634cc12021-11-11 15:52:52187 };
188
Blink Reformat4c46d092018-04-07 15:32:37189 /**
190 * Run specified test on a fresh instance of the test suite.
191 * @param {Array<string>} args method name followed by its parameters.
192 */
Danil Somsikov266e53e2021-10-25 16:07:42193 TestSuite.prototype.dispatchOnTestSuite = async function(args) {
Blink Reformat4c46d092018-04-07 15:32:37194 const methodName = args.shift();
195 try {
Danil Somsikov266e53e2021-10-25 16:07:42196 await this[methodName].apply(this, args);
Tim van der Lippe1d6e57a2019-09-30 11:55:34197 if (!this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:37198 this.reportOk_();
Tim van der Lippe1d6e57a2019-09-30 11:55:34199 }
Blink Reformat4c46d092018-04-07 15:32:37200 } catch (e) {
201 this.reportFailure_(e);
202 }
203 };
204
205 /**
206 * Wrap an async method with TestSuite.{takeControl(), releaseControl()}
207 * and invoke TestSuite.reportOk_ upon completion.
208 * @param {Array<string>} args method name followed by its parameters.
209 */
210 TestSuite.prototype.waitForAsync = function(var_args) {
211 const args = Array.prototype.slice.call(arguments);
212 this.takeControl();
213 args.push(this.releaseControl.bind(this));
214 this.dispatchOnTestSuite(args);
215 };
216
217 /**
218 * Overrides the method with specified name until it's called first time.
219 * @param {!Object} receiver An object whose method to override.
220 * @param {string} methodName Name of the method to override.
221 * @param {!Function} override A function that should be called right after the
222 * overridden method returns.
223 * @param {?boolean} opt_sticky Whether restore original method after first run
224 * or not.
225 */
226 TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) {
227 const orig = receiver[methodName];
Tim van der Lippe1d6e57a2019-09-30 11:55:34228 if (typeof orig !== 'function') {
Blink Reformat4c46d092018-04-07 15:32:37229 this.fail('Cannot find method to override: ' + methodName);
Tim van der Lippe1d6e57a2019-09-30 11:55:34230 }
Blink Reformat4c46d092018-04-07 15:32:37231 const test = this;
232 receiver[methodName] = function(var_args) {
233 let result;
234 try {
235 result = orig.apply(this, arguments);
236 } finally {
Tim van der Lippe1d6e57a2019-09-30 11:55:34237 if (!opt_sticky) {
Blink Reformat4c46d092018-04-07 15:32:37238 receiver[methodName] = orig;
Tim van der Lippe1d6e57a2019-09-30 11:55:34239 }
Blink Reformat4c46d092018-04-07 15:32:37240 }
241 // In case of exception the override won't be called.
242 try {
243 override.apply(this, arguments);
244 } catch (e) {
245 test.fail('Exception in overriden method \'' + methodName + '\': ' + e);
246 }
247 return result;
248 };
249 };
250
251 /**
252 * Waits for current throttler invocations, if any.
253 * @param {!Common.Throttler} throttler
254 * @param {function()} callback
255 */
256 TestSuite.prototype.waitForThrottler = function(throttler, callback) {
257 const test = this;
258 let scheduleShouldFail = true;
259 test.addSniffer(throttler, 'schedule', onSchedule);
260
261 function hasSomethingScheduled() {
262 return throttler._isRunningProcess || throttler._process;
263 }
264
265 function checkState() {
266 if (!hasSomethingScheduled()) {
267 scheduleShouldFail = false;
268 callback();
269 return;
270 }
271
Sigurd Schneider9e9a51c2021-08-19 12:02:24272 test.addSniffer(throttler, 'processCompletedForTests', checkState);
Blink Reformat4c46d092018-04-07 15:32:37273 }
274
275 function onSchedule() {
Tim van der Lippe1d6e57a2019-09-30 11:55:34276 if (scheduleShouldFail) {
Blink Reformat4c46d092018-04-07 15:32:37277 test.fail('Unexpected Throttler.schedule');
Tim van der Lippe1d6e57a2019-09-30 11:55:34278 }
Blink Reformat4c46d092018-04-07 15:32:37279 }
280
281 checkState();
282 };
283
284 /**
285 * @param {string} panelName Name of the panel to show.
286 */
287 TestSuite.prototype.showPanel = function(panelName) {
Simon Zündeb6e27f2023-08-25 07:27:34288 return UI.InspectorView.InspectorView.instance().showPanel(panelName);
Blink Reformat4c46d092018-04-07 15:32:37289 };
290
291 // UI Tests
292
293 /**
294 * Tests that scripts tab can be open and populated with inspected scripts.
295 */
296 TestSuite.prototype.testShowScriptsTab = function() {
297 const test = this;
298 this.showPanel('sources').then(function() {
299 // There should be at least main page script.
300 this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
301 test.releaseControl();
302 });
303 }.bind(this));
304 // Wait until all scripts are added to the debugger.
305 this.takeControl();
306 };
307
308 /**
Alex Rudenkob6eac402023-08-10 07:41:53309 * Tests that Recorder tab can be open.
310 */
311 TestSuite.prototype.testShowRecorderTab = function() {
Danil Somsikov96f4b2f2024-01-19 12:52:08312 this.showPanel('chrome-recorder')
Alex Rudenkob6eac402023-08-10 07:41:53313 .then(() => {
314 this.releaseControl();
315 })
316 .catch(err => {
317 this.fail('Loading Recorder panel failed: ' + err.message);
318 });
319 this.takeControl();
320 };
321
322 /**
Blink Reformat4c46d092018-04-07 15:32:37323 * Tests that scripts list contains content scripts.
324 */
325 TestSuite.prototype.testContentScriptIsPresent = function() {
326 const test = this;
327 this.showPanel('sources').then(function() {
328 test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() {
329 test.releaseControl();
330 });
331 });
332
333 // Wait until all scripts are added to the debugger.
334 this.takeControl();
335 };
336
337 /**
338 * Tests that scripts are not duplicaed on Scripts tab switch.
339 */
340 TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() {
341 const test = this;
342
343 function switchToElementsTab() {
344 test.showPanel('elements').then(function() {
345 setTimeout(switchToScriptsTab, 0);
346 });
347 }
348
349 function switchToScriptsTab() {
350 test.showPanel('sources').then(function() {
351 setTimeout(checkScriptsPanel, 0);
352 });
353 }
354
355 function checkScriptsPanel() {
356 test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.');
357 checkNoDuplicates();
358 test.releaseControl();
359 }
360
361 function checkNoDuplicates() {
362 const uiSourceCodes = test.nonAnonymousUISourceCodes_();
363 for (let i = 0; i < uiSourceCodes.length; i++) {
364 for (let j = i + 1; j < uiSourceCodes.length; j++) {
365 test.assertTrue(
366 uiSourceCodes[i].url() !== uiSourceCodes[j].url(),
367 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes));
368 }
369 }
370 }
371
372 this.showPanel('sources').then(function() {
373 test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
374 checkNoDuplicates();
375 setTimeout(switchToElementsTab, 0);
376 });
377 });
378
379 // Wait until all scripts are added to the debugger.
Sigurd Schneiderd8d7e822021-03-16 09:34:19380 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37381 };
382
383 // Tests that debugger works correctly if pause event occurs when DevTools
384 // frontend is being loaded.
385 TestSuite.prototype.testPauseWhenLoadingDevTools = function() {
Simon Zünd1cf335c2023-08-23 12:16:50386 const debuggerModel =
387 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.model(SDK.DebuggerModel.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34388 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37389 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34390 }
Blink Reformat4c46d092018-04-07 15:32:37391
392 this.showPanel('sources').then(function() {
393 // Script execution can already be paused.
394
395 this._waitForScriptPause(this.releaseControl.bind(this));
396 }.bind(this));
397
398 this.takeControl();
399 };
400
Blink Reformat4c46d092018-04-07 15:32:37401 /**
402 * Tests network size.
403 */
404 TestSuite.prototype.testNetworkSize = function() {
405 const test = this;
406
407 function finishRequest(request, finishTime) {
408 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
409 test.releaseControl();
410 }
411
Simon Zünd1cf335c2023-08-23 12:16:50412 this.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37413
414 // Reload inspected page to sniff network events
415 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
416
Sigurd Schneiderd8d7e822021-03-16 09:34:19417 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37418 };
419
420 /**
421 * Tests network sync size.
422 */
423 TestSuite.prototype.testNetworkSyncSize = function() {
424 const test = this;
425
426 function finishRequest(request, finishTime) {
427 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
428 test.releaseControl();
429 }
430
Simon Zünd1cf335c2023-08-23 12:16:50431 this.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37432
433 // Send synchronous XHR to sniff network events
434 test.evaluateInConsole_(
435 'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {});
436
Sigurd Schneiderd8d7e822021-03-16 09:34:19437 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37438 };
439
440 /**
441 * Tests network raw headers text.
442 */
443 TestSuite.prototype.testNetworkRawHeadersText = function() {
444 const test = this;
445
446 function finishRequest(request, finishTime) {
Tim van der Lippe1d6e57a2019-09-30 11:55:34447 if (!request.responseHeadersText) {
Blink Reformat4c46d092018-04-07 15:32:37448 test.fail('Failure: resource does not have response headers text');
Tim van der Lippe1d6e57a2019-09-30 11:55:34449 }
Blink Reformat4c46d092018-04-07 15:32:37450 const index = request.responseHeadersText.indexOf('Date:');
451 test.assertEquals(
452 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length');
453 test.releaseControl();
454 }
455
Simon Zünd1cf335c2023-08-23 12:16:50456 this.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37457
458 // Reload inspected page to sniff network events
459 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
460
Sigurd Schneiderd8d7e822021-03-16 09:34:19461 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37462 };
463
464 /**
465 * Tests network timing.
466 */
467 TestSuite.prototype.testNetworkTiming = function() {
468 const test = this;
469
470 function finishRequest(request, finishTime) {
471 // Setting relaxed expectations to reduce flakiness.
472 // Server sends headers after 100ms, then sends data during another 100ms.
473 // We expect these times to be measured at least as 70ms.
474 test.assertTrue(
475 request.timing.receiveHeadersEnd - request.timing.connectStart >= 70,
476 'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' +
Jack Franklin408ed8a2023-07-07 11:05:56477 'receiveHeadersEnd=' + request.timing.receiveHeadersEnd +
478 ', connectStart=' + request.timing.connectStart + '.');
Blink Reformat4c46d092018-04-07 15:32:37479 test.assertTrue(
480 request.responseReceivedTime - request.startTime >= 0.07,
481 'Time between responseReceivedTime and startTime should be >=0.07s, but was ' +
482 'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.');
483 test.assertTrue(
484 request.endTime - request.startTime >= 0.14,
485 'Time between endTime and startTime should be >=0.14s, but was ' +
486 'endtime=' + request.endTime + ', startTime=' + request.startTime + '.');
487
488 test.releaseControl();
489 }
490
Simon Zünd1cf335c2023-08-23 12:16:50491 this.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37492
493 // Reload inspected page to sniff network events
494 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
495
Sigurd Schneiderd8d7e822021-03-16 09:34:19496 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37497 };
498
499 TestSuite.prototype.testPushTimes = function(url) {
500 const test = this;
501 let pendingRequestCount = 2;
502
503 function finishRequest(request, finishTime) {
504 test.assertTrue(
505 typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0,
506 `pushStart is invalid: ${request.timing.pushStart}`);
507 test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`);
508 test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime');
509 if (request.url().endsWith('?pushUseNullEndTime')) {
510 test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`);
511 } else {
512 test.assertTrue(
513 request.timing.pushStart < request.timing.pushEnd,
514 `pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`);
515 // The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant.
516 test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime');
517 test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime');
518 }
Tim van der Lippe1d6e57a2019-09-30 11:55:34519 if (!--pendingRequestCount) {
Blink Reformat4c46d092018-04-07 15:32:37520 test.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:34521 }
Blink Reformat4c46d092018-04-07 15:32:37522 }
523
Simon Zünd1cf335c2023-08-23 12:16:50524 this.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest, true);
Blink Reformat4c46d092018-04-07 15:32:37525
526 test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {});
527 test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {});
528 this.takeControl();
529 };
530
531 TestSuite.prototype.testConsoleOnNavigateBack = function() {
Blink Reformat4c46d092018-04-07 15:32:37532 function filteredMessages() {
Simon Zünd1cf335c2023-08-23 12:16:50533 return SDK.ConsoleModel.ConsoleModel.allMessagesUnordered().filter(
534 a => a.source !== Protocol.Log.LogEntrySource.Violation);
Blink Reformat4c46d092018-04-07 15:32:37535 }
536
Tim van der Lippe1d6e57a2019-09-30 11:55:34537 if (filteredMessages().length === 1) {
Blink Reformat4c46d092018-04-07 15:32:37538 firstConsoleMessageReceived.call(this, null);
Tim van der Lippe1d6e57a2019-09-30 11:55:34539 } else {
Simon Zünd1cf335c2023-08-23 12:16:50540 SDK.TargetManager.TargetManager.instance().addModelListener(
541 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Tim van der Lippe1d6e57a2019-09-30 11:55:34542 }
Blink Reformat4c46d092018-04-07 15:32:37543
Blink Reformat4c46d092018-04-07 15:32:37544 function firstConsoleMessageReceived(event) {
Tim van der Lippeeb876c62021-05-14 15:02:11545 if (event && event.data.source === Protocol.Log.LogEntrySource.Violation) {
Blink Reformat4c46d092018-04-07 15:32:37546 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34547 }
Simon Zünd1cf335c2023-08-23 12:16:50548 SDK.TargetManager.TargetManager.instance().removeModelListener(
549 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Blink Reformat4c46d092018-04-07 15:32:37550 this.evaluateInConsole_('clickLink();', didClickLink.bind(this));
551 }
552
553 function didClickLink() {
554 // Check that there are no new messages(command is not a message).
555 this.assertEquals(3, filteredMessages().length);
556 this.evaluateInConsole_('history.back();', didNavigateBack.bind(this));
557 }
558
559 function didNavigateBack() {
560 // Make sure navigation completed and possible console messages were pushed.
561 this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this));
562 }
563
564 function didCompleteNavigation() {
565 this.assertEquals(7, filteredMessages().length);
566 this.releaseControl();
567 }
568
569 this.takeControl();
570 };
571
572 TestSuite.prototype.testSharedWorker = function() {
573 function didEvaluateInConsole(resultText) {
574 this.assertEquals('2011', resultText);
575 this.releaseControl();
576 }
577 this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this));
578 this.takeControl();
579 };
580
581 TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() {
582 // Make sure the worker is loaded.
583 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00584 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37585
586 function callback() {
Simon Zündb6414c92020-03-19 07:16:40587 ProtocolClient.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37588 }
589 };
590
591 TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() {
592 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00593 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37594
595 function callback() {
Simon Zünd1cf335c2023-08-23 12:16:50596 const debuggerModel = SDK.TargetManager.TargetManager.instance().models(SDK.DebuggerModel.DebuggerModel)[0];
Blink Reformat4c46d092018-04-07 15:32:37597 if (debuggerModel.isPaused()) {
Simon Zünd1cf335c2023-08-23 12:16:50598 SDK.TargetManager.TargetManager.instance().addModelListener(
599 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31600 debuggerModel.resume();
Blink Reformat4c46d092018-04-07 15:32:37601 return;
602 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31603 this._waitForScriptPause(callback.bind(this));
604 }
605
606 function onConsoleMessage(event) {
607 const message = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:34608 if (message !== 'connected') {
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31609 this.fail('Unexpected message: ' + message);
Tim van der Lippe1d6e57a2019-09-30 11:55:34610 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31611 this.releaseControl();
Blink Reformat4c46d092018-04-07 15:32:37612 }
613 };
614
Joey Arhar0585e6f2018-10-30 23:11:18615 TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
616 this.takeControl();
617 this.showPanel('network').then(() => {
Tim van der Lippe1d6e57a2019-09-30 11:55:34618 if (!document.querySelector('#network-container')) {
Joey Arhar0585e6f2018-10-30 23:11:18619 this.fail('unable to find #network-container');
Tim van der Lippe1d6e57a2019-09-30 11:55:34620 }
Joey Arhar0585e6f2018-10-30 23:11:18621 this.releaseControl();
622 });
623 };
624
Blink Reformat4c46d092018-04-07 15:32:37625 TestSuite.prototype.enableTouchEmulation = function() {
626 const deviceModeModel = new Emulation.DeviceModeModel(function() {});
Simon Zünd1cf335c2023-08-23 12:16:50627 deviceModeModel._target = SDK.TargetManager.TargetManager.instance().primaryPageTarget();
Blink Reformat4c46d092018-04-07 15:32:37628 deviceModeModel._applyTouch(true, true);
629 };
630
631 TestSuite.prototype.waitForDebuggerPaused = function() {
Simon Zünd1cf335c2023-08-23 12:16:50632 const debuggerModel =
633 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.model(SDK.DebuggerModel.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34634 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37635 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34636 }
Blink Reformat4c46d092018-04-07 15:32:37637
638 this.takeControl();
639 this._waitForScriptPause(this.releaseControl.bind(this));
640 };
641
642 TestSuite.prototype.switchToPanel = function(panelName) {
643 this.showPanel(panelName).then(this.releaseControl.bind(this));
644 this.takeControl();
645 };
646
647 // Regression test for crbug.com/370035.
648 TestSuite.prototype.testDeviceMetricsOverrides = function() {
649 function dumpPageMetrics() {
650 return JSON.stringify(
651 {width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
652 }
653
654 const test = this;
655
656 async function testOverrides(params, metrics, callback) {
Simon Zünd1cf335c2023-08-23 12:16:50657 await SDK.TargetManager.TargetManager.instance()
658 .primaryPageTarget()
659 ?.emulationAgent()
660 .invoke_setDeviceMetricsOverride(params);
Blink Reformat4c46d092018-04-07 15:32:37661 test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics);
662
663 function checkMetrics(consoleResult) {
664 test.assertEquals(
Johan Bay9ea04a82021-06-22 09:20:15665 `'${JSON.stringify(metrics)}'`, consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params));
Blink Reformat4c46d092018-04-07 15:32:37666 callback();
667 }
668 }
669
670 function step1() {
671 testOverrides(
672 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
673 {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
674 }
675
676 function step2() {
677 testOverrides(
678 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
679 {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
680 }
681
682 function step3() {
683 testOverrides(
684 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
685 {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
686 }
687
688 function step4() {
689 testOverrides(
690 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
691 {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
692 }
693
694 function finish() {
695 test.releaseControl();
696 }
697
698 test.takeControl();
699 step1();
700 };
701
702 TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
703 const test = this;
704 let receivedReady = false;
705
706 function signalToShowAutofill() {
Simon Zünd1cf335c2023-08-23 12:16:50707 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37708 {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Simon Zünd1cf335c2023-08-23 12:16:50709 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37710 {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
711 }
712
713 function selectTopAutoFill() {
Simon Zünd1cf335c2023-08-23 12:16:50714 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37715 {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
Simon Zünd1cf335c2023-08-23 12:16:50716 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37717 {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
718
719 test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
720 }
721
722 function onResultOfInput(value) {
Johan Bay9ea04a82021-06-22 09:20:15723 // Console adds '' around the response.
724 test.assertEquals('\'Abbf\'', value);
Blink Reformat4c46d092018-04-07 15:32:37725 test.releaseControl();
726 }
727
728 function onConsoleMessage(event) {
729 const message = event.data.messageText;
730 if (message === 'ready' && !receivedReady) {
731 receivedReady = true;
732 signalToShowAutofill();
733 }
734 // This log comes from the browser unittest code.
Tim van der Lippe1d6e57a2019-09-30 11:55:34735 if (message === 'didShowSuggestions') {
Blink Reformat4c46d092018-04-07 15:32:37736 selectTopAutoFill();
Tim van der Lippe1d6e57a2019-09-30 11:55:34737 }
Blink Reformat4c46d092018-04-07 15:32:37738 }
739
Sigurd Schneider5cfca2e2021-03-22 12:09:28740 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37741
742 // It is possible for the ready console messagage to be already received but not handled
743 // or received later. This ensures we can catch both cases.
Simon Zünd1cf335c2023-08-23 12:16:50744 SDK.TargetManager.TargetManager.instance().addModelListener(
745 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37746
Simon Zünd1cf335c2023-08-23 12:16:50747 const messages = SDK.ConsoleModel.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:37748 if (messages.length) {
749 const text = messages[0].messageText;
750 this.assertEquals('ready', text);
751 signalToShowAutofill();
752 }
753 };
754
Pâris MEULEMANd4709cb2019-04-17 08:32:48755 TestSuite.prototype.testKeyEventUnhandled = function() {
756 function onKeyEventUnhandledKeyDown(event) {
757 this.assertEquals('keydown', event.data.type);
758 this.assertEquals('F8', event.data.key);
759 this.assertEquals(119, event.data.keyCode);
760 this.assertEquals(0, event.data.modifiers);
761 this.assertEquals('', event.data.code);
Tim van der Lippe50cfa9b2019-10-01 10:40:58762 Host.InspectorFrontendHost.events.removeEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44763 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Tim van der Lippe50cfa9b2019-10-01 10:40:58764 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44765 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
Simon Zünd1cf335c2023-08-23 12:16:50766 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48767 {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
768 }
769 function onKeyEventUnhandledKeyUp(event) {
770 this.assertEquals('keyup', event.data.type);
771 this.assertEquals('F8', event.data.key);
772 this.assertEquals(119, event.data.keyCode);
773 this.assertEquals(0, event.data.modifiers);
774 this.assertEquals('F8', event.data.code);
775 this.releaseControl();
776 }
777 this.takeControl();
Tim van der Lippe50cfa9b2019-10-01 10:40:58778 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44779 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Simon Zünd1cf335c2023-08-23 12:16:50780 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48781 {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
782 };
783
Jack Lynchb514f9f2020-06-19 21:16:45784 // Tests that the keys that are forwarded from the browser update
785 // when their shortcuts change
786 TestSuite.prototype.testForwardedKeysChanged = function() {
Jack Lynch080a0fd2020-06-15 19:55:19787 this.takeControl();
788
Simon Zündeb6e27f2023-08-25 07:27:34789 this.addSniffer(UI.ShortcutRegistry.ShortcutRegistry.instance(), 'registerBindings', () => {
Simon Zünd1cf335c2023-08-23 12:16:50790 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Jack Lynch080a0fd2020-06-15 19:55:19791 {type: 'rawKeyDown', key: 'F1', windowsVirtualKeyCode: 112, nativeVirtualKeyCode: 112});
792 });
Simon Zündeb6e27f2023-08-25 07:27:34793 this.addSniffer(UI.ShortcutRegistry.ShortcutRegistry.instance(), 'handleKey', key => {
Jack Lynch080a0fd2020-06-15 19:55:19794 this.assertEquals(112, key);
795 this.releaseControl();
796 });
797
Danil Somsikova0619ba2024-01-30 06:12:52798 Common.Settings.moduleSetting('active-keybind-set').set('vsCode');
Jack Lynch080a0fd2020-06-15 19:55:19799 };
800
Blink Reformat4c46d092018-04-07 15:32:37801 TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
Simon Zünd1cf335c2023-08-23 12:16:50802 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37803 {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
Simon Zünd1cf335c2023-08-23 12:16:50804 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37805 {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
806 };
807
Pâris MEULEMANd81f35f2019-05-07 09:04:34808 // Check that showing the certificate viewer does not crash, crbug.com/954874
809 TestSuite.prototype.testShowCertificate = function() {
Tim van der Lippe50cfa9b2019-10-01 10:40:58810 Host.InspectorFrontendHost.showCertificateViewer([
Pâris MEULEMANd81f35f2019-05-07 09:04:34811 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
812 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
813 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
814 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
815 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
816 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
817 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
818 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
819 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
820 'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
821 'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
822 'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOcIA7AVR/Ck22Uj8X' +
823 'UOECercjUrKdDyaAPcLp2TThAgMBAAGjggHZMIIB1TATBgNVHSUEDDAKBggr' +
824 'BgEFBQcDATCBrwYDVR0RBIGnMIGkgg0qLmFwcHNwb3QuY29tggsqLmEucnVu' +
825 'LmFwcIIVKi50aGlua3dpdGhnb29nbGUuY29tghAqLndpdGhnb29nbGUuY29t' +
826 'ghEqLndpdGh5b3V0dWJlLmNvbYILYXBwc3BvdC5jb22CB3J1bi5hcHCCE3Ro' +
827 'aW5rd2l0aGdvb2dsZS5jb22CDndpdGhnb29nbGUuY29tgg93aXRoeW91dHVi' +
828 'ZS5jb20waAYIKwYBBQUHAQEEXDBaMC0GCCsGAQUFBzAChiFodHRwOi8vcGtp' +
829 'Lmdvb2cvZ3NyMi9HVFNHSUFHMy5jcnQwKQYIKwYBBQUHMAGGHWh0dHA6Ly9v' +
830 'Y3NwLnBraS5nb29nL0dUU0dJQUczMB0GA1UdDgQWBBTGkpE5o0H9+Wjc05rF' +
831 'hNQiYDjBFjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFHfCuFCaZ3Z2sS3C' +
832 'htCDoH6mfrpLMCEGA1UdIAQaMBgwDAYKKwYBBAHWeQIFAzAIBgZngQwBAgIw' +
833 'MQYDVR0fBCowKDAmoCSgIoYgaHR0cDovL2NybC5wa2kuZ29vZy9HVFNHSUFH' +
834 'My5jcmwwDQYJKoZIhvcNAQELBQADggEBALqoYGqWtJW/6obEzY+ehsgfyXb+' +
835 'qNIuV09wt95cRF93HlLbBlSZ/Iz8HXX44ZT1/tGAkwKnW0gDKSSab3I8U+e9' +
836 'LHbC9VXrgAFENzu89MNKNmK5prwv+MPA2HUQPu4Pad3qXmd4+nKc/EUjtg1d' +
837 '/xKGK1Vn6JX3i5ly/rduowez3LxpSAJuIwseum331aQaKC2z2ri++96B8MPU' +
838 'KFXzvV2gVGOe3ZYqmwPaG8y38Tba+OzEh59ygl8ydJJhoI6+R3itPSy0aXUU' +
839 'lMvvAbfCobXD5kBRQ28ysgbDSDOPs3fraXpAKL92QUjsABs58XBz5vka4swu' +
840 'gg/u+ZxaKOqfIm8=',
841 'MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBM' +
842 'MSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMK' +
843 'R2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAw' +
844 'NDJaFw0yMTEyMTUwMDAwNDJaMFQxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVH' +
845 'b29nbGUgVHJ1c3QgU2VydmljZXMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5l' +
846 'dCBBdXRob3JpdHkgRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB' +
847 'AQDKUkvqHv/OJGuo2nIYaNVWXQ5IWi01CXZaz6TIHLGp/lOJ+600/4hbn7vn' +
848 '6AAB3DVzdQOts7G5pH0rJnnOFUAK71G4nzKMfHCGUksW/mona+Y2emJQ2N+a' +
849 'icwJKetPKRSIgAuPOB6Aahh8Hb2XO3h9RUk2T0HNouB2VzxoMXlkyW7XUR5m' +
850 'w6JkLHnA52XDVoRTWkNty5oCINLvGmnRsJ1zouAqYGVQMc/7sy+/EYhALrVJ' +
851 'EA8KbtyX+r8snwU5C1hUrwaW6MWOARa8qBpNQcWTkaIeoYvy/sGIJEmjR0vF' +
852 'EwHdp1cSaWIr6/4g72n7OqXwfinu7ZYW97EfoOSQJeAzAgMBAAGjggEzMIIB' +
853 'LzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF' +
854 'BwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFHfCuFCaZ3Z2sS3C' +
855 'htCDoH6mfrpLMB8GA1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUG' +
856 'CCsGAQUFBwEBBCkwJzAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdv' +
857 'b2cvZ3NyMjAyBgNVHR8EKzApMCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29n' +
858 'L2dzcjIvZ3NyMi5jcmwwPwYDVR0gBDgwNjA0BgZngQwBAgIwKjAoBggrBgEF' +
859 'BQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9yZXBvc2l0b3J5LzANBgkqhkiG9w0B' +
860 'AQsFAAOCAQEAHLeJluRT7bvs26gyAZ8so81trUISd7O45skDUmAge1cnxhG1' +
861 'P2cNmSxbWsoiCt2eux9LSD+PAj2LIYRFHW31/6xoic1k4tbWXkDCjir37xTT' +
862 'NqRAMPUyFRWSdvt+nlPqwnb8Oa2I/maSJukcxDjNSfpDh/Bd1lZNgdd/8cLd' +
863 'sE3+wypufJ9uXO1iQpnh9zbuFIwsIONGl1p3A8CgxkqI/UAih3JaGOqcpcda' +
864 'CIzkBaR9uYQ1X4k2Vg5APRLouzVy7a8IVk6wuy6pm+T7HT4LY8ibS5FEZlfA' +
865 'FLSW8NwsVz9SBK2Vqn1N0PIMn5xA6NZVc7o835DLAFshEWfC7TIe3g==',
866 'MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEg' +
867 'MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkds' +
868 'b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAw' +
869 'WhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg' +
870 'Q0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs' +
871 'U2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o' +
872 'mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe' +
873 '+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1' +
874 'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
875 'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
876 '4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
877 'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
878 'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
879 'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
880 'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
881 'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
882 'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
883 'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
884 'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
885 '9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
886 'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
887 '/H5COEBkEveegeGTLg=='
888 ]);
889 };
890
Paul Lewise407fce2021-02-26 09:59:31891 // Simple check to make sure network throttling is wired up
Blink Reformat4c46d092018-04-07 15:32:37892 // See crbug.com/747724
893 TestSuite.prototype.testOfflineNetworkConditions = async function() {
894 const test = this;
Simon Zünd1cf335c2023-08-23 12:16:50895 SDK.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Blink Reformat4c46d092018-04-07 15:32:37896
897 function finishRequest(request) {
898 test.assertEquals(
899 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
900 test.releaseControl();
901 }
902
Simon Zünd1cf335c2023-08-23 12:16:50903 this.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
Blink Reformat4c46d092018-04-07 15:32:37904
Danil Somsikovf9a63312021-10-01 13:21:08905 test.takeControl();
906 test.evaluateInConsole_('await fetch("/");', function(resultText) {});
Blink Reformat4c46d092018-04-07 15:32:37907 };
908
909 TestSuite.prototype.testEmulateNetworkConditions = function() {
910 const test = this;
911
912 function testPreset(preset, messages, next) {
913 function onConsoleMessage(event) {
914 const index = messages.indexOf(event.data.messageText);
915 if (index === -1) {
916 test.fail('Unexpected message: ' + event.data.messageText);
917 return;
918 }
919
920 messages.splice(index, 1);
921 if (!messages.length) {
Simon Zünd1cf335c2023-08-23 12:16:50922 SDK.TargetManager.TargetManager.instance().removeModelListener(
923 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37924 next();
925 }
926 }
927
Simon Zünd1cf335c2023-08-23 12:16:50928 SDK.TargetManager.TargetManager.instance().addModelListener(
929 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
930 SDK.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(preset);
Blink Reformat4c46d092018-04-07 15:32:37931 }
932
933 test.takeControl();
934 step1();
935
936 function step1() {
937 testPreset(
Jack Franklin30608212024-06-03 12:42:39938 MobileThrottling.networkPresets[3],
Blink Reformat4c46d092018-04-07 15:32:37939 [
940 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
941 ],
942 step2);
943 }
944
945 function step2() {
946 testPreset(
Jack Franklin30608212024-06-03 12:42:39947 MobileThrottling.networkPresets[2],
Blink Reformat4c46d092018-04-07 15:32:37948 [
949 'online event: online = true',
Wolfgang Beyerd451ecd2020-10-23 08:35:54950 'connection change event: type = cellular; downlinkMax = 0.3814697265625; effectiveType = 2g'
Blink Reformat4c46d092018-04-07 15:32:37951 ],
952 step3);
953 }
954
955 function step3() {
956 testPreset(
Jack Franklin30608212024-06-03 12:42:39957 MobileThrottling.networkPresets[1],
958 ['connection change event: type = cellular; downlinkMax = 1.373291015625; effectiveType = 3g'], step4);
959 }
960
961 function step4() {
962 testPreset(
Blink Reformat4c46d092018-04-07 15:32:37963 MobileThrottling.networkPresets[0],
Jack Franklin30608212024-06-03 12:42:39964 ['connection change event: type = cellular; downlinkMax = 7.724761962890625; effectiveType = 4g'],
Blink Reformat4c46d092018-04-07 15:32:37965 test.releaseControl.bind(test));
966 }
967 };
968
969 TestSuite.prototype.testScreenshotRecording = function() {
970 const test = this;
971
972 function performActionsInPage(callback) {
973 let count = 0;
974 const div = document.createElement('div');
975 div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
976 document.body.appendChild(div);
977 requestAnimationFrame(frame);
978 function frame() {
979 const color = [0, 0, 0];
980 color[count % 3] = 255;
981 div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34982 if (++count > 10) {
Blink Reformat4c46d092018-04-07 15:32:37983 requestAnimationFrame(callback);
Tim van der Lippe1d6e57a2019-09-30 11:55:34984 } else {
Blink Reformat4c46d092018-04-07 15:32:37985 requestAnimationFrame(frame);
Tim van der Lippe1d6e57a2019-09-30 11:55:34986 }
Blink Reformat4c46d092018-04-07 15:32:37987 }
988 }
989
Simon Zünd5111ff42023-08-23 08:46:17990 const captureFilmStripSetting =
Danil Somsikov97f3b412024-02-01 10:50:07991 Common.Settings.Settings.instance().createSetting('timeline-capture-film-strip', false);
Blink Reformat4c46d092018-04-07 15:32:37992 captureFilmStripSetting.set(true);
993 test.evaluateInConsole_(performActionsInPage.toString(), function() {});
994 test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
995
996 function onTimelineDone() {
997 captureFilmStripSetting.set(false);
Simon Zündeb6e27f2023-08-25 07:27:34998 const filmStripModel = Timeline.TimelinePanel.TimelinePanel.instance().performanceModel?.filmStripModel();
Blink Reformat4c46d092018-04-07 15:32:37999 const frames = filmStripModel.frames();
1000 test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
1001 loadFrameImages(frames);
1002 }
1003
1004 function loadFrameImages(frames) {
1005 const readyImages = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341006 for (const frame of frames) {
Blink Reformat4c46d092018-04-07 15:32:371007 frame.imageDataPromise().then(onGotImageData);
Tim van der Lippe1d6e57a2019-09-30 11:55:341008 }
Blink Reformat4c46d092018-04-07 15:32:371009
Paul Irish0e464322024-01-16 18:57:291010 function onGotImageData(dataUri) {
Blink Reformat4c46d092018-04-07 15:32:371011 const image = new Image();
Paul Irish0e464322024-01-16 18:57:291012 test.assertTrue(Boolean(dataUri), 'No image data for frame');
Blink Reformat4c46d092018-04-07 15:32:371013 image.addEventListener('load', onLoad);
Paul Irish0e464322024-01-16 18:57:291014 image.src = dataUri;
Blink Reformat4c46d092018-04-07 15:32:371015 }
1016
1017 function onLoad(event) {
1018 readyImages.push(event.target);
Tim van der Lippe1d6e57a2019-09-30 11:55:341019 if (readyImages.length === frames.length) {
Blink Reformat4c46d092018-04-07 15:32:371020 validateImagesAndCompleteTest(readyImages);
Tim van der Lippe1d6e57a2019-09-30 11:55:341021 }
Blink Reformat4c46d092018-04-07 15:32:371022 }
1023 }
1024
1025 function validateImagesAndCompleteTest(images) {
1026 let redCount = 0;
1027 let greenCount = 0;
1028 let blueCount = 0;
1029
1030 const canvas = document.createElement('canvas');
1031 const ctx = canvas.getContext('2d');
1032 for (const image of images) {
1033 test.assertTrue(image.naturalWidth > 10);
1034 test.assertTrue(image.naturalHeight > 10);
1035 canvas.width = image.naturalWidth;
1036 canvas.height = image.naturalHeight;
1037 ctx.drawImage(image, 0, 0);
1038 const data = ctx.getImageData(0, 0, 1, 1);
1039 const color = Array.prototype.join.call(data.data, ',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341040 if (data.data[0] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371041 redCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341042 } else if (data.data[1] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371043 greenCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341044 } else if (data.data[2] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371045 blueCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341046 } else {
Blink Reformat4c46d092018-04-07 15:32:371047 test.fail('Unexpected color: ' + color);
Tim van der Lippe1d6e57a2019-09-30 11:55:341048 }
Blink Reformat4c46d092018-04-07 15:32:371049 }
Paul Lewise407fce2021-02-26 09:59:311050 test.assertTrue(redCount && greenCount && blueCount, 'Color check failed');
Blink Reformat4c46d092018-04-07 15:32:371051 test.releaseControl();
1052 }
1053
1054 test.takeControl();
1055 };
1056
1057 TestSuite.prototype.testSettings = function() {
1058 const test = this;
1059
1060 createSettings();
1061 test.takeControl();
1062 setTimeout(reset, 0);
1063
1064 function createSettings() {
Simon Zünd5111ff42023-08-23 08:46:171065 const localSetting = Common.Settings.Settings.instance().createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371066 localSetting.set({s: 'local', n: 1});
Simon Zünd5111ff42023-08-23 08:46:171067 const globalSetting = Common.Settings.Settings.instance().createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371068 globalSetting.set({s: 'global', n: 2});
1069 }
1070
1071 function reset() {
Tim van der Lippe99e59b82019-09-30 20:00:591072 Root.Runtime.experiments.clearForTest();
Tim van der Lippe50cfa9b2019-10-01 10:40:581073 Host.InspectorFrontendHost.getPreferences(gotPreferences);
Blink Reformat4c46d092018-04-07 15:32:371074 }
1075
1076 function gotPreferences(prefs) {
Jan Schefflerd5bf8792021-08-07 15:09:581077 Main.Main.instanceForTest.createSettings(prefs);
Blink Reformat4c46d092018-04-07 15:32:371078
Simon Zünd5111ff42023-08-23 08:46:171079 const localSetting = Common.Settings.Settings.instance().createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371080 test.assertEquals('object', typeof localSetting.get());
1081 test.assertEquals('local', localSetting.get().s);
1082 test.assertEquals(1, localSetting.get().n);
Simon Zünd5111ff42023-08-23 08:46:171083 const globalSetting = Common.Settings.Settings.instance().createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371084 test.assertEquals('object', typeof globalSetting.get());
1085 test.assertEquals('global', globalSetting.get().s);
1086 test.assertEquals(2, globalSetting.get().n);
1087 test.releaseControl();
1088 }
1089 };
1090
1091 TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
1092 const test = this;
1093 test.takeControl();
Simon Zünd1cf335c2023-08-23 12:16:501094 const messages = SDK.ConsoleModel.ConsoleModel.allMessagesUnordered();
Tim van der Lippe1d6e57a2019-09-30 11:55:341095 if (messages.length === 1) {
Blink Reformat4c46d092018-04-07 15:32:371096 checkMessages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341097 } else {
Simon Zünd1cf335c2023-08-23 12:16:501098 SDK.TargetManager.TargetManager.instance().addModelListener(
1099 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
Tim van der Lippe1d6e57a2019-09-30 11:55:341100 }
Blink Reformat4c46d092018-04-07 15:32:371101
1102 function checkMessages() {
Simon Zünd1cf335c2023-08-23 12:16:501103 const messages = SDK.ConsoleModel.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:371104 test.assertEquals(1, messages.length);
1105 test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
1106 test.releaseControl();
1107 }
1108 };
1109
1110 TestSuite.prototype.testConsoleContextNames = function() {
1111 const test = this;
1112 test.takeControl();
1113 this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
1114
1115 function onExecutionContexts() {
1116 const consoleView = Console.ConsoleView.instance();
Jan Scheffler9befd492021-08-12 13:44:261117 const selector = consoleView.consoleContextSelector;
Blink Reformat4c46d092018-04-07 15:32:371118 const values = [];
Jan Scheffler9befd492021-08-12 13:44:261119 for (const item of selector.items) {
Blink Reformat4c46d092018-04-07 15:32:371120 values.push(selector.titleFor(item));
Tim van der Lippe1d6e57a2019-09-30 11:55:341121 }
Blink Reformat4c46d092018-04-07 15:32:371122 test.assertEquals('top', values[0]);
1123 test.assertEquals('Simple content script', values[1]);
1124 test.releaseControl();
1125 }
1126 };
1127
1128 TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
1129 const test = this;
Sigurd Schneider5cfca2e2021-03-22 12:09:281130 test.takeControl({slownessFactor: 10});
Simon Zünd1cf335c2023-08-23 12:16:501131 SDK.TargetManager.TargetManager.instance().addModelListener(
1132 SDK.NetworkManager.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
Blink Reformat4c46d092018-04-07 15:32:371133
sbingler18b2d022025-01-17 21:51:151134 this.evaluateInConsole_(`location.href= "${url}";`, () => {});
Blink Reformat4c46d092018-04-07 15:32:371135
1136 let count = 0;
1137 function onResponseReceived(event) {
Songtao Xia1e692682020-06-19 13:56:391138 const networkRequest = event.data.request;
Tim van der Lippe1d6e57a2019-09-30 11:55:341139 if (!networkRequest.url().startsWith('http')) {
Blink Reformat4c46d092018-04-07 15:32:371140 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341141 }
Blink Reformat4c46d092018-04-07 15:32:371142 switch (++count) {
1143 case 1: // Original redirect
1144 test.assertEquals(301, networkRequest.statusCode);
1145 test.assertEquals('Moved Permanently', networkRequest.statusText);
1146 test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
1147 break;
1148
1149 case 2: // HSTS internal redirect
1150 test.assertTrue(networkRequest.url().startsWith('http://'));
Blink Reformat4c46d092018-04-07 15:32:371151 test.assertEquals(307, networkRequest.statusCode);
1152 test.assertEquals('Internal Redirect', networkRequest.statusText);
1153 test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
1154 test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
1155 break;
1156
1157 case 3: // Final response
1158 test.assertTrue(networkRequest.url().startsWith('https://'));
1159 test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
1160 test.assertEquals(200, networkRequest.statusCode);
1161 test.assertEquals('OK', networkRequest.statusText);
1162 test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
1163 test.releaseControl();
1164 }
1165 }
1166 };
1167
1168 TestSuite.prototype.testDOMWarnings = function() {
Simon Zünd1cf335c2023-08-23 12:16:501169 const messages = SDK.ConsoleModel.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:371170 this.assertEquals(1, messages.length);
1171 const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
1172 this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
1173 };
1174
1175 TestSuite.prototype.waitForTestResultsInConsole = function() {
Simon Zünd1cf335c2023-08-23 12:16:501176 const messages = SDK.ConsoleModel.ConsoleModel.allMessagesUnordered();
Blink Reformat4c46d092018-04-07 15:32:371177 for (let i = 0; i < messages.length; ++i) {
1178 const text = messages[i].messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341179 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371180 return;
Mathias Bynensf06e8c02020-02-28 13:58:281181 }
1182 if (/^FAIL/.test(text)) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341183 this.fail(text);
1184 } // This will throw.
Blink Reformat4c46d092018-04-07 15:32:371185 }
1186 // Neither PASS nor FAIL, so wait for more messages.
1187 function onConsoleMessage(event) {
1188 const text = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341189 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371190 this.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:341191 } else if (/^FAIL/.test(text)) {
Blink Reformat4c46d092018-04-07 15:32:371192 this.fail(text);
Tim van der Lippe1d6e57a2019-09-30 11:55:341193 }
Blink Reformat4c46d092018-04-07 15:32:371194 }
1195
Simon Zünd1cf335c2023-08-23 12:16:501196 SDK.TargetManager.TargetManager.instance().addModelListener(
1197 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Sigurd Schneiderbf7f1602021-03-18 07:51:571198 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:371199 };
1200
Andrey Kosyakova08cb9b2020-04-01 21:49:521201 TestSuite.prototype.waitForTestResultsAsMessage = function() {
1202 const onMessage = event => {
1203 if (!event.data.testOutput) {
1204 return;
1205 }
1206 top.removeEventListener('message', onMessage);
1207 const text = event.data.testOutput;
1208 if (text === 'PASS') {
1209 this.releaseControl();
1210 } else {
1211 this.fail(text);
1212 }
1213 };
1214 top.addEventListener('message', onMessage);
1215 this.takeControl();
1216 };
1217
Blink Reformat4c46d092018-04-07 15:32:371218 TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
1219 const original = receiver[methodName];
1220 if (typeof original !== 'function') {
Mathias Bynens23ee1aa2020-03-02 12:06:381221 this.fail(`TestSuite._overrideMethod: ${methodName} is not a function`);
Blink Reformat4c46d092018-04-07 15:32:371222 return;
1223 }
1224 receiver[methodName] = function() {
1225 let value;
1226 try {
1227 value = original.apply(receiver, arguments);
1228 } finally {
1229 receiver[methodName] = original;
1230 }
1231 override.apply(original, arguments);
1232 return value;
1233 };
1234 };
1235
1236 TestSuite.prototype.startTimeline = function(callback) {
1237 const test = this;
1238 this.showPanel('timeline').then(function() {
Simon Zündeb6e27f2023-08-25 07:27:341239 const timeline = Timeline.TimelinePanel.TimelinePanel.instance();
Sigurd Schneider5c917812021-08-16 07:42:131240 test._overrideMethod(timeline, 'recordingStarted', callback);
Blink Reformat4c46d092018-04-07 15:32:371241 timeline._toggleRecording();
1242 });
1243 };
1244
1245 TestSuite.prototype.stopTimeline = function(callback) {
Simon Zündeb6e27f2023-08-25 07:27:341246 const timeline = Timeline.TimelinePanel.TimelinePanel.instance();
Blink Reformat4c46d092018-04-07 15:32:371247 this._overrideMethod(timeline, 'loadingComplete', callback);
1248 timeline._toggleRecording();
1249 };
1250
1251 TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
1252 const callback = arguments[arguments.length - 1];
1253 const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
1254 const argsString = arguments.length < 3 ?
1255 '' :
1256 Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
1257 this.evaluateInConsole_(
1258 `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
Simon Zünd1cf335c2023-08-23 12:16:501259 SDK.TargetManager.TargetManager.instance().addModelListener(
1260 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371261
1262 function onConsoleMessage(event) {
1263 const text = event.data.messageText;
1264 if (text === doneMessage) {
Simon Zünd1cf335c2023-08-23 12:16:501265 SDK.TargetManager.TargetManager.instance().removeModelListener(
1266 SDK.ConsoleModel.ConsoleModel, SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371267 callback();
1268 }
1269 }
1270 };
1271
1272 TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
1273 const test = this;
1274
1275 this.startTimeline(onRecordingStarted);
1276
1277 function onRecordingStarted() {
1278 test.invokePageFunctionAsync(functionName, pageActionsDone);
1279 }
1280
1281 function pageActionsDone() {
1282 test.stopTimeline(callback);
1283 }
1284 };
1285
1286 TestSuite.prototype.enableExperiment = function(name) {
Tim van der Lippe99e59b82019-09-30 20:00:591287 Root.Runtime.experiments.enableForTest(name);
Blink Reformat4c46d092018-04-07 15:32:371288 };
1289
Blink Reformat4c46d092018-04-07 15:32:371290 TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
1291 this.takeControl();
Simon Zündce724902023-08-25 08:12:521292 /** @type {import('./panels/elements/elements.js')} */
1293 const Elements = await self.runtime.loadLegacyModule('panels/elements/elements.js');
1294 if (!Elements.ElementsPanel.ElementsPanel.firstInspectElementNodeNameForTest) {
1295 await new Promise(
1296 f => this.addSniffer(Elements.ElementsPanel.ElementsPanel, 'firstInspectElementCompletedForTest', f));
Tim van der Lippe1d6e57a2019-09-30 11:55:341297 }
Simon Zündce724902023-08-25 08:12:521298 this.assertEquals(nodeName, Elements.ElementsPanel.ElementsPanel.firstInspectElementNodeNameForTest);
Blink Reformat4c46d092018-04-07 15:32:371299 this.releaseControl();
1300 };
1301
Andrey Lushnikovd92662b2018-05-09 03:57:001302 TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
1303 this.takeControl();
Simon Zünd1cf335c2023-08-23 12:16:501304 const targetAgent = SDK.TargetManager.TargetManager.instance().rootTarget()?.targetAgent();
Andrey Lushnikovd92662b2018-05-09 03:57:001305 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1306 const response1 = await targetAgent.invoke_getBrowserContexts();
1307 this.assertEquals(response1.browserContextIds.length, 1);
1308 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1309 const response2 = await targetAgent.invoke_getBrowserContexts();
1310 this.assertEquals(response2.browserContextIds.length, 0);
1311 this.releaseControl();
1312 };
1313
Peter Marshalld2f58c32020-04-21 13:23:131314 TestSuite.prototype.testNewWindowFromBrowserContext = async function(url) {
1315 this.takeControl();
1316 // Create a BrowserContext.
Simon Zünd1cf335c2023-08-23 12:16:501317 const targetAgent = SDK.TargetManager.TargetManager.instance().rootTarget()?.targetAgent();
Peter Marshalld2f58c32020-04-21 13:23:131318 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1319
1320 // Cause a Browser to be created with the temp profile.
Sigurd Schneider3fec5ca2021-05-14 10:18:341321 const {targetId} = await targetAgent.invoke_createTarget(
1322 {url: 'data:text/html,<!DOCTYPE html>', browserContextId, newWindow: true});
Peter Marshalld2f58c32020-04-21 13:23:131323 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
1324
1325 // Destroy the temp profile.
1326 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1327
1328 this.releaseControl();
1329 };
1330
Andrey Lushnikov0eea25e2018-04-24 22:29:511331 TestSuite.prototype.testCreateBrowserContext = async function(url) {
1332 this.takeControl();
1333 const browserContextIds = [];
Simon Zünd1cf335c2023-08-23 12:16:501334 const targetAgent = SDK.TargetManager.TargetManager.instance().rootTarget()?.targetAgent();
Andrey Lushnikov0eea25e2018-04-24 22:29:511335
Danil Somsikove2101812021-11-05 13:58:561336 const target1 = await createIsolatedTarget(url, browserContextIds);
1337 const target2 = await createIsolatedTarget(url, browserContextIds);
Andrey Lushnikov0eea25e2018-04-24 22:29:511338
Andrey Lushnikov07477b42018-05-08 22:00:521339 const response = await targetAgent.invoke_getBrowserContexts();
1340 this.assertEquals(response.browserContextIds.length, 2);
1341 this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
1342 this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
1343
Andrey Lushnikov0eea25e2018-04-24 22:29:511344 await evalCode(target1, 'localStorage.setItem("page1", "page1")');
1345 await evalCode(target2, 'localStorage.setItem("page2", "page2")');
1346
1347 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
1348 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
1349 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
1350 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
1351
Andrey Lushnikov69499702018-05-08 18:20:471352 const removedTargets = [];
Simon Zünd1cf335c2023-08-23 12:16:501353 SDK.TargetManager.TargetManager.instance().observeTargets(
Paul Lewis4ae5f4f2020-01-23 10:19:331354 {targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
Andrey Lushnikov69499702018-05-08 18:20:471355 await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
1356 this.assertEquals(removedTargets.length, 2);
1357 this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
1358 this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
Andrey Lushnikov0eea25e2018-04-24 22:29:511359
1360 this.releaseControl();
Andrey Lushnikov0eea25e2018-04-24 22:29:511361 };
1362
Danil Somsikove2101812021-11-05 13:58:561363 /**
1364 * @param {string} url
Simon Zünd1cf335c2023-08-23 12:16:501365 * @return {!Promise<!SDK.Target.Target>}
Danil Somsikove2101812021-11-05 13:58:561366 */
1367 async function createIsolatedTarget(url, opt_browserContextIds) {
Simon Zünd1cf335c2023-08-23 12:16:501368 const targetAgent = SDK.TargetManager.TargetManager.instance().rootTarget()?.targetAgent();
Danil Somsikove2101812021-11-05 13:58:561369 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1370 if (opt_browserContextIds) {
1371 opt_browserContextIds.push(browserContextId);
1372 }
1373
1374 const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
1375 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
1376
Simon Zünd1cf335c2023-08-23 12:16:501377 const target = SDK.TargetManager.TargetManager.instance().targets().find(target => target.id() === targetId);
Danil Somsikove2101812021-11-05 13:58:561378 const pageAgent = target.pageAgent();
1379 await pageAgent.invoke_enable();
1380 await pageAgent.invoke_navigate({url});
1381 return target;
1382 }
1383
1384 async function disposeBrowserContext(browserContextId) {
Simon Zünd1cf335c2023-08-23 12:16:501385 const targetAgent = SDK.TargetManager.TargetManager.instance().rootTarget()?.targetAgent();
Danil Somsikove2101812021-11-05 13:58:561386 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1387 }
1388
1389 async function evalCode(target, code) {
1390 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1391 }
1392
Blink Reformat4c46d092018-04-07 15:32:371393 TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
1394 this.takeControl();
1395
1396 await new Promise(callback => this._waitForTargets(2, callback));
1397
1398 async function takeLogs(target) {
Danil Somsikove2101812021-11-05 13:58:561399 return await evalCode(target, `
Blink Reformat4c46d092018-04-07 15:32:371400 (function() {
1401 var result = window.logs.join(' ');
1402 window.logs = [];
1403 return result;
Danil Somsikove2101812021-11-05 13:58:561404 })()`);
Blink Reformat4c46d092018-04-07 15:32:371405 }
1406
1407 let parentFrameOutput;
1408 let childFrameOutput;
1409
Simon Zünd1cf335c2023-08-23 12:16:501410 const inputAgent = SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.inputAgent();
1411 const runtimeAgent = SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.runtimeAgent();
Blink Reformat4c46d092018-04-07 15:32:371412 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
1413 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
1414 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
1415 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
1416 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
1417 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
1418 parentFrameOutput = 'Event type: mousedown button: 0 x: 10 y: 10 Event type: mouseup button: 0 x: 10 y: 20';
Simon Zünd1cf335c2023-08-23 12:16:501419 this.assertEquals(parentFrameOutput, await takeLogs(SDK.TargetManager.TargetManager.instance().targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371420 childFrameOutput = 'Event type: mousedown button: 0 x: 30 y: 40 Event type: mouseup button: 0 x: 30 y: 50';
Simon Zünd1cf335c2023-08-23 12:16:501421 this.assertEquals(childFrameOutput, await takeLogs(SDK.TargetManager.TargetManager.instance().targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371422
Blink Reformat4c46d092018-04-07 15:32:371423 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
Jack Franklin408ed8a2023-07-07 11:05:561424 await runtimeAgent.invoke_evaluate({expression: 'document.querySelector(\'iframe\').focus()'});
Blink Reformat4c46d092018-04-07 15:32:371425 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
1426 parentFrameOutput = 'Event type: keydown';
Simon Zünd1cf335c2023-08-23 12:16:501427 this.assertEquals(parentFrameOutput, await takeLogs(SDK.TargetManager.TargetManager.instance().targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371428 childFrameOutput = 'Event type: keydown';
Simon Zünd1cf335c2023-08-23 12:16:501429 this.assertEquals(childFrameOutput, await takeLogs(SDK.TargetManager.TargetManager.instance().targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371430
1431 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
1432 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1433 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
1434 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1435 parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
Simon Zünd1cf335c2023-08-23 12:16:501436 this.assertEquals(parentFrameOutput, await takeLogs(SDK.TargetManager.TargetManager.instance().targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371437 childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
Simon Zünd1cf335c2023-08-23 12:16:501438 this.assertEquals(childFrameOutput, await takeLogs(SDK.TargetManager.TargetManager.instance().targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371439
1440 this.releaseControl();
1441 };
1442
Andrey Kosyakov4f7fb052019-03-19 15:53:431443 TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
Blink Reformat4c46d092018-04-07 15:32:371444 const test = this;
1445 const loggedHeaders = new Set(['cache-control', 'pragma']);
1446 function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
1447 return new Promise(fulfill => {
Simon Zündb4f900e2023-08-23 09:45:571448 HostModule.ResourceLoader.load(url, headers, callback);
Blink Reformat4c46d092018-04-07 15:32:371449
Sigurd Schneidera327cde2020-01-21 15:48:121450 function callback(success, headers, content, errorDescription) {
1451 test.assertEquals(expectedStatus, errorDescription.statusCode);
Blink Reformat4c46d092018-04-07 15:32:371452
1453 const headersArray = [];
1454 for (const name in headers) {
1455 const nameLower = name.toLowerCase();
Tim van der Lippe1d6e57a2019-09-30 11:55:341456 if (loggedHeaders.has(nameLower)) {
Blink Reformat4c46d092018-04-07 15:32:371457 headersArray.push(nameLower);
Tim van der Lippe1d6e57a2019-09-30 11:55:341458 }
Blink Reformat4c46d092018-04-07 15:32:371459 }
1460 headersArray.sort();
1461 test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
1462 test.assertEquals(expectedContent, content);
1463 fulfill();
1464 }
1465 });
1466 }
1467
Sigurd Schneider5cfca2e2021-03-22 12:09:281468 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:371469 await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
1470 await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
1471 await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
1472 await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
1473
Simon Zünd1cf335c2023-08-23 12:16:501474 await SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.runtimeAgent().invoke_evaluate({
Blink Reformat4c46d092018-04-07 15:32:371475 expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
1476 {credentials: 'include'})`,
1477 awaitPromise: true
1478 });
1479 await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
1480
Simon Zünd1cf335c2023-08-23 12:16:501481 await SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.runtimeAgent().invoke_evaluate({
Andrey Kosyakov73081cc2019-01-08 03:50:591482 expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
1483 {credentials: 'include'})`,
1484 awaitPromise: true
1485 });
1486 await testCase(
1487 baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
Andrey Kosyakov4f7fb052019-03-19 15:53:431488 await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
Changhao Hanaf7ba132021-05-10 12:44:541489 await testCase(fileURL, undefined, 200, [], '<!DOCTYPE html>\n<html>\n<body>\nDummy page.\n</body>\n</html>\n');
Rob Paveza30df0482019-10-09 23:15:491490 await testCase(fileURL + 'thisfileshouldnotbefound', undefined, 404, [], '');
Andrey Kosyakov73081cc2019-01-08 03:50:591491
Blink Reformat4c46d092018-04-07 15:32:371492 this.releaseControl();
1493 };
1494
Joey Arhar723d5b52019-04-19 01:31:391495 TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
1496 this.takeControl();
1497
1498 const testUserAgent = 'test user agent';
Simon Zünd1cf335c2023-08-23 12:16:501499 SDK.NetworkManager.MultitargetNetworkManager.instance().setUserAgentOverride(testUserAgent, null);
Joey Arhar723d5b52019-04-19 01:31:391500
1501 function onRequestUpdated(event) {
1502 const request = event.data;
Simon Zünd1cf335c2023-08-23 12:16:501503 if (request.resourceType() !== Common.ResourceType.resourceTypes.WebSocket) {
Joey Arhar723d5b52019-04-19 01:31:391504 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341505 }
1506 if (!request.requestHeadersText()) {
Joey Arhar723d5b52019-04-19 01:31:391507 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341508 }
Joey Arhar723d5b52019-04-19 01:31:391509
1510 let actualUserAgent = 'no user-agent header';
1511 for (const {name, value} of request.requestHeaders()) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341512 if (name.toLowerCase() === 'user-agent') {
Joey Arhar723d5b52019-04-19 01:31:391513 actualUserAgent = value;
Tim van der Lippe1d6e57a2019-09-30 11:55:341514 }
Joey Arhar723d5b52019-04-19 01:31:391515 }
1516 this.assertEquals(testUserAgent, actualUserAgent);
1517 this.releaseControl();
1518 }
Simon Zünd1cf335c2023-08-23 12:16:501519 SDK.TargetManager.TargetManager.instance().addModelListener(
1520 SDK.NetworkManager.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
Joey Arhar723d5b52019-04-19 01:31:391521
1522 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
1523 };
1524
Danil Somsikov7ee05592021-10-26 09:42:111525 TestSuite.prototype.testExtensionWebSocketOfflineNetworkConditions = async function(websocketPort) {
Simon Zünd1cf335c2023-08-23 12:16:501526 SDK.NetworkManager.MultitargetNetworkManager.instance().setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Danil Somsikov7ee05592021-10-26 09:42:111527
1528 // TODO(crbug.com/1263900): Currently we don't send loadingFailed for web sockets.
1529 // Update this once we do.
Simon Zünd1cf335c2023-08-23 12:16:501530 this.addSniffer(SDK.NetworkManager.NetworkDispatcher.prototype, 'webSocketClosed', () => {
Danil Somsikov7ee05592021-10-26 09:42:111531 this.releaseControl();
1532 });
1533
1534 this.takeControl();
1535 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}/echo-with-no-extension')`, () => {});
1536 };
1537
Blink Reformat4c46d092018-04-07 15:32:371538 /**
1539 * Serializes array of uiSourceCodes to string.
1540 * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
1541 * @return {string}
1542 */
1543 TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
1544 const names = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341545 for (let i = 0; i < uiSourceCodes.length; i++) {
Blink Reformat4c46d092018-04-07 15:32:371546 names.push('"' + uiSourceCodes[i].url() + '"');
Tim van der Lippe1d6e57a2019-09-30 11:55:341547 }
Blink Reformat4c46d092018-04-07 15:32:371548 return names.join(',');
1549 };
1550
Danil Somsikov338debd2021-12-14 11:42:001551 TestSuite.prototype.testSourceMapsFromExtension = function(extensionId) {
1552 this.takeControl();
Simon Zünd1cf335c2023-08-23 12:16:501553 const debuggerModel =
1554 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.model(SDK.DebuggerModel.DebuggerModel);
Danil Somsikov338debd2021-12-14 11:42:001555 debuggerModel.sourceMapManager().addEventListener(
1556 SDK.SourceMapManager.Events.SourceMapAttached, this.releaseControl.bind(this));
1557
1558 this.evaluateInConsole_(
1559 `console.log(1) //# sourceMappingURL=chrome-extension://${extensionId}/source.map`, () => {});
1560 };
1561
Danil Somsikov98c7a812022-01-11 09:03:351562 TestSuite.prototype.testSourceMapsFromDevtools = function() {
1563 this.takeControl();
Simon Zünd1cf335c2023-08-23 12:16:501564 const debuggerModel =
1565 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.model(SDK.DebuggerModel.DebuggerModel);
Danil Somsikov98c7a812022-01-11 09:03:351566 debuggerModel.sourceMapManager().addEventListener(
1567 SDK.SourceMapManager.Events.SourceMapWillAttach, this.releaseControl.bind(this));
1568
1569 this.evaluateInConsole_(
1570 'console.log(1) //# sourceMappingURL=devtools://devtools/bundled/devtools_compatibility.js', () => {});
1571 };
1572
1573 TestSuite.prototype.testDoesNotCrashOnSourceMapsFromUnknownScheme = function() {
1574 this.evaluateInConsole_('console.log(1) //# sourceMappingURL=invalid-scheme://source.map', () => {});
1575 };
1576
Blink Reformat4c46d092018-04-07 15:32:371577 /**
1578 * Returns all loaded non anonymous uiSourceCodes.
1579 * @return {!Array.<!Workspace.UISourceCode>}
1580 */
1581 TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
1582 /**
1583 * @param {!Workspace.UISourceCode} uiSourceCode
1584 */
1585 function filterOutService(uiSourceCode) {
1586 return !uiSourceCode.project().isServiceProject();
1587 }
1588
Simon Zünddf37f272023-08-25 07:45:041589 const uiSourceCodes = Workspace.Workspace.WorkspaceImpl.instance().uiSourceCodes();
Blink Reformat4c46d092018-04-07 15:32:371590 return uiSourceCodes.filter(filterOutService);
1591 };
1592
1593 /*
1594 * Evaluates the code in the console as if user typed it manually and invokes
1595 * the callback when the result message is received and added to the console.
1596 * @param {string} code
1597 * @param {function(string)} callback
1598 */
1599 TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
1600 function innerEvaluate() {
Simon Zündeb6e27f2023-08-25 07:27:341601 UI.Context.Context.instance().removeFlavorChangeListener(
1602 SDK.RuntimeModel.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371603 const consoleView = Console.ConsoleView.instance();
Jan Scheffler9befd492021-08-12 13:44:261604 consoleView.prompt.appendCommand(code);
Blink Reformat4c46d092018-04-07 15:32:371605
Jan Scheffler9befd492021-08-12 13:44:261606 this.addSniffer(Console.ConsoleView.prototype, 'consoleMessageAddedForTest', function(viewMessage) {
Blink Reformat4c46d092018-04-07 15:32:371607 callback(viewMessage.toMessageElement().deepTextContent());
1608 }.bind(this));
1609 }
1610
1611 function showConsoleAndEvaluate() {
Simon Zünd5111ff42023-08-23 08:46:171612 Common.Console.Console.instance().showPromise().then(innerEvaluate.bind(this));
Blink Reformat4c46d092018-04-07 15:32:371613 }
1614
Simon Zündeb6e27f2023-08-25 07:27:341615 if (!UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext)) {
1616 UI.Context.Context.instance().addFlavorChangeListener(
1617 SDK.RuntimeModel.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371618 return;
1619 }
1620 showConsoleAndEvaluate.call(this);
1621 };
1622
1623 /**
1624 * Checks that all expected scripts are present in the scripts list
1625 * in the Scripts panel.
1626 * @param {!Array.<string>} expected Regular expressions describing
1627 * expected script names.
1628 * @return {boolean} Whether all the scripts are in "scripts-files" select
1629 * box
1630 */
1631 TestSuite.prototype._scriptsAreParsed = function(expected) {
1632 const uiSourceCodes = this.nonAnonymousUISourceCodes_();
1633 // Check that at least all the expected scripts are present.
1634 const missing = expected.slice(0);
1635 for (let i = 0; i < uiSourceCodes.length; ++i) {
1636 for (let j = 0; j < missing.length; ++j) {
1637 if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
1638 missing.splice(j, 1);
1639 break;
1640 }
1641 }
1642 }
1643 return missing.length === 0;
1644 };
1645
1646 /**
1647 * Waits for script pause, checks expectations, and invokes the callback.
1648 * @param {function():void} callback
1649 */
1650 TestSuite.prototype._waitForScriptPause = function(callback) {
Simon Zünd1cf335c2023-08-23 12:16:501651 this.addSniffer(SDK.DebuggerModel.DebuggerModel.prototype, 'pausedScript', callback);
Blink Reformat4c46d092018-04-07 15:32:371652 };
1653
1654 /**
1655 * Waits until all the scripts are parsed and invokes the callback.
1656 */
1657 TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
1658 const test = this;
1659
1660 function waitForAllScripts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341661 if (test._scriptsAreParsed(expectedScripts)) {
Blink Reformat4c46d092018-04-07 15:32:371662 callback();
Tim van der Lippe1d6e57a2019-09-30 11:55:341663 } else {
Simon Zündeb6e27f2023-08-25 07:27:341664 test.addSniffer(
1665 Sources.SourcesPanel.SourcesPanel.instance().sourcesView(), 'addUISourceCode', waitForAllScripts);
Tim van der Lippe1d6e57a2019-09-30 11:55:341666 }
Blink Reformat4c46d092018-04-07 15:32:371667 }
1668
1669 waitForAllScripts();
1670 };
1671
1672 TestSuite.prototype._waitForTargets = function(n, callback) {
1673 checkTargets.call(this);
1674
1675 function checkTargets() {
Simon Zünd1cf335c2023-08-23 12:16:501676 if (SDK.TargetManager.TargetManager.instance().targets().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371677 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341678 } else {
Simon Zünd1cf335c2023-08-23 12:16:501679 this.addSniffer(SDK.TargetManager.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341680 }
Blink Reformat4c46d092018-04-07 15:32:371681 }
1682 };
1683
1684 TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
Simon Zünd1cf335c2023-08-23 12:16:501685 const runtimeModel =
1686 SDK.TargetManager.TargetManager.instance().primaryPageTarget()?.model(SDK.RuntimeModel.RuntimeModel);
Blink Reformat4c46d092018-04-07 15:32:371687 checkForExecutionContexts.call(this);
1688
1689 function checkForExecutionContexts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341690 if (runtimeModel.executionContexts().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371691 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341692 } else {
Simon Zünd1cf335c2023-08-23 12:16:501693 this.addSniffer(
1694 SDK.RuntimeModel.RuntimeModel.prototype, 'executionContextCreated', checkForExecutionContexts.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341695 }
Blink Reformat4c46d092018-04-07 15:32:371696 }
1697 };
1698
Blink Reformat4c46d092018-04-07 15:32:371699 window.uiTests = new TestSuite(window.domAutomationController);
1700})(window);