blob: b76b6f3369c74ba567b19473d76ea3ff33a45ad3 [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) {
41
Blink Reformat4c46d092018-04-07 15:32:3742 const TestSuite = class {
43 /**
44 * Test suite for interactive UI tests.
45 * @param {Object} domAutomationController DomAutomationController instance.
46 */
47 constructor(domAutomationController) {
48 this.domAutomationController_ = domAutomationController;
49 this.controlTaken_ = false;
50 this.timerId_ = -1;
51 this._asyncInvocationId = 0;
52 }
53
54 /**
55 * Key event with given key identifier.
56 */
57 static createKeyEvent(key) {
58 return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key});
59 }
60 };
61
62 /**
63 * Reports test failure.
64 * @param {string} message Failure description.
65 */
66 TestSuite.prototype.fail = function(message) {
Tim van der Lippe1d6e57a2019-09-30 11:55:3467 if (this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:3768 this.reportFailure_(message);
Tim van der Lippe1d6e57a2019-09-30 11:55:3469 } else {
Blink Reformat4c46d092018-04-07 15:32:3770 throw message;
Tim van der Lippe1d6e57a2019-09-30 11:55:3471 }
Blink Reformat4c46d092018-04-07 15:32:3772 };
73
74 /**
75 * Equals assertion tests that expected === actual.
76 * @param {!Object|boolean} expected Expected object.
77 * @param {!Object|boolean} actual Actual object.
78 * @param {string} opt_message User message to print if the test fails.
79 */
80 TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
81 if (expected !== actual) {
82 let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
Tim van der Lippe1d6e57a2019-09-30 11:55:3483 if (opt_message) {
Blink Reformat4c46d092018-04-07 15:32:3784 message = opt_message + '(' + message + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:3485 }
Blink Reformat4c46d092018-04-07 15:32:3786 this.fail(message);
87 }
88 };
89
90 /**
91 * True assertion tests that value == true.
92 * @param {!Object} value Actual object.
93 * @param {string} opt_message User message to print if the test fails.
94 */
95 TestSuite.prototype.assertTrue = function(value, opt_message) {
Tim van der Lipped7cfd142021-01-07 12:17:2496 this.assertEquals(true, Boolean(value), opt_message);
Blink Reformat4c46d092018-04-07 15:32:3797 };
98
99 /**
100 * Takes control over execution.
Sigurd Schneider72ac3562021-03-11 10:35:25101 * @param {{slownessFactor:number}=} options
Blink Reformat4c46d092018-04-07 15:32:37102 */
Sigurd Schneider72ac3562021-03-11 10:35:25103 TestSuite.prototype.takeControl = function(options) {
104 const {slownessFactor} = {slownessFactor: 1, ...options};
Blink Reformat4c46d092018-04-07 15:32:37105 this.controlTaken_ = true;
106 // Set up guard timer.
107 const self = this;
Sigurd Schneider376d2712021-03-12 15:07:51108 const timeoutInSec = 20 * slownessFactor;
Blink Reformat4c46d092018-04-07 15:32:37109 this.timerId_ = setTimeout(function() {
Sigurd Schneider376d2712021-03-12 15:07:51110 self.reportFailure_(`Timeout exceeded: ${timeoutInSec} sec`);
111 }, timeoutInSec * 1000);
Blink Reformat4c46d092018-04-07 15:32:37112 };
113
114 /**
115 * Releases control over execution.
116 */
117 TestSuite.prototype.releaseControl = function() {
118 if (this.timerId_ !== -1) {
119 clearTimeout(this.timerId_);
120 this.timerId_ = -1;
121 }
122 this.controlTaken_ = false;
123 this.reportOk_();
124 };
125
126 /**
127 * Async tests use this one to report that they are completed.
128 */
129 TestSuite.prototype.reportOk_ = function() {
130 this.domAutomationController_.send('[OK]');
131 };
132
133 /**
134 * Async tests use this one to report failures.
135 */
136 TestSuite.prototype.reportFailure_ = function(error) {
137 if (this.timerId_ !== -1) {
138 clearTimeout(this.timerId_);
139 this.timerId_ = -1;
140 }
141 this.domAutomationController_.send('[FAILED] ' + error);
142 };
143
144 /**
145 * Run specified test on a fresh instance of the test suite.
146 * @param {Array<string>} args method name followed by its parameters.
147 */
148 TestSuite.prototype.dispatchOnTestSuite = function(args) {
149 const methodName = args.shift();
150 try {
151 this[methodName].apply(this, args);
Tim van der Lippe1d6e57a2019-09-30 11:55:34152 if (!this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:37153 this.reportOk_();
Tim van der Lippe1d6e57a2019-09-30 11:55:34154 }
Blink Reformat4c46d092018-04-07 15:32:37155 } catch (e) {
156 this.reportFailure_(e);
157 }
158 };
159
160 /**
161 * Wrap an async method with TestSuite.{takeControl(), releaseControl()}
162 * and invoke TestSuite.reportOk_ upon completion.
163 * @param {Array<string>} args method name followed by its parameters.
164 */
165 TestSuite.prototype.waitForAsync = function(var_args) {
166 const args = Array.prototype.slice.call(arguments);
167 this.takeControl();
168 args.push(this.releaseControl.bind(this));
169 this.dispatchOnTestSuite(args);
170 };
171
172 /**
173 * Overrides the method with specified name until it's called first time.
174 * @param {!Object} receiver An object whose method to override.
175 * @param {string} methodName Name of the method to override.
176 * @param {!Function} override A function that should be called right after the
177 * overridden method returns.
178 * @param {?boolean} opt_sticky Whether restore original method after first run
179 * or not.
180 */
181 TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) {
182 const orig = receiver[methodName];
Tim van der Lippe1d6e57a2019-09-30 11:55:34183 if (typeof orig !== 'function') {
Blink Reformat4c46d092018-04-07 15:32:37184 this.fail('Cannot find method to override: ' + methodName);
Tim van der Lippe1d6e57a2019-09-30 11:55:34185 }
Blink Reformat4c46d092018-04-07 15:32:37186 const test = this;
187 receiver[methodName] = function(var_args) {
188 let result;
189 try {
190 result = orig.apply(this, arguments);
191 } finally {
Tim van der Lippe1d6e57a2019-09-30 11:55:34192 if (!opt_sticky) {
Blink Reformat4c46d092018-04-07 15:32:37193 receiver[methodName] = orig;
Tim van der Lippe1d6e57a2019-09-30 11:55:34194 }
Blink Reformat4c46d092018-04-07 15:32:37195 }
196 // In case of exception the override won't be called.
197 try {
198 override.apply(this, arguments);
199 } catch (e) {
200 test.fail('Exception in overriden method \'' + methodName + '\': ' + e);
201 }
202 return result;
203 };
204 };
205
206 /**
207 * Waits for current throttler invocations, if any.
208 * @param {!Common.Throttler} throttler
209 * @param {function()} callback
210 */
211 TestSuite.prototype.waitForThrottler = function(throttler, callback) {
212 const test = this;
213 let scheduleShouldFail = true;
214 test.addSniffer(throttler, 'schedule', onSchedule);
215
216 function hasSomethingScheduled() {
217 return throttler._isRunningProcess || throttler._process;
218 }
219
220 function checkState() {
221 if (!hasSomethingScheduled()) {
222 scheduleShouldFail = false;
223 callback();
224 return;
225 }
226
227 test.addSniffer(throttler, '_processCompletedForTests', checkState);
228 }
229
230 function onSchedule() {
Tim van der Lippe1d6e57a2019-09-30 11:55:34231 if (scheduleShouldFail) {
Blink Reformat4c46d092018-04-07 15:32:37232 test.fail('Unexpected Throttler.schedule');
Tim van der Lippe1d6e57a2019-09-30 11:55:34233 }
Blink Reformat4c46d092018-04-07 15:32:37234 }
235
236 checkState();
237 };
238
239 /**
240 * @param {string} panelName Name of the panel to show.
241 */
242 TestSuite.prototype.showPanel = function(panelName) {
Paul Lewis0a7c6b62020-01-23 16:16:22243 return self.UI.inspectorView.showPanel(panelName);
Blink Reformat4c46d092018-04-07 15:32:37244 };
245
246 // UI Tests
247
248 /**
249 * Tests that scripts tab can be open and populated with inspected scripts.
250 */
251 TestSuite.prototype.testShowScriptsTab = function() {
252 const test = this;
253 this.showPanel('sources').then(function() {
254 // There should be at least main page script.
255 this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
256 test.releaseControl();
257 });
258 }.bind(this));
259 // Wait until all scripts are added to the debugger.
260 this.takeControl();
261 };
262
263 /**
264 * Tests that scripts tab is populated with inspected scripts even if it
265 * hadn't been shown by the moment inspected paged refreshed.
266 * @see http://crbug.com/26312
267 */
268 TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() {
269 const test = this;
Paul Lewis4ae5f4f2020-01-23 10:19:33270 const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
Blink Reformat4c46d092018-04-07 15:32:37271 debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
272
273 this.showPanel('elements').then(function() {
274 // Reload inspected page. It will reset the debugger agent.
275 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
276 });
277
278 function waitUntilScriptIsParsed() {
279 debuggerModel.removeEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
280 test.showPanel('sources').then(function() {
281 test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
282 test.releaseControl();
283 });
284 });
285 }
286
287 // Wait until all scripts are added to the debugger.
288 this.takeControl();
289 };
290
291 /**
292 * Tests that scripts list contains content scripts.
293 */
294 TestSuite.prototype.testContentScriptIsPresent = function() {
295 const test = this;
296 this.showPanel('sources').then(function() {
297 test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() {
298 test.releaseControl();
299 });
300 });
301
302 // Wait until all scripts are added to the debugger.
303 this.takeControl();
304 };
305
306 /**
307 * Tests that scripts are not duplicaed on Scripts tab switch.
308 */
309 TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() {
310 const test = this;
311
312 function switchToElementsTab() {
313 test.showPanel('elements').then(function() {
314 setTimeout(switchToScriptsTab, 0);
315 });
316 }
317
318 function switchToScriptsTab() {
319 test.showPanel('sources').then(function() {
320 setTimeout(checkScriptsPanel, 0);
321 });
322 }
323
324 function checkScriptsPanel() {
325 test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.');
326 checkNoDuplicates();
327 test.releaseControl();
328 }
329
330 function checkNoDuplicates() {
331 const uiSourceCodes = test.nonAnonymousUISourceCodes_();
332 for (let i = 0; i < uiSourceCodes.length; i++) {
333 for (let j = i + 1; j < uiSourceCodes.length; j++) {
334 test.assertTrue(
335 uiSourceCodes[i].url() !== uiSourceCodes[j].url(),
336 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes));
337 }
338 }
339 }
340
341 this.showPanel('sources').then(function() {
342 test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
343 checkNoDuplicates();
344 setTimeout(switchToElementsTab, 0);
345 });
346 });
347
348 // Wait until all scripts are added to the debugger.
Sigurd Schneiderd8d7e822021-03-16 09:34:19349 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37350 };
351
352 // Tests that debugger works correctly if pause event occurs when DevTools
353 // frontend is being loaded.
354 TestSuite.prototype.testPauseWhenLoadingDevTools = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33355 const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34356 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37357 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34358 }
Blink Reformat4c46d092018-04-07 15:32:37359
360 this.showPanel('sources').then(function() {
361 // Script execution can already be paused.
362
363 this._waitForScriptPause(this.releaseControl.bind(this));
364 }.bind(this));
365
366 this.takeControl();
367 };
368
369 // Tests that pressing "Pause" will pause script execution if the script
370 // is already running.
371 TestSuite.prototype.testPauseWhenScriptIsRunning = function() {
372 this.showPanel('sources').then(function() {
373 this.evaluateInConsole_('setTimeout("handleClick()", 0)', didEvaluateInConsole.bind(this));
374 }.bind(this));
375
376 function didEvaluateInConsole(resultText) {
377 this.assertTrue(!isNaN(resultText), 'Failed to get timer id: ' + resultText);
378 // Wait for some time to make sure that inspected page is running the
379 // infinite loop.
380 setTimeout(testScriptPause.bind(this), 300);
381 }
382
383 function testScriptPause() {
384 // The script should be in infinite loop. Click "Pause" button to
385 // pause it and wait for the result.
386 UI.panels.sources._togglePause();
387
388 this._waitForScriptPause(this.releaseControl.bind(this));
389 }
390
391 this.takeControl();
392 };
393
394 /**
395 * Tests network size.
396 */
397 TestSuite.prototype.testNetworkSize = function() {
398 const test = this;
399
400 function finishRequest(request, finishTime) {
401 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
402 test.releaseControl();
403 }
404
405 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
406
407 // Reload inspected page to sniff network events
408 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
409
Sigurd Schneiderd8d7e822021-03-16 09:34:19410 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37411 };
412
413 /**
414 * Tests network sync size.
415 */
416 TestSuite.prototype.testNetworkSyncSize = function() {
417 const test = this;
418
419 function finishRequest(request, finishTime) {
420 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
421 test.releaseControl();
422 }
423
424 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
425
426 // Send synchronous XHR to sniff network events
427 test.evaluateInConsole_(
428 'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {});
429
Sigurd Schneiderd8d7e822021-03-16 09:34:19430 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37431 };
432
433 /**
434 * Tests network raw headers text.
435 */
436 TestSuite.prototype.testNetworkRawHeadersText = function() {
437 const test = this;
438
439 function finishRequest(request, finishTime) {
Tim van der Lippe1d6e57a2019-09-30 11:55:34440 if (!request.responseHeadersText) {
Blink Reformat4c46d092018-04-07 15:32:37441 test.fail('Failure: resource does not have response headers text');
Tim van der Lippe1d6e57a2019-09-30 11:55:34442 }
Blink Reformat4c46d092018-04-07 15:32:37443 const index = request.responseHeadersText.indexOf('Date:');
444 test.assertEquals(
445 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length');
446 test.releaseControl();
447 }
448
449 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
450
451 // Reload inspected page to sniff network events
452 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
453
Sigurd Schneiderd8d7e822021-03-16 09:34:19454 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37455 };
456
457 /**
458 * Tests network timing.
459 */
460 TestSuite.prototype.testNetworkTiming = function() {
461 const test = this;
462
463 function finishRequest(request, finishTime) {
464 // Setting relaxed expectations to reduce flakiness.
465 // Server sends headers after 100ms, then sends data during another 100ms.
466 // We expect these times to be measured at least as 70ms.
467 test.assertTrue(
468 request.timing.receiveHeadersEnd - request.timing.connectStart >= 70,
469 'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' +
470 'receiveHeadersEnd=' + request.timing.receiveHeadersEnd + ', connectStart=' +
471 request.timing.connectStart + '.');
472 test.assertTrue(
473 request.responseReceivedTime - request.startTime >= 0.07,
474 'Time between responseReceivedTime and startTime should be >=0.07s, but was ' +
475 'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.');
476 test.assertTrue(
477 request.endTime - request.startTime >= 0.14,
478 'Time between endTime and startTime should be >=0.14s, but was ' +
479 'endtime=' + request.endTime + ', startTime=' + request.startTime + '.');
480
481 test.releaseControl();
482 }
483
484 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
485
486 // Reload inspected page to sniff network events
487 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
488
Sigurd Schneiderd8d7e822021-03-16 09:34:19489 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37490 };
491
492 TestSuite.prototype.testPushTimes = function(url) {
493 const test = this;
494 let pendingRequestCount = 2;
495
496 function finishRequest(request, finishTime) {
497 test.assertTrue(
498 typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0,
499 `pushStart is invalid: ${request.timing.pushStart}`);
500 test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`);
501 test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime');
502 if (request.url().endsWith('?pushUseNullEndTime')) {
503 test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`);
504 } else {
505 test.assertTrue(
506 request.timing.pushStart < request.timing.pushEnd,
507 `pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`);
508 // The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant.
509 test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime');
510 test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime');
511 }
Tim van der Lippe1d6e57a2019-09-30 11:55:34512 if (!--pendingRequestCount) {
Blink Reformat4c46d092018-04-07 15:32:37513 test.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:34514 }
Blink Reformat4c46d092018-04-07 15:32:37515 }
516
517 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest, true);
518
519 test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {});
520 test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {});
521 this.takeControl();
522 };
523
524 TestSuite.prototype.testConsoleOnNavigateBack = function() {
525
526 function filteredMessages() {
Tim van der Lippeeb876c62021-05-14 15:02:11527 return self.SDK.consoleModel.messages().filter(a => a.source !== Protocol.Log.LogEntrySource.Violation);
Blink Reformat4c46d092018-04-07 15:32:37528 }
529
Tim van der Lippe1d6e57a2019-09-30 11:55:34530 if (filteredMessages().length === 1) {
Blink Reformat4c46d092018-04-07 15:32:37531 firstConsoleMessageReceived.call(this, null);
Tim van der Lippe1d6e57a2019-09-30 11:55:34532 } else {
Paul Lewise504fd62020-01-23 16:52:33533 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Tim van der Lippe1d6e57a2019-09-30 11:55:34534 }
Blink Reformat4c46d092018-04-07 15:32:37535
536
537 function firstConsoleMessageReceived(event) {
Tim van der Lippeeb876c62021-05-14 15:02:11538 if (event && event.data.source === Protocol.Log.LogEntrySource.Violation) {
Blink Reformat4c46d092018-04-07 15:32:37539 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34540 }
Paul Lewise504fd62020-01-23 16:52:33541 self.SDK.consoleModel.removeEventListener(
542 SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Blink Reformat4c46d092018-04-07 15:32:37543 this.evaluateInConsole_('clickLink();', didClickLink.bind(this));
544 }
545
546 function didClickLink() {
547 // Check that there are no new messages(command is not a message).
548 this.assertEquals(3, filteredMessages().length);
549 this.evaluateInConsole_('history.back();', didNavigateBack.bind(this));
550 }
551
552 function didNavigateBack() {
553 // Make sure navigation completed and possible console messages were pushed.
554 this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this));
555 }
556
557 function didCompleteNavigation() {
558 this.assertEquals(7, filteredMessages().length);
559 this.releaseControl();
560 }
561
562 this.takeControl();
563 };
564
565 TestSuite.prototype.testSharedWorker = function() {
566 function didEvaluateInConsole(resultText) {
567 this.assertEquals('2011', resultText);
568 this.releaseControl();
569 }
570 this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this));
571 this.takeControl();
572 };
573
574 TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() {
575 // Make sure the worker is loaded.
576 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00577 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37578
579 function callback() {
Simon Zündb6414c92020-03-19 07:16:40580 ProtocolClient.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37581 }
582 };
583
584 TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() {
585 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00586 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37587
588 function callback() {
Paul Lewis4ae5f4f2020-01-23 10:19:33589 const debuggerModel = self.SDK.targetManager.models(SDK.DebuggerModel)[0];
Blink Reformat4c46d092018-04-07 15:32:37590 if (debuggerModel.isPaused()) {
Paul Lewise504fd62020-01-23 16:52:33591 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31592 debuggerModel.resume();
Blink Reformat4c46d092018-04-07 15:32:37593 return;
594 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31595 this._waitForScriptPause(callback.bind(this));
596 }
597
598 function onConsoleMessage(event) {
599 const message = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:34600 if (message !== 'connected') {
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31601 this.fail('Unexpected message: ' + message);
Tim van der Lippe1d6e57a2019-09-30 11:55:34602 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31603 this.releaseControl();
Blink Reformat4c46d092018-04-07 15:32:37604 }
605 };
606
Joey Arhar0585e6f2018-10-30 23:11:18607 TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
608 this.takeControl();
609 this.showPanel('network').then(() => {
Tim van der Lippe1d6e57a2019-09-30 11:55:34610 if (!document.querySelector('#network-container')) {
Joey Arhar0585e6f2018-10-30 23:11:18611 this.fail('unable to find #network-container');
Tim van der Lippe1d6e57a2019-09-30 11:55:34612 }
Joey Arhar0585e6f2018-10-30 23:11:18613 this.releaseControl();
614 });
615 };
616
Blink Reformat4c46d092018-04-07 15:32:37617 TestSuite.prototype.enableTouchEmulation = function() {
618 const deviceModeModel = new Emulation.DeviceModeModel(function() {});
Paul Lewis4ae5f4f2020-01-23 10:19:33619 deviceModeModel._target = self.SDK.targetManager.mainTarget();
Blink Reformat4c46d092018-04-07 15:32:37620 deviceModeModel._applyTouch(true, true);
621 };
622
623 TestSuite.prototype.waitForDebuggerPaused = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33624 const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34625 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37626 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34627 }
Blink Reformat4c46d092018-04-07 15:32:37628
629 this.takeControl();
630 this._waitForScriptPause(this.releaseControl.bind(this));
631 };
632
633 TestSuite.prototype.switchToPanel = function(panelName) {
634 this.showPanel(panelName).then(this.releaseControl.bind(this));
635 this.takeControl();
636 };
637
638 // Regression test for crbug.com/370035.
639 TestSuite.prototype.testDeviceMetricsOverrides = function() {
640 function dumpPageMetrics() {
641 return JSON.stringify(
642 {width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
643 }
644
645 const test = this;
646
647 async function testOverrides(params, metrics, callback) {
Paul Lewis4ae5f4f2020-01-23 10:19:33648 await self.SDK.targetManager.mainTarget().emulationAgent().invoke_setDeviceMetricsOverride(params);
Blink Reformat4c46d092018-04-07 15:32:37649 test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics);
650
651 function checkMetrics(consoleResult) {
652 test.assertEquals(
Benedikt Meurer62b49da2021-02-18 09:15:55653 JSON.stringify(JSON.stringify(metrics)), consoleResult,
654 'Wrong metrics for params: ' + JSON.stringify(params));
Blink Reformat4c46d092018-04-07 15:32:37655 callback();
656 }
657 }
658
659 function step1() {
660 testOverrides(
661 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
662 {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
663 }
664
665 function step2() {
666 testOverrides(
667 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
668 {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
669 }
670
671 function step3() {
672 testOverrides(
673 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
674 {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
675 }
676
677 function step4() {
678 testOverrides(
679 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
680 {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
681 }
682
683 function finish() {
684 test.releaseControl();
685 }
686
687 test.takeControl();
688 step1();
689 };
690
691 TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
692 const test = this;
693 let receivedReady = false;
694
695 function signalToShowAutofill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33696 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37697 {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Paul Lewis4ae5f4f2020-01-23 10:19:33698 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37699 {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
700 }
701
702 function selectTopAutoFill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33703 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37704 {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
Paul Lewis4ae5f4f2020-01-23 10:19:33705 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37706 {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
707
708 test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
709 }
710
711 function onResultOfInput(value) {
712 // Console adds "" around the response.
713 test.assertEquals('"Abbf"', value);
714 test.releaseControl();
715 }
716
717 function onConsoleMessage(event) {
718 const message = event.data.messageText;
719 if (message === 'ready' && !receivedReady) {
720 receivedReady = true;
721 signalToShowAutofill();
722 }
723 // This log comes from the browser unittest code.
Tim van der Lippe1d6e57a2019-09-30 11:55:34724 if (message === 'didShowSuggestions') {
Blink Reformat4c46d092018-04-07 15:32:37725 selectTopAutoFill();
Tim van der Lippe1d6e57a2019-09-30 11:55:34726 }
Blink Reformat4c46d092018-04-07 15:32:37727 }
728
Sigurd Schneider5cfca2e2021-03-22 12:09:28729 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37730
731 // It is possible for the ready console messagage to be already received but not handled
732 // or received later. This ensures we can catch both cases.
Paul Lewise504fd62020-01-23 16:52:33733 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37734
Paul Lewise504fd62020-01-23 16:52:33735 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:37736 if (messages.length) {
737 const text = messages[0].messageText;
738 this.assertEquals('ready', text);
739 signalToShowAutofill();
740 }
741 };
742
Pâris MEULEMANd4709cb2019-04-17 08:32:48743 TestSuite.prototype.testKeyEventUnhandled = function() {
744 function onKeyEventUnhandledKeyDown(event) {
745 this.assertEquals('keydown', event.data.type);
746 this.assertEquals('F8', event.data.key);
747 this.assertEquals(119, event.data.keyCode);
748 this.assertEquals(0, event.data.modifiers);
749 this.assertEquals('', event.data.code);
Tim van der Lippe50cfa9b2019-10-01 10:40:58750 Host.InspectorFrontendHost.events.removeEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44751 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Tim van der Lippe50cfa9b2019-10-01 10:40:58752 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44753 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33754 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48755 {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
756 }
757 function onKeyEventUnhandledKeyUp(event) {
758 this.assertEquals('keyup', event.data.type);
759 this.assertEquals('F8', event.data.key);
760 this.assertEquals(119, event.data.keyCode);
761 this.assertEquals(0, event.data.modifiers);
762 this.assertEquals('F8', event.data.code);
763 this.releaseControl();
764 }
765 this.takeControl();
Tim van der Lippe50cfa9b2019-10-01 10:40:58766 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44767 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33768 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48769 {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
770 };
771
Jack Lynchb514f9f2020-06-19 21:16:45772 // Tests that the keys that are forwarded from the browser update
773 // when their shortcuts change
774 TestSuite.prototype.testForwardedKeysChanged = function() {
Jack Lynch080a0fd2020-06-15 19:55:19775 this.takeControl();
776
777 this.addSniffer(self.UI.shortcutRegistry, '_registerBindings', () => {
778 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
779 {type: 'rawKeyDown', key: 'F1', windowsVirtualKeyCode: 112, nativeVirtualKeyCode: 112});
780 });
781 this.addSniffer(self.UI.shortcutRegistry, 'handleKey', key => {
782 this.assertEquals(112, key);
783 this.releaseControl();
784 });
785
786 self.Common.settings.moduleSetting('activeKeybindSet').set('vsCode');
787 };
788
Blink Reformat4c46d092018-04-07 15:32:37789 TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33790 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37791 {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
Paul Lewis4ae5f4f2020-01-23 10:19:33792 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37793 {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
794 };
795
Pâris MEULEMANd81f35f2019-05-07 09:04:34796 // Check that showing the certificate viewer does not crash, crbug.com/954874
797 TestSuite.prototype.testShowCertificate = function() {
Tim van der Lippe50cfa9b2019-10-01 10:40:58798 Host.InspectorFrontendHost.showCertificateViewer([
Pâris MEULEMANd81f35f2019-05-07 09:04:34799 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
800 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
801 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
802 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
803 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
804 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
805 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
806 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
807 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
808 'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
809 'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
810 'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOcIA7AVR/Ck22Uj8X' +
811 'UOECercjUrKdDyaAPcLp2TThAgMBAAGjggHZMIIB1TATBgNVHSUEDDAKBggr' +
812 'BgEFBQcDATCBrwYDVR0RBIGnMIGkgg0qLmFwcHNwb3QuY29tggsqLmEucnVu' +
813 'LmFwcIIVKi50aGlua3dpdGhnb29nbGUuY29tghAqLndpdGhnb29nbGUuY29t' +
814 'ghEqLndpdGh5b3V0dWJlLmNvbYILYXBwc3BvdC5jb22CB3J1bi5hcHCCE3Ro' +
815 'aW5rd2l0aGdvb2dsZS5jb22CDndpdGhnb29nbGUuY29tgg93aXRoeW91dHVi' +
816 'ZS5jb20waAYIKwYBBQUHAQEEXDBaMC0GCCsGAQUFBzAChiFodHRwOi8vcGtp' +
817 'Lmdvb2cvZ3NyMi9HVFNHSUFHMy5jcnQwKQYIKwYBBQUHMAGGHWh0dHA6Ly9v' +
818 'Y3NwLnBraS5nb29nL0dUU0dJQUczMB0GA1UdDgQWBBTGkpE5o0H9+Wjc05rF' +
819 'hNQiYDjBFjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFHfCuFCaZ3Z2sS3C' +
820 'htCDoH6mfrpLMCEGA1UdIAQaMBgwDAYKKwYBBAHWeQIFAzAIBgZngQwBAgIw' +
821 'MQYDVR0fBCowKDAmoCSgIoYgaHR0cDovL2NybC5wa2kuZ29vZy9HVFNHSUFH' +
822 'My5jcmwwDQYJKoZIhvcNAQELBQADggEBALqoYGqWtJW/6obEzY+ehsgfyXb+' +
823 'qNIuV09wt95cRF93HlLbBlSZ/Iz8HXX44ZT1/tGAkwKnW0gDKSSab3I8U+e9' +
824 'LHbC9VXrgAFENzu89MNKNmK5prwv+MPA2HUQPu4Pad3qXmd4+nKc/EUjtg1d' +
825 '/xKGK1Vn6JX3i5ly/rduowez3LxpSAJuIwseum331aQaKC2z2ri++96B8MPU' +
826 'KFXzvV2gVGOe3ZYqmwPaG8y38Tba+OzEh59ygl8ydJJhoI6+R3itPSy0aXUU' +
827 'lMvvAbfCobXD5kBRQ28ysgbDSDOPs3fraXpAKL92QUjsABs58XBz5vka4swu' +
828 'gg/u+ZxaKOqfIm8=',
829 'MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBM' +
830 'MSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMK' +
831 'R2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAw' +
832 'NDJaFw0yMTEyMTUwMDAwNDJaMFQxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVH' +
833 'b29nbGUgVHJ1c3QgU2VydmljZXMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5l' +
834 'dCBBdXRob3JpdHkgRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB' +
835 'AQDKUkvqHv/OJGuo2nIYaNVWXQ5IWi01CXZaz6TIHLGp/lOJ+600/4hbn7vn' +
836 '6AAB3DVzdQOts7G5pH0rJnnOFUAK71G4nzKMfHCGUksW/mona+Y2emJQ2N+a' +
837 'icwJKetPKRSIgAuPOB6Aahh8Hb2XO3h9RUk2T0HNouB2VzxoMXlkyW7XUR5m' +
838 'w6JkLHnA52XDVoRTWkNty5oCINLvGmnRsJ1zouAqYGVQMc/7sy+/EYhALrVJ' +
839 'EA8KbtyX+r8snwU5C1hUrwaW6MWOARa8qBpNQcWTkaIeoYvy/sGIJEmjR0vF' +
840 'EwHdp1cSaWIr6/4g72n7OqXwfinu7ZYW97EfoOSQJeAzAgMBAAGjggEzMIIB' +
841 'LzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF' +
842 'BwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFHfCuFCaZ3Z2sS3C' +
843 'htCDoH6mfrpLMB8GA1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUG' +
844 'CCsGAQUFBwEBBCkwJzAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdv' +
845 'b2cvZ3NyMjAyBgNVHR8EKzApMCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29n' +
846 'L2dzcjIvZ3NyMi5jcmwwPwYDVR0gBDgwNjA0BgZngQwBAgIwKjAoBggrBgEF' +
847 'BQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9yZXBvc2l0b3J5LzANBgkqhkiG9w0B' +
848 'AQsFAAOCAQEAHLeJluRT7bvs26gyAZ8so81trUISd7O45skDUmAge1cnxhG1' +
849 'P2cNmSxbWsoiCt2eux9LSD+PAj2LIYRFHW31/6xoic1k4tbWXkDCjir37xTT' +
850 'NqRAMPUyFRWSdvt+nlPqwnb8Oa2I/maSJukcxDjNSfpDh/Bd1lZNgdd/8cLd' +
851 'sE3+wypufJ9uXO1iQpnh9zbuFIwsIONGl1p3A8CgxkqI/UAih3JaGOqcpcda' +
852 'CIzkBaR9uYQ1X4k2Vg5APRLouzVy7a8IVk6wuy6pm+T7HT4LY8ibS5FEZlfA' +
853 'FLSW8NwsVz9SBK2Vqn1N0PIMn5xA6NZVc7o835DLAFshEWfC7TIe3g==',
854 'MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEg' +
855 'MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkds' +
856 'b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAw' +
857 'WhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg' +
858 'Q0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs' +
859 'U2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o' +
860 'mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe' +
861 '+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1' +
862 'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
863 'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
864 '4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
865 'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
866 'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
867 'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
868 'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
869 'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
870 'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
871 'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
872 'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
873 '9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
874 'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
875 '/H5COEBkEveegeGTLg=='
876 ]);
877 };
878
Paul Lewise407fce2021-02-26 09:59:31879 // Simple check to make sure network throttling is wired up
Blink Reformat4c46d092018-04-07 15:32:37880 // See crbug.com/747724
881 TestSuite.prototype.testOfflineNetworkConditions = async function() {
882 const test = this;
Paul Lewis5a922e72020-01-24 11:58:08883 self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Blink Reformat4c46d092018-04-07 15:32:37884
885 function finishRequest(request) {
886 test.assertEquals(
887 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
888 test.releaseControl();
889 }
890
891 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
892
Sigurd Schneider72ac3562021-03-11 10:35:25893 // Allow more time for this test as it needs to reload the inspected page.
Sigurd Schneider376d2712021-03-12 15:07:51894 test.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:37895 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
896 };
897
898 TestSuite.prototype.testEmulateNetworkConditions = function() {
899 const test = this;
900
901 function testPreset(preset, messages, next) {
902 function onConsoleMessage(event) {
903 const index = messages.indexOf(event.data.messageText);
904 if (index === -1) {
905 test.fail('Unexpected message: ' + event.data.messageText);
906 return;
907 }
908
909 messages.splice(index, 1);
910 if (!messages.length) {
Paul Lewise504fd62020-01-23 16:52:33911 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37912 next();
913 }
914 }
915
Paul Lewise504fd62020-01-23 16:52:33916 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Paul Lewis5a922e72020-01-24 11:58:08917 self.SDK.multitargetNetworkManager.setNetworkConditions(preset);
Blink Reformat4c46d092018-04-07 15:32:37918 }
919
920 test.takeControl();
921 step1();
922
923 function step1() {
924 testPreset(
925 MobileThrottling.networkPresets[2],
926 [
927 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
928 ],
929 step2);
930 }
931
932 function step2() {
933 testPreset(
934 MobileThrottling.networkPresets[1],
935 [
936 'online event: online = true',
Wolfgang Beyerd451ecd2020-10-23 08:35:54937 'connection change event: type = cellular; downlinkMax = 0.3814697265625; effectiveType = 2g'
Blink Reformat4c46d092018-04-07 15:32:37938 ],
939 step3);
940 }
941
942 function step3() {
943 testPreset(
944 MobileThrottling.networkPresets[0],
Wolfgang Beyerd451ecd2020-10-23 08:35:54945 ['connection change event: type = cellular; downlinkMax = 1.373291015625; effectiveType = 3g'],
Blink Reformat4c46d092018-04-07 15:32:37946 test.releaseControl.bind(test));
947 }
948 };
949
950 TestSuite.prototype.testScreenshotRecording = function() {
951 const test = this;
952
953 function performActionsInPage(callback) {
954 let count = 0;
955 const div = document.createElement('div');
956 div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
957 document.body.appendChild(div);
958 requestAnimationFrame(frame);
959 function frame() {
960 const color = [0, 0, 0];
961 color[count % 3] = 255;
962 div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34963 if (++count > 10) {
Blink Reformat4c46d092018-04-07 15:32:37964 requestAnimationFrame(callback);
Tim van der Lippe1d6e57a2019-09-30 11:55:34965 } else {
Blink Reformat4c46d092018-04-07 15:32:37966 requestAnimationFrame(frame);
Tim van der Lippe1d6e57a2019-09-30 11:55:34967 }
Blink Reformat4c46d092018-04-07 15:32:37968 }
969 }
970
Paul Lewis6bcdb182020-01-23 11:08:05971 const captureFilmStripSetting = self.Common.settings.createSetting('timelineCaptureFilmStrip', false);
Blink Reformat4c46d092018-04-07 15:32:37972 captureFilmStripSetting.set(true);
973 test.evaluateInConsole_(performActionsInPage.toString(), function() {});
974 test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
975
976 function onTimelineDone() {
977 captureFilmStripSetting.set(false);
978 const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
979 const frames = filmStripModel.frames();
980 test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
981 loadFrameImages(frames);
982 }
983
984 function loadFrameImages(frames) {
985 const readyImages = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:34986 for (const frame of frames) {
Blink Reformat4c46d092018-04-07 15:32:37987 frame.imageDataPromise().then(onGotImageData);
Tim van der Lippe1d6e57a2019-09-30 11:55:34988 }
Blink Reformat4c46d092018-04-07 15:32:37989
990 function onGotImageData(data) {
991 const image = new Image();
Tim van der Lipped7cfd142021-01-07 12:17:24992 test.assertTrue(Boolean(data), 'No image data for frame');
Blink Reformat4c46d092018-04-07 15:32:37993 image.addEventListener('load', onLoad);
994 image.src = 'data:image/jpg;base64,' + data;
995 }
996
997 function onLoad(event) {
998 readyImages.push(event.target);
Tim van der Lippe1d6e57a2019-09-30 11:55:34999 if (readyImages.length === frames.length) {
Blink Reformat4c46d092018-04-07 15:32:371000 validateImagesAndCompleteTest(readyImages);
Tim van der Lippe1d6e57a2019-09-30 11:55:341001 }
Blink Reformat4c46d092018-04-07 15:32:371002 }
1003 }
1004
1005 function validateImagesAndCompleteTest(images) {
1006 let redCount = 0;
1007 let greenCount = 0;
1008 let blueCount = 0;
1009
1010 const canvas = document.createElement('canvas');
1011 const ctx = canvas.getContext('2d');
1012 for (const image of images) {
1013 test.assertTrue(image.naturalWidth > 10);
1014 test.assertTrue(image.naturalHeight > 10);
1015 canvas.width = image.naturalWidth;
1016 canvas.height = image.naturalHeight;
1017 ctx.drawImage(image, 0, 0);
1018 const data = ctx.getImageData(0, 0, 1, 1);
1019 const color = Array.prototype.join.call(data.data, ',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341020 if (data.data[0] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371021 redCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341022 } else if (data.data[1] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371023 greenCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341024 } else if (data.data[2] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371025 blueCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341026 } else {
Blink Reformat4c46d092018-04-07 15:32:371027 test.fail('Unexpected color: ' + color);
Tim van der Lippe1d6e57a2019-09-30 11:55:341028 }
Blink Reformat4c46d092018-04-07 15:32:371029 }
Paul Lewise407fce2021-02-26 09:59:311030 test.assertTrue(redCount && greenCount && blueCount, 'Color check failed');
Blink Reformat4c46d092018-04-07 15:32:371031 test.releaseControl();
1032 }
1033
1034 test.takeControl();
1035 };
1036
1037 TestSuite.prototype.testSettings = function() {
1038 const test = this;
1039
1040 createSettings();
1041 test.takeControl();
1042 setTimeout(reset, 0);
1043
1044 function createSettings() {
Paul Lewis6bcdb182020-01-23 11:08:051045 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371046 localSetting.set({s: 'local', n: 1});
Paul Lewis6bcdb182020-01-23 11:08:051047 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371048 globalSetting.set({s: 'global', n: 2});
1049 }
1050
1051 function reset() {
Tim van der Lippe99e59b82019-09-30 20:00:591052 Root.Runtime.experiments.clearForTest();
Tim van der Lippe50cfa9b2019-10-01 10:40:581053 Host.InspectorFrontendHost.getPreferences(gotPreferences);
Blink Reformat4c46d092018-04-07 15:32:371054 }
1055
1056 function gotPreferences(prefs) {
1057 Main.Main._instanceForTest._createSettings(prefs);
1058
Paul Lewis6bcdb182020-01-23 11:08:051059 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371060 test.assertEquals('object', typeof localSetting.get());
1061 test.assertEquals('local', localSetting.get().s);
1062 test.assertEquals(1, localSetting.get().n);
Paul Lewis6bcdb182020-01-23 11:08:051063 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371064 test.assertEquals('object', typeof globalSetting.get());
1065 test.assertEquals('global', globalSetting.get().s);
1066 test.assertEquals(2, globalSetting.get().n);
1067 test.releaseControl();
1068 }
1069 };
1070
1071 TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
1072 const test = this;
1073 test.takeControl();
Paul Lewise504fd62020-01-23 16:52:331074 const messages = self.SDK.consoleModel.messages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341075 if (messages.length === 1) {
Blink Reformat4c46d092018-04-07 15:32:371076 checkMessages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341077 } else {
Paul Lewise504fd62020-01-23 16:52:331078 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
Tim van der Lippe1d6e57a2019-09-30 11:55:341079 }
Blink Reformat4c46d092018-04-07 15:32:371080
1081 function checkMessages() {
Paul Lewise504fd62020-01-23 16:52:331082 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371083 test.assertEquals(1, messages.length);
1084 test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
1085 test.releaseControl();
1086 }
1087 };
1088
1089 TestSuite.prototype.testConsoleContextNames = function() {
1090 const test = this;
1091 test.takeControl();
1092 this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
1093
1094 function onExecutionContexts() {
1095 const consoleView = Console.ConsoleView.instance();
1096 const selector = consoleView._consoleContextSelector;
1097 const values = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341098 for (const item of selector._items) {
Blink Reformat4c46d092018-04-07 15:32:371099 values.push(selector.titleFor(item));
Tim van der Lippe1d6e57a2019-09-30 11:55:341100 }
Blink Reformat4c46d092018-04-07 15:32:371101 test.assertEquals('top', values[0]);
1102 test.assertEquals('Simple content script', values[1]);
1103 test.releaseControl();
1104 }
1105 };
1106
1107 TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
1108 const test = this;
Sigurd Schneider5cfca2e2021-03-22 12:09:281109 test.takeControl({slownessFactor: 10});
Paul Lewis4ae5f4f2020-01-23 10:19:331110 self.SDK.targetManager.addModelListener(
Blink Reformat4c46d092018-04-07 15:32:371111 SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
1112
1113 this.evaluateInConsole_(`
1114 let img = document.createElement('img');
1115 img.src = "${url}";
1116 document.body.appendChild(img);
1117 `, () => {});
1118
1119 let count = 0;
1120 function onResponseReceived(event) {
Songtao Xia1e692682020-06-19 13:56:391121 const networkRequest = event.data.request;
Tim van der Lippe1d6e57a2019-09-30 11:55:341122 if (!networkRequest.url().startsWith('http')) {
Blink Reformat4c46d092018-04-07 15:32:371123 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341124 }
Blink Reformat4c46d092018-04-07 15:32:371125 switch (++count) {
1126 case 1: // Original redirect
1127 test.assertEquals(301, networkRequest.statusCode);
1128 test.assertEquals('Moved Permanently', networkRequest.statusText);
1129 test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
1130 break;
1131
1132 case 2: // HSTS internal redirect
1133 test.assertTrue(networkRequest.url().startsWith('http://'));
Blink Reformat4c46d092018-04-07 15:32:371134 test.assertEquals(307, networkRequest.statusCode);
1135 test.assertEquals('Internal Redirect', networkRequest.statusText);
1136 test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
1137 test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
1138 break;
1139
1140 case 3: // Final response
1141 test.assertTrue(networkRequest.url().startsWith('https://'));
1142 test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
1143 test.assertEquals(200, networkRequest.statusCode);
1144 test.assertEquals('OK', networkRequest.statusText);
1145 test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
1146 test.releaseControl();
1147 }
1148 }
1149 };
1150
1151 TestSuite.prototype.testDOMWarnings = function() {
Paul Lewise504fd62020-01-23 16:52:331152 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371153 this.assertEquals(1, messages.length);
1154 const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
1155 this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
1156 };
1157
1158 TestSuite.prototype.waitForTestResultsInConsole = function() {
Paul Lewise504fd62020-01-23 16:52:331159 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371160 for (let i = 0; i < messages.length; ++i) {
1161 const text = messages[i].messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341162 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371163 return;
Mathias Bynensf06e8c02020-02-28 13:58:281164 }
1165 if (/^FAIL/.test(text)) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341166 this.fail(text);
1167 } // This will throw.
Blink Reformat4c46d092018-04-07 15:32:371168 }
1169 // Neither PASS nor FAIL, so wait for more messages.
1170 function onConsoleMessage(event) {
1171 const text = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341172 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371173 this.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:341174 } else if (/^FAIL/.test(text)) {
Blink Reformat4c46d092018-04-07 15:32:371175 this.fail(text);
Tim van der Lippe1d6e57a2019-09-30 11:55:341176 }
Blink Reformat4c46d092018-04-07 15:32:371177 }
1178
Paul Lewise504fd62020-01-23 16:52:331179 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Sigurd Schneiderbf7f1602021-03-18 07:51:571180 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:371181 };
1182
Andrey Kosyakova08cb9b2020-04-01 21:49:521183 TestSuite.prototype.waitForTestResultsAsMessage = function() {
1184 const onMessage = event => {
1185 if (!event.data.testOutput) {
1186 return;
1187 }
1188 top.removeEventListener('message', onMessage);
1189 const text = event.data.testOutput;
1190 if (text === 'PASS') {
1191 this.releaseControl();
1192 } else {
1193 this.fail(text);
1194 }
1195 };
1196 top.addEventListener('message', onMessage);
1197 this.takeControl();
1198 };
1199
Blink Reformat4c46d092018-04-07 15:32:371200 TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
1201 const original = receiver[methodName];
1202 if (typeof original !== 'function') {
Mathias Bynens23ee1aa2020-03-02 12:06:381203 this.fail(`TestSuite._overrideMethod: ${methodName} is not a function`);
Blink Reformat4c46d092018-04-07 15:32:371204 return;
1205 }
1206 receiver[methodName] = function() {
1207 let value;
1208 try {
1209 value = original.apply(receiver, arguments);
1210 } finally {
1211 receiver[methodName] = original;
1212 }
1213 override.apply(original, arguments);
1214 return value;
1215 };
1216 };
1217
1218 TestSuite.prototype.startTimeline = function(callback) {
1219 const test = this;
1220 this.showPanel('timeline').then(function() {
1221 const timeline = UI.panels.timeline;
1222 test._overrideMethod(timeline, '_recordingStarted', callback);
1223 timeline._toggleRecording();
1224 });
1225 };
1226
1227 TestSuite.prototype.stopTimeline = function(callback) {
1228 const timeline = UI.panels.timeline;
1229 this._overrideMethod(timeline, 'loadingComplete', callback);
1230 timeline._toggleRecording();
1231 };
1232
1233 TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
1234 const callback = arguments[arguments.length - 1];
1235 const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
1236 const argsString = arguments.length < 3 ?
1237 '' :
1238 Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
1239 this.evaluateInConsole_(
1240 `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
Paul Lewise504fd62020-01-23 16:52:331241 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371242
1243 function onConsoleMessage(event) {
1244 const text = event.data.messageText;
1245 if (text === doneMessage) {
Paul Lewise504fd62020-01-23 16:52:331246 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371247 callback();
1248 }
1249 }
1250 };
1251
1252 TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
1253 const test = this;
1254
1255 this.startTimeline(onRecordingStarted);
1256
1257 function onRecordingStarted() {
1258 test.invokePageFunctionAsync(functionName, pageActionsDone);
1259 }
1260
1261 function pageActionsDone() {
1262 test.stopTimeline(callback);
1263 }
1264 };
1265
1266 TestSuite.prototype.enableExperiment = function(name) {
Tim van der Lippe99e59b82019-09-30 20:00:591267 Root.Runtime.experiments.enableForTest(name);
Blink Reformat4c46d092018-04-07 15:32:371268 };
1269
1270 TestSuite.prototype.checkInputEventsPresent = function() {
1271 const expectedEvents = new Set(arguments);
1272 const model = UI.panels.timeline._performanceModel.timelineModel();
1273 const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
1274 const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
1275 const prefix = 'InputLatency::';
1276 for (const e of input) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341277 if (!e.name.startsWith(prefix)) {
Blink Reformat4c46d092018-04-07 15:32:371278 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341279 }
1280 if (e.steps.length < 2) {
Blink Reformat4c46d092018-04-07 15:32:371281 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341282 }
Blink Reformat4c46d092018-04-07 15:32:371283 if (e.name.startsWith(prefix + 'Mouse') &&
Tim van der Lippe1d6e57a2019-09-30 11:55:341284 typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') {
Blink Reformat4c46d092018-04-07 15:32:371285 throw `Missing timeWaitingForMainThread on ${e.name}`;
Tim van der Lippe1d6e57a2019-09-30 11:55:341286 }
Blink Reformat4c46d092018-04-07 15:32:371287 expectedEvents.delete(e.name.substr(prefix.length));
1288 }
Tim van der Lippe1d6e57a2019-09-30 11:55:341289 if (expectedEvents.size) {
Blink Reformat4c46d092018-04-07 15:32:371290 throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341291 }
Blink Reformat4c46d092018-04-07 15:32:371292 };
1293
1294 TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
1295 this.takeControl();
1296 await self.runtime.loadModulePromise('elements');
Tim van der Lippe1d6e57a2019-09-30 11:55:341297 if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) {
Blink Reformat4c46d092018-04-07 15:32:371298 await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f));
Tim van der Lippe1d6e57a2019-09-30 11:55:341299 }
Blink Reformat4c46d092018-04-07 15:32:371300 this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest);
1301 this.releaseControl();
1302 };
1303
Andrey Lushnikovd92662b2018-05-09 03:57:001304 TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
1305 this.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331306 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikovd92662b2018-05-09 03:57:001307 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1308 const response1 = await targetAgent.invoke_getBrowserContexts();
1309 this.assertEquals(response1.browserContextIds.length, 1);
1310 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1311 const response2 = await targetAgent.invoke_getBrowserContexts();
1312 this.assertEquals(response2.browserContextIds.length, 0);
1313 this.releaseControl();
1314 };
1315
Peter Marshalld2f58c32020-04-21 13:23:131316 TestSuite.prototype.testNewWindowFromBrowserContext = async function(url) {
1317 this.takeControl();
1318 // Create a BrowserContext.
1319 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
1320 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1321
1322 // Cause a Browser to be created with the temp profile.
Sigurd Schneider3fec5ca2021-05-14 10:18:341323 const {targetId} = await targetAgent.invoke_createTarget(
1324 {url: 'data:text/html,<!DOCTYPE html>', browserContextId, newWindow: true});
Peter Marshalld2f58c32020-04-21 13:23:131325 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
1326
1327 // Destroy the temp profile.
1328 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1329
1330 this.releaseControl();
1331 };
1332
Andrey Lushnikov0eea25e2018-04-24 22:29:511333 TestSuite.prototype.testCreateBrowserContext = async function(url) {
1334 this.takeControl();
1335 const browserContextIds = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331336 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov0eea25e2018-04-24 22:29:511337
1338 const target1 = await createIsolatedTarget(url);
1339 const target2 = await createIsolatedTarget(url);
1340
Andrey Lushnikov07477b42018-05-08 22:00:521341 const response = await targetAgent.invoke_getBrowserContexts();
1342 this.assertEquals(response.browserContextIds.length, 2);
1343 this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
1344 this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
1345
Andrey Lushnikov0eea25e2018-04-24 22:29:511346 await evalCode(target1, 'localStorage.setItem("page1", "page1")');
1347 await evalCode(target2, 'localStorage.setItem("page2", "page2")');
1348
1349 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
1350 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
1351 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
1352 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
1353
Andrey Lushnikov69499702018-05-08 18:20:471354 const removedTargets = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331355 self.SDK.targetManager.observeTargets(
1356 {targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
Andrey Lushnikov69499702018-05-08 18:20:471357 await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
1358 this.assertEquals(removedTargets.length, 2);
1359 this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
1360 this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
Andrey Lushnikov0eea25e2018-04-24 22:29:511361
1362 this.releaseControl();
1363
1364 /**
1365 * @param {string} url
1366 * @return {!Promise<!SDK.Target>}
1367 */
1368 async function createIsolatedTarget(url) {
Andrey Lushnikov0eea25e2018-04-24 22:29:511369 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1370 browserContextIds.push(browserContextId);
1371
1372 const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
Dmitry Gozman99d7a6c2018-11-12 17:55:111373 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
Andrey Lushnikov0eea25e2018-04-24 22:29:511374
Paul Lewis4ae5f4f2020-01-23 10:19:331375 const target = self.SDK.targetManager.targets().find(target => target.id() === targetId);
Andrey Lushnikov0eea25e2018-04-24 22:29:511376 const pageAgent = target.pageAgent();
1377 await pageAgent.invoke_enable();
1378 await pageAgent.invoke_navigate({url});
1379 return target;
1380 }
1381
Andrey Lushnikov0eea25e2018-04-24 22:29:511382 async function disposeBrowserContext(browserContextId) {
Paul Lewis4ae5f4f2020-01-23 10:19:331383 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov69499702018-05-08 18:20:471384 await targetAgent.invoke_disposeBrowserContext({browserContextId});
Andrey Lushnikov0eea25e2018-04-24 22:29:511385 }
1386
1387 async function evalCode(target, code) {
1388 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1389 }
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) {
1398 const code = `
1399 (function() {
1400 var result = window.logs.join(' ');
1401 window.logs = [];
1402 return result;
1403 })()
1404 `;
1405 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1406 }
1407
1408 let parentFrameOutput;
1409 let childFrameOutput;
1410
Paul Lewis4ae5f4f2020-01-23 10:19:331411 const inputAgent = self.SDK.targetManager.mainTarget().inputAgent();
1412 const runtimeAgent = self.SDK.targetManager.mainTarget().runtimeAgent();
Blink Reformat4c46d092018-04-07 15:32:371413 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
1414 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
1415 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
1416 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
1417 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
1418 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
1419 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:331420 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371421 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:331422 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371423
1424
1425 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
Mathias Bynens23ee1aa2020-03-02 12:06:381426 await runtimeAgent.invoke_evaluate({expression: "document.querySelector('iframe').focus()"});
Blink Reformat4c46d092018-04-07 15:32:371427 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
1428 parentFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331429 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371430 childFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331431 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371432
1433 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
1434 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1435 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
1436 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1437 parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
Paul Lewis4ae5f4f2020-01-23 10:19:331438 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371439 childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
Paul Lewis4ae5f4f2020-01-23 10:19:331440 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371441
1442 this.releaseControl();
1443 };
1444
Andrey Kosyakov4f7fb052019-03-19 15:53:431445 TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
Blink Reformat4c46d092018-04-07 15:32:371446 const test = this;
1447 const loggedHeaders = new Set(['cache-control', 'pragma']);
1448 function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
1449 return new Promise(fulfill => {
1450 Host.ResourceLoader.load(url, headers, callback);
1451
Sigurd Schneidera327cde2020-01-21 15:48:121452 function callback(success, headers, content, errorDescription) {
1453 test.assertEquals(expectedStatus, errorDescription.statusCode);
Blink Reformat4c46d092018-04-07 15:32:371454
1455 const headersArray = [];
1456 for (const name in headers) {
1457 const nameLower = name.toLowerCase();
Tim van der Lippe1d6e57a2019-09-30 11:55:341458 if (loggedHeaders.has(nameLower)) {
Blink Reformat4c46d092018-04-07 15:32:371459 headersArray.push(nameLower);
Tim van der Lippe1d6e57a2019-09-30 11:55:341460 }
Blink Reformat4c46d092018-04-07 15:32:371461 }
1462 headersArray.sort();
1463 test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
1464 test.assertEquals(expectedContent, content);
1465 fulfill();
1466 }
1467 });
1468 }
1469
Sigurd Schneider5cfca2e2021-03-22 12:09:281470 this.takeControl({slownessFactor: 10});
Blink Reformat4c46d092018-04-07 15:32:371471 await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
1472 await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
1473 await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
1474 await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
1475
Paul Lewis4ae5f4f2020-01-23 10:19:331476 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Blink Reformat4c46d092018-04-07 15:32:371477 expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
1478 {credentials: 'include'})`,
1479 awaitPromise: true
1480 });
1481 await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
1482
Paul Lewis4ae5f4f2020-01-23 10:19:331483 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Andrey Kosyakov73081cc2019-01-08 03:50:591484 expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
1485 {credentials: 'include'})`,
1486 awaitPromise: true
1487 });
1488 await testCase(
1489 baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
Andrey Kosyakov4f7fb052019-03-19 15:53:431490 await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
Changhao Hanaf7ba132021-05-10 12:44:541491 await testCase(fileURL, undefined, 200, [], '<!DOCTYPE html>\n<html>\n<body>\nDummy page.\n</body>\n</html>\n');
Rob Paveza30df0482019-10-09 23:15:491492 await testCase(fileURL + 'thisfileshouldnotbefound', undefined, 404, [], '');
Andrey Kosyakov73081cc2019-01-08 03:50:591493
Blink Reformat4c46d092018-04-07 15:32:371494 this.releaseControl();
1495 };
1496
Joey Arhar723d5b52019-04-19 01:31:391497 TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
1498 this.takeControl();
1499
1500 const testUserAgent = 'test user agent';
Paul Lewis5a922e72020-01-24 11:58:081501 self.SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
Joey Arhar723d5b52019-04-19 01:31:391502
1503 function onRequestUpdated(event) {
1504 const request = event.data;
Tim van der Lippe1d6e57a2019-09-30 11:55:341505 if (request.resourceType() !== Common.resourceTypes.WebSocket) {
Joey Arhar723d5b52019-04-19 01:31:391506 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341507 }
1508 if (!request.requestHeadersText()) {
Joey Arhar723d5b52019-04-19 01:31:391509 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341510 }
Joey Arhar723d5b52019-04-19 01:31:391511
1512 let actualUserAgent = 'no user-agent header';
1513 for (const {name, value} of request.requestHeaders()) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341514 if (name.toLowerCase() === 'user-agent') {
Joey Arhar723d5b52019-04-19 01:31:391515 actualUserAgent = value;
Tim van der Lippe1d6e57a2019-09-30 11:55:341516 }
Joey Arhar723d5b52019-04-19 01:31:391517 }
1518 this.assertEquals(testUserAgent, actualUserAgent);
1519 this.releaseControl();
1520 }
Paul Lewis4ae5f4f2020-01-23 10:19:331521 self.SDK.targetManager.addModelListener(
Joey Arhar723d5b52019-04-19 01:31:391522 SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
1523
1524 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
1525 };
1526
Blink Reformat4c46d092018-04-07 15:32:371527 /**
1528 * Serializes array of uiSourceCodes to string.
1529 * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
1530 * @return {string}
1531 */
1532 TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
1533 const names = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341534 for (let i = 0; i < uiSourceCodes.length; i++) {
Blink Reformat4c46d092018-04-07 15:32:371535 names.push('"' + uiSourceCodes[i].url() + '"');
Tim van der Lippe1d6e57a2019-09-30 11:55:341536 }
Blink Reformat4c46d092018-04-07 15:32:371537 return names.join(',');
1538 };
1539
1540 /**
1541 * Returns all loaded non anonymous uiSourceCodes.
1542 * @return {!Array.<!Workspace.UISourceCode>}
1543 */
1544 TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
1545 /**
1546 * @param {!Workspace.UISourceCode} uiSourceCode
1547 */
1548 function filterOutService(uiSourceCode) {
1549 return !uiSourceCode.project().isServiceProject();
1550 }
1551
Paul Lewis10e83a92020-01-23 14:07:581552 const uiSourceCodes = self.Workspace.workspace.uiSourceCodes();
Blink Reformat4c46d092018-04-07 15:32:371553 return uiSourceCodes.filter(filterOutService);
1554 };
1555
1556 /*
1557 * Evaluates the code in the console as if user typed it manually and invokes
1558 * the callback when the result message is received and added to the console.
1559 * @param {string} code
1560 * @param {function(string)} callback
1561 */
1562 TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
1563 function innerEvaluate() {
Paul Lewisd9907342020-01-24 13:49:471564 self.UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371565 const consoleView = Console.ConsoleView.instance();
1566 consoleView._prompt._appendCommand(code);
1567
1568 this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) {
1569 callback(viewMessage.toMessageElement().deepTextContent());
1570 }.bind(this));
1571 }
1572
1573 function showConsoleAndEvaluate() {
Paul Lewis04ccecc2020-01-22 17:15:141574 self.Common.console.showPromise().then(innerEvaluate.bind(this));
Blink Reformat4c46d092018-04-07 15:32:371575 }
1576
Paul Lewisd9907342020-01-24 13:49:471577 if (!self.UI.context.flavor(SDK.ExecutionContext)) {
1578 self.UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371579 return;
1580 }
1581 showConsoleAndEvaluate.call(this);
1582 };
1583
1584 /**
1585 * Checks that all expected scripts are present in the scripts list
1586 * in the Scripts panel.
1587 * @param {!Array.<string>} expected Regular expressions describing
1588 * expected script names.
1589 * @return {boolean} Whether all the scripts are in "scripts-files" select
1590 * box
1591 */
1592 TestSuite.prototype._scriptsAreParsed = function(expected) {
1593 const uiSourceCodes = this.nonAnonymousUISourceCodes_();
1594 // Check that at least all the expected scripts are present.
1595 const missing = expected.slice(0);
1596 for (let i = 0; i < uiSourceCodes.length; ++i) {
1597 for (let j = 0; j < missing.length; ++j) {
1598 if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
1599 missing.splice(j, 1);
1600 break;
1601 }
1602 }
1603 }
1604 return missing.length === 0;
1605 };
1606
1607 /**
1608 * Waits for script pause, checks expectations, and invokes the callback.
1609 * @param {function():void} callback
1610 */
1611 TestSuite.prototype._waitForScriptPause = function(callback) {
1612 this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback);
1613 };
1614
1615 /**
1616 * Waits until all the scripts are parsed and invokes the callback.
1617 */
1618 TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
1619 const test = this;
1620
1621 function waitForAllScripts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341622 if (test._scriptsAreParsed(expectedScripts)) {
Blink Reformat4c46d092018-04-07 15:32:371623 callback();
Tim van der Lippe1d6e57a2019-09-30 11:55:341624 } else {
Blink Reformat4c46d092018-04-07 15:32:371625 test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts);
Tim van der Lippe1d6e57a2019-09-30 11:55:341626 }
Blink Reformat4c46d092018-04-07 15:32:371627 }
1628
1629 waitForAllScripts();
1630 };
1631
1632 TestSuite.prototype._waitForTargets = function(n, callback) {
1633 checkTargets.call(this);
1634
1635 function checkTargets() {
Paul Lewis4ae5f4f2020-01-23 10:19:331636 if (self.SDK.targetManager.targets().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371637 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341638 } else {
Blink Reformat4c46d092018-04-07 15:32:371639 this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341640 }
Blink Reformat4c46d092018-04-07 15:32:371641 }
1642 };
1643
1644 TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
Paul Lewis4ae5f4f2020-01-23 10:19:331645 const runtimeModel = self.SDK.targetManager.mainTarget().model(SDK.RuntimeModel);
Blink Reformat4c46d092018-04-07 15:32:371646 checkForExecutionContexts.call(this);
1647
1648 function checkForExecutionContexts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341649 if (runtimeModel.executionContexts().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371650 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341651 } else {
Blink Reformat4c46d092018-04-07 15:32:371652 this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341653 }
Blink Reformat4c46d092018-04-07 15:32:371654 }
1655 };
1656
1657
1658 window.uiTests = new TestSuite(window.domAutomationController);
1659})(window);