blob: 85f8c913478a53626d95e0f143e6814a0cf18148 [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
35 * and are executed by the devtools_sanity_unittest.cc as a part of the
36 * Interactive UI Test suite.
37 * FIXME: change field naming style to use trailing underscore.
38 */
39
40(function createTestSuite(window) {
41
42 /**
43 * @unrestricted
44 */
45 const TestSuite = class {
46 /**
47 * Test suite for interactive UI tests.
48 * @param {Object} domAutomationController DomAutomationController instance.
49 */
50 constructor(domAutomationController) {
51 this.domAutomationController_ = domAutomationController;
52 this.controlTaken_ = false;
53 this.timerId_ = -1;
54 this._asyncInvocationId = 0;
55 }
56
57 /**
58 * Key event with given key identifier.
59 */
60 static createKeyEvent(key) {
61 return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key});
62 }
63 };
64
65 /**
66 * Reports test failure.
67 * @param {string} message Failure description.
68 */
69 TestSuite.prototype.fail = function(message) {
Tim van der Lippe1d6e57a2019-09-30 11:55:3470 if (this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:3771 this.reportFailure_(message);
Tim van der Lippe1d6e57a2019-09-30 11:55:3472 } else {
Blink Reformat4c46d092018-04-07 15:32:3773 throw message;
Tim van der Lippe1d6e57a2019-09-30 11:55:3474 }
Blink Reformat4c46d092018-04-07 15:32:3775 };
76
77 /**
78 * Equals assertion tests that expected === actual.
79 * @param {!Object|boolean} expected Expected object.
80 * @param {!Object|boolean} actual Actual object.
81 * @param {string} opt_message User message to print if the test fails.
82 */
83 TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
84 if (expected !== actual) {
85 let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
Tim van der Lippe1d6e57a2019-09-30 11:55:3486 if (opt_message) {
Blink Reformat4c46d092018-04-07 15:32:3787 message = opt_message + '(' + message + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:3488 }
Blink Reformat4c46d092018-04-07 15:32:3789 this.fail(message);
90 }
91 };
92
93 /**
94 * True assertion tests that value == true.
95 * @param {!Object} value Actual object.
96 * @param {string} opt_message User message to print if the test fails.
97 */
98 TestSuite.prototype.assertTrue = function(value, opt_message) {
99 this.assertEquals(true, !!value, opt_message);
100 };
101
102 /**
103 * Takes control over execution.
104 */
105 TestSuite.prototype.takeControl = function() {
106 this.controlTaken_ = true;
107 // Set up guard timer.
108 const self = this;
109 this.timerId_ = setTimeout(function() {
110 self.reportFailure_('Timeout exceeded: 20 sec');
111 }, 20000);
112 };
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.
349 this.takeControl();
350 };
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
410 this.takeControl();
411 };
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
430 this.takeControl();
431 };
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
454 this.takeControl();
455 };
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
489 this.takeControl();
490 };
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() {
Paul Lewise504fd62020-01-23 16:52:33527 return self.SDK.consoleModel.messages().filter(a => a.source !== SDK.ConsoleMessage.MessageSource.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 Lippe1d6e57a2019-09-30 11:55:34538 if (event && event.data.source === SDK.ConsoleMessage.MessageSource.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(
653 '"' + JSON.stringify(metrics) + '"', consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params));
654 callback();
655 }
656 }
657
658 function step1() {
659 testOverrides(
660 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
661 {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
662 }
663
664 function step2() {
665 testOverrides(
666 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
667 {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
668 }
669
670 function step3() {
671 testOverrides(
672 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
673 {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
674 }
675
676 function step4() {
677 testOverrides(
678 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
679 {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
680 }
681
682 function finish() {
683 test.releaseControl();
684 }
685
686 test.takeControl();
687 step1();
688 };
689
690 TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
691 const test = this;
692 let receivedReady = false;
693
694 function signalToShowAutofill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33695 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37696 {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Paul Lewis4ae5f4f2020-01-23 10:19:33697 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37698 {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
699 }
700
701 function selectTopAutoFill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33702 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37703 {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
Paul Lewis4ae5f4f2020-01-23 10:19:33704 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37705 {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
706
707 test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
708 }
709
710 function onResultOfInput(value) {
711 // Console adds "" around the response.
712 test.assertEquals('"Abbf"', value);
713 test.releaseControl();
714 }
715
716 function onConsoleMessage(event) {
717 const message = event.data.messageText;
718 if (message === 'ready' && !receivedReady) {
719 receivedReady = true;
720 signalToShowAutofill();
721 }
722 // This log comes from the browser unittest code.
Tim van der Lippe1d6e57a2019-09-30 11:55:34723 if (message === 'didShowSuggestions') {
Blink Reformat4c46d092018-04-07 15:32:37724 selectTopAutoFill();
Tim van der Lippe1d6e57a2019-09-30 11:55:34725 }
Blink Reformat4c46d092018-04-07 15:32:37726 }
727
728 this.takeControl();
729
730 // It is possible for the ready console messagage to be already received but not handled
731 // or received later. This ensures we can catch both cases.
Paul Lewise504fd62020-01-23 16:52:33732 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37733
Paul Lewise504fd62020-01-23 16:52:33734 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:37735 if (messages.length) {
736 const text = messages[0].messageText;
737 this.assertEquals('ready', text);
738 signalToShowAutofill();
739 }
740 };
741
Pâris MEULEMANd4709cb2019-04-17 08:32:48742 TestSuite.prototype.testKeyEventUnhandled = function() {
743 function onKeyEventUnhandledKeyDown(event) {
744 this.assertEquals('keydown', event.data.type);
745 this.assertEquals('F8', event.data.key);
746 this.assertEquals(119, event.data.keyCode);
747 this.assertEquals(0, event.data.modifiers);
748 this.assertEquals('', event.data.code);
Tim van der Lippe50cfa9b2019-10-01 10:40:58749 Host.InspectorFrontendHost.events.removeEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44750 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Tim van der Lippe50cfa9b2019-10-01 10:40:58751 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44752 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33753 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48754 {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
755 }
756 function onKeyEventUnhandledKeyUp(event) {
757 this.assertEquals('keyup', 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('F8', event.data.code);
762 this.releaseControl();
763 }
764 this.takeControl();
Tim van der Lippe50cfa9b2019-10-01 10:40:58765 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44766 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33767 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48768 {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
769 };
770
Jack Lynchb514f9f2020-06-19 21:16:45771 // Tests that the keys that are forwarded from the browser update
772 // when their shortcuts change
773 TestSuite.prototype.testForwardedKeysChanged = function() {
Jack Lynch080a0fd2020-06-15 19:55:19774 this.takeControl();
775
776 this.addSniffer(self.UI.shortcutRegistry, '_registerBindings', () => {
777 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
778 {type: 'rawKeyDown', key: 'F1', windowsVirtualKeyCode: 112, nativeVirtualKeyCode: 112});
779 });
780 this.addSniffer(self.UI.shortcutRegistry, 'handleKey', key => {
781 this.assertEquals(112, key);
782 this.releaseControl();
783 });
784
785 self.Common.settings.moduleSetting('activeKeybindSet').set('vsCode');
786 };
787
Blink Reformat4c46d092018-04-07 15:32:37788 TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33789 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37790 {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
Paul Lewis4ae5f4f2020-01-23 10:19:33791 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37792 {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
793 };
794
Pâris MEULEMANd81f35f2019-05-07 09:04:34795 // Check that showing the certificate viewer does not crash, crbug.com/954874
796 TestSuite.prototype.testShowCertificate = function() {
Tim van der Lippe50cfa9b2019-10-01 10:40:58797 Host.InspectorFrontendHost.showCertificateViewer([
Pâris MEULEMANd81f35f2019-05-07 09:04:34798 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
799 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
800 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
801 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
802 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
803 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
804 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
805 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
806 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
807 'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
808 'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
809 'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOcIA7AVR/Ck22Uj8X' +
810 'UOECercjUrKdDyaAPcLp2TThAgMBAAGjggHZMIIB1TATBgNVHSUEDDAKBggr' +
811 'BgEFBQcDATCBrwYDVR0RBIGnMIGkgg0qLmFwcHNwb3QuY29tggsqLmEucnVu' +
812 'LmFwcIIVKi50aGlua3dpdGhnb29nbGUuY29tghAqLndpdGhnb29nbGUuY29t' +
813 'ghEqLndpdGh5b3V0dWJlLmNvbYILYXBwc3BvdC5jb22CB3J1bi5hcHCCE3Ro' +
814 'aW5rd2l0aGdvb2dsZS5jb22CDndpdGhnb29nbGUuY29tgg93aXRoeW91dHVi' +
815 'ZS5jb20waAYIKwYBBQUHAQEEXDBaMC0GCCsGAQUFBzAChiFodHRwOi8vcGtp' +
816 'Lmdvb2cvZ3NyMi9HVFNHSUFHMy5jcnQwKQYIKwYBBQUHMAGGHWh0dHA6Ly9v' +
817 'Y3NwLnBraS5nb29nL0dUU0dJQUczMB0GA1UdDgQWBBTGkpE5o0H9+Wjc05rF' +
818 'hNQiYDjBFjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFHfCuFCaZ3Z2sS3C' +
819 'htCDoH6mfrpLMCEGA1UdIAQaMBgwDAYKKwYBBAHWeQIFAzAIBgZngQwBAgIw' +
820 'MQYDVR0fBCowKDAmoCSgIoYgaHR0cDovL2NybC5wa2kuZ29vZy9HVFNHSUFH' +
821 'My5jcmwwDQYJKoZIhvcNAQELBQADggEBALqoYGqWtJW/6obEzY+ehsgfyXb+' +
822 'qNIuV09wt95cRF93HlLbBlSZ/Iz8HXX44ZT1/tGAkwKnW0gDKSSab3I8U+e9' +
823 'LHbC9VXrgAFENzu89MNKNmK5prwv+MPA2HUQPu4Pad3qXmd4+nKc/EUjtg1d' +
824 '/xKGK1Vn6JX3i5ly/rduowez3LxpSAJuIwseum331aQaKC2z2ri++96B8MPU' +
825 'KFXzvV2gVGOe3ZYqmwPaG8y38Tba+OzEh59ygl8ydJJhoI6+R3itPSy0aXUU' +
826 'lMvvAbfCobXD5kBRQ28ysgbDSDOPs3fraXpAKL92QUjsABs58XBz5vka4swu' +
827 'gg/u+ZxaKOqfIm8=',
828 'MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBM' +
829 'MSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMK' +
830 'R2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAw' +
831 'NDJaFw0yMTEyMTUwMDAwNDJaMFQxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVH' +
832 'b29nbGUgVHJ1c3QgU2VydmljZXMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5l' +
833 'dCBBdXRob3JpdHkgRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB' +
834 'AQDKUkvqHv/OJGuo2nIYaNVWXQ5IWi01CXZaz6TIHLGp/lOJ+600/4hbn7vn' +
835 '6AAB3DVzdQOts7G5pH0rJnnOFUAK71G4nzKMfHCGUksW/mona+Y2emJQ2N+a' +
836 'icwJKetPKRSIgAuPOB6Aahh8Hb2XO3h9RUk2T0HNouB2VzxoMXlkyW7XUR5m' +
837 'w6JkLHnA52XDVoRTWkNty5oCINLvGmnRsJ1zouAqYGVQMc/7sy+/EYhALrVJ' +
838 'EA8KbtyX+r8snwU5C1hUrwaW6MWOARa8qBpNQcWTkaIeoYvy/sGIJEmjR0vF' +
839 'EwHdp1cSaWIr6/4g72n7OqXwfinu7ZYW97EfoOSQJeAzAgMBAAGjggEzMIIB' +
840 'LzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF' +
841 'BwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFHfCuFCaZ3Z2sS3C' +
842 'htCDoH6mfrpLMB8GA1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUG' +
843 'CCsGAQUFBwEBBCkwJzAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdv' +
844 'b2cvZ3NyMjAyBgNVHR8EKzApMCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29n' +
845 'L2dzcjIvZ3NyMi5jcmwwPwYDVR0gBDgwNjA0BgZngQwBAgIwKjAoBggrBgEF' +
846 'BQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9yZXBvc2l0b3J5LzANBgkqhkiG9w0B' +
847 'AQsFAAOCAQEAHLeJluRT7bvs26gyAZ8so81trUISd7O45skDUmAge1cnxhG1' +
848 'P2cNmSxbWsoiCt2eux9LSD+PAj2LIYRFHW31/6xoic1k4tbWXkDCjir37xTT' +
849 'NqRAMPUyFRWSdvt+nlPqwnb8Oa2I/maSJukcxDjNSfpDh/Bd1lZNgdd/8cLd' +
850 'sE3+wypufJ9uXO1iQpnh9zbuFIwsIONGl1p3A8CgxkqI/UAih3JaGOqcpcda' +
851 'CIzkBaR9uYQ1X4k2Vg5APRLouzVy7a8IVk6wuy6pm+T7HT4LY8ibS5FEZlfA' +
852 'FLSW8NwsVz9SBK2Vqn1N0PIMn5xA6NZVc7o835DLAFshEWfC7TIe3g==',
853 'MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEg' +
854 'MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkds' +
855 'b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAw' +
856 'WhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg' +
857 'Q0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs' +
858 'U2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o' +
859 'mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe' +
860 '+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1' +
861 'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
862 'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
863 '4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
864 'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
865 'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
866 'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
867 'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
868 'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
869 'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
870 'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
871 'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
872 '9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
873 'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
874 '/H5COEBkEveegeGTLg=='
875 ]);
876 };
877
Blink Reformat4c46d092018-04-07 15:32:37878 // Simple sanity check to make sure network throttling is wired up
879 // See crbug.com/747724
880 TestSuite.prototype.testOfflineNetworkConditions = async function() {
881 const test = this;
Paul Lewis5a922e72020-01-24 11:58:08882 self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Blink Reformat4c46d092018-04-07 15:32:37883
884 function finishRequest(request) {
885 test.assertEquals(
886 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
887 test.releaseControl();
888 }
889
890 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
891
892 test.takeControl();
893 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
894 };
895
896 TestSuite.prototype.testEmulateNetworkConditions = function() {
897 const test = this;
898
899 function testPreset(preset, messages, next) {
900 function onConsoleMessage(event) {
901 const index = messages.indexOf(event.data.messageText);
902 if (index === -1) {
903 test.fail('Unexpected message: ' + event.data.messageText);
904 return;
905 }
906
907 messages.splice(index, 1);
908 if (!messages.length) {
Paul Lewise504fd62020-01-23 16:52:33909 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37910 next();
911 }
912 }
913
Paul Lewise504fd62020-01-23 16:52:33914 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Paul Lewis5a922e72020-01-24 11:58:08915 self.SDK.multitargetNetworkManager.setNetworkConditions(preset);
Blink Reformat4c46d092018-04-07 15:32:37916 }
917
918 test.takeControl();
919 step1();
920
921 function step1() {
922 testPreset(
923 MobileThrottling.networkPresets[2],
924 [
925 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
926 ],
927 step2);
928 }
929
930 function step2() {
931 testPreset(
932 MobileThrottling.networkPresets[1],
933 [
934 'online event: online = true',
Wolfgang Beyerd451ecd2020-10-23 08:35:54935 'connection change event: type = cellular; downlinkMax = 0.3814697265625; effectiveType = 2g'
Blink Reformat4c46d092018-04-07 15:32:37936 ],
937 step3);
938 }
939
940 function step3() {
941 testPreset(
942 MobileThrottling.networkPresets[0],
Wolfgang Beyerd451ecd2020-10-23 08:35:54943 ['connection change event: type = cellular; downlinkMax = 1.373291015625; effectiveType = 3g'],
Blink Reformat4c46d092018-04-07 15:32:37944 test.releaseControl.bind(test));
945 }
946 };
947
948 TestSuite.prototype.testScreenshotRecording = function() {
949 const test = this;
950
951 function performActionsInPage(callback) {
952 let count = 0;
953 const div = document.createElement('div');
954 div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
955 document.body.appendChild(div);
956 requestAnimationFrame(frame);
957 function frame() {
958 const color = [0, 0, 0];
959 color[count % 3] = 255;
960 div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34961 if (++count > 10) {
Blink Reformat4c46d092018-04-07 15:32:37962 requestAnimationFrame(callback);
Tim van der Lippe1d6e57a2019-09-30 11:55:34963 } else {
Blink Reformat4c46d092018-04-07 15:32:37964 requestAnimationFrame(frame);
Tim van der Lippe1d6e57a2019-09-30 11:55:34965 }
Blink Reformat4c46d092018-04-07 15:32:37966 }
967 }
968
Paul Lewis6bcdb182020-01-23 11:08:05969 const captureFilmStripSetting = self.Common.settings.createSetting('timelineCaptureFilmStrip', false);
Blink Reformat4c46d092018-04-07 15:32:37970 captureFilmStripSetting.set(true);
971 test.evaluateInConsole_(performActionsInPage.toString(), function() {});
972 test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
973
974 function onTimelineDone() {
975 captureFilmStripSetting.set(false);
976 const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
977 const frames = filmStripModel.frames();
978 test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
979 loadFrameImages(frames);
980 }
981
982 function loadFrameImages(frames) {
983 const readyImages = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:34984 for (const frame of frames) {
Blink Reformat4c46d092018-04-07 15:32:37985 frame.imageDataPromise().then(onGotImageData);
Tim van der Lippe1d6e57a2019-09-30 11:55:34986 }
Blink Reformat4c46d092018-04-07 15:32:37987
988 function onGotImageData(data) {
989 const image = new Image();
990 test.assertTrue(!!data, 'No image data for frame');
991 image.addEventListener('load', onLoad);
992 image.src = 'data:image/jpg;base64,' + data;
993 }
994
995 function onLoad(event) {
996 readyImages.push(event.target);
Tim van der Lippe1d6e57a2019-09-30 11:55:34997 if (readyImages.length === frames.length) {
Blink Reformat4c46d092018-04-07 15:32:37998 validateImagesAndCompleteTest(readyImages);
Tim van der Lippe1d6e57a2019-09-30 11:55:34999 }
Blink Reformat4c46d092018-04-07 15:32:371000 }
1001 }
1002
1003 function validateImagesAndCompleteTest(images) {
1004 let redCount = 0;
1005 let greenCount = 0;
1006 let blueCount = 0;
1007
1008 const canvas = document.createElement('canvas');
1009 const ctx = canvas.getContext('2d');
1010 for (const image of images) {
1011 test.assertTrue(image.naturalWidth > 10);
1012 test.assertTrue(image.naturalHeight > 10);
1013 canvas.width = image.naturalWidth;
1014 canvas.height = image.naturalHeight;
1015 ctx.drawImage(image, 0, 0);
1016 const data = ctx.getImageData(0, 0, 1, 1);
1017 const color = Array.prototype.join.call(data.data, ',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341018 if (data.data[0] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371019 redCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341020 } else if (data.data[1] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371021 greenCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341022 } else if (data.data[2] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371023 blueCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341024 } else {
Blink Reformat4c46d092018-04-07 15:32:371025 test.fail('Unexpected color: ' + color);
Tim van der Lippe1d6e57a2019-09-30 11:55:341026 }
Blink Reformat4c46d092018-04-07 15:32:371027 }
1028 test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed');
1029 test.releaseControl();
1030 }
1031
1032 test.takeControl();
1033 };
1034
1035 TestSuite.prototype.testSettings = function() {
1036 const test = this;
1037
1038 createSettings();
1039 test.takeControl();
1040 setTimeout(reset, 0);
1041
1042 function createSettings() {
Paul Lewis6bcdb182020-01-23 11:08:051043 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371044 localSetting.set({s: 'local', n: 1});
Paul Lewis6bcdb182020-01-23 11:08:051045 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371046 globalSetting.set({s: 'global', n: 2});
1047 }
1048
1049 function reset() {
Tim van der Lippe99e59b82019-09-30 20:00:591050 Root.Runtime.experiments.clearForTest();
Tim van der Lippe50cfa9b2019-10-01 10:40:581051 Host.InspectorFrontendHost.getPreferences(gotPreferences);
Blink Reformat4c46d092018-04-07 15:32:371052 }
1053
1054 function gotPreferences(prefs) {
1055 Main.Main._instanceForTest._createSettings(prefs);
1056
Paul Lewis6bcdb182020-01-23 11:08:051057 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371058 test.assertEquals('object', typeof localSetting.get());
1059 test.assertEquals('local', localSetting.get().s);
1060 test.assertEquals(1, localSetting.get().n);
Paul Lewis6bcdb182020-01-23 11:08:051061 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371062 test.assertEquals('object', typeof globalSetting.get());
1063 test.assertEquals('global', globalSetting.get().s);
1064 test.assertEquals(2, globalSetting.get().n);
1065 test.releaseControl();
1066 }
1067 };
1068
1069 TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
1070 const test = this;
1071 test.takeControl();
Paul Lewise504fd62020-01-23 16:52:331072 const messages = self.SDK.consoleModel.messages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341073 if (messages.length === 1) {
Blink Reformat4c46d092018-04-07 15:32:371074 checkMessages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341075 } else {
Paul Lewise504fd62020-01-23 16:52:331076 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
Tim van der Lippe1d6e57a2019-09-30 11:55:341077 }
Blink Reformat4c46d092018-04-07 15:32:371078
1079 function checkMessages() {
Paul Lewise504fd62020-01-23 16:52:331080 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371081 test.assertEquals(1, messages.length);
1082 test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
1083 test.releaseControl();
1084 }
1085 };
1086
1087 TestSuite.prototype.testConsoleContextNames = function() {
1088 const test = this;
1089 test.takeControl();
1090 this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
1091
1092 function onExecutionContexts() {
1093 const consoleView = Console.ConsoleView.instance();
1094 const selector = consoleView._consoleContextSelector;
1095 const values = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341096 for (const item of selector._items) {
Blink Reformat4c46d092018-04-07 15:32:371097 values.push(selector.titleFor(item));
Tim van der Lippe1d6e57a2019-09-30 11:55:341098 }
Blink Reformat4c46d092018-04-07 15:32:371099 test.assertEquals('top', values[0]);
1100 test.assertEquals('Simple content script', values[1]);
1101 test.releaseControl();
1102 }
1103 };
1104
1105 TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
1106 const test = this;
1107 test.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331108 self.SDK.targetManager.addModelListener(
Blink Reformat4c46d092018-04-07 15:32:371109 SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
1110
1111 this.evaluateInConsole_(`
1112 let img = document.createElement('img');
1113 img.src = "${url}";
1114 document.body.appendChild(img);
1115 `, () => {});
1116
1117 let count = 0;
1118 function onResponseReceived(event) {
Songtao Xia1e692682020-06-19 13:56:391119 const networkRequest = event.data.request;
Tim van der Lippe1d6e57a2019-09-30 11:55:341120 if (!networkRequest.url().startsWith('http')) {
Blink Reformat4c46d092018-04-07 15:32:371121 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341122 }
Blink Reformat4c46d092018-04-07 15:32:371123 switch (++count) {
1124 case 1: // Original redirect
1125 test.assertEquals(301, networkRequest.statusCode);
1126 test.assertEquals('Moved Permanently', networkRequest.statusText);
1127 test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
1128 break;
1129
1130 case 2: // HSTS internal redirect
1131 test.assertTrue(networkRequest.url().startsWith('http://'));
Blink Reformat4c46d092018-04-07 15:32:371132 test.assertEquals(307, networkRequest.statusCode);
1133 test.assertEquals('Internal Redirect', networkRequest.statusText);
1134 test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
1135 test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
1136 break;
1137
1138 case 3: // Final response
1139 test.assertTrue(networkRequest.url().startsWith('https://'));
1140 test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
1141 test.assertEquals(200, networkRequest.statusCode);
1142 test.assertEquals('OK', networkRequest.statusText);
1143 test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
1144 test.releaseControl();
1145 }
1146 }
1147 };
1148
1149 TestSuite.prototype.testDOMWarnings = function() {
Paul Lewise504fd62020-01-23 16:52:331150 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371151 this.assertEquals(1, messages.length);
1152 const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
1153 this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
1154 };
1155
1156 TestSuite.prototype.waitForTestResultsInConsole = function() {
Paul Lewise504fd62020-01-23 16:52:331157 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371158 for (let i = 0; i < messages.length; ++i) {
1159 const text = messages[i].messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341160 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371161 return;
Mathias Bynensf06e8c02020-02-28 13:58:281162 }
1163 if (/^FAIL/.test(text)) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341164 this.fail(text);
1165 } // This will throw.
Blink Reformat4c46d092018-04-07 15:32:371166 }
1167 // Neither PASS nor FAIL, so wait for more messages.
1168 function onConsoleMessage(event) {
1169 const text = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341170 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371171 this.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:341172 } else if (/^FAIL/.test(text)) {
Blink Reformat4c46d092018-04-07 15:32:371173 this.fail(text);
Tim van der Lippe1d6e57a2019-09-30 11:55:341174 }
Blink Reformat4c46d092018-04-07 15:32:371175 }
1176
Paul Lewise504fd62020-01-23 16:52:331177 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:371178 this.takeControl();
1179 };
1180
Andrey Kosyakova08cb9b2020-04-01 21:49:521181 TestSuite.prototype.waitForTestResultsAsMessage = function() {
1182 const onMessage = event => {
1183 if (!event.data.testOutput) {
1184 return;
1185 }
1186 top.removeEventListener('message', onMessage);
1187 const text = event.data.testOutput;
1188 if (text === 'PASS') {
1189 this.releaseControl();
1190 } else {
1191 this.fail(text);
1192 }
1193 };
1194 top.addEventListener('message', onMessage);
1195 this.takeControl();
1196 };
1197
Blink Reformat4c46d092018-04-07 15:32:371198 TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
1199 const original = receiver[methodName];
1200 if (typeof original !== 'function') {
Mathias Bynens23ee1aa2020-03-02 12:06:381201 this.fail(`TestSuite._overrideMethod: ${methodName} is not a function`);
Blink Reformat4c46d092018-04-07 15:32:371202 return;
1203 }
1204 receiver[methodName] = function() {
1205 let value;
1206 try {
1207 value = original.apply(receiver, arguments);
1208 } finally {
1209 receiver[methodName] = original;
1210 }
1211 override.apply(original, arguments);
1212 return value;
1213 };
1214 };
1215
1216 TestSuite.prototype.startTimeline = function(callback) {
1217 const test = this;
1218 this.showPanel('timeline').then(function() {
1219 const timeline = UI.panels.timeline;
1220 test._overrideMethod(timeline, '_recordingStarted', callback);
1221 timeline._toggleRecording();
1222 });
1223 };
1224
1225 TestSuite.prototype.stopTimeline = function(callback) {
1226 const timeline = UI.panels.timeline;
1227 this._overrideMethod(timeline, 'loadingComplete', callback);
1228 timeline._toggleRecording();
1229 };
1230
1231 TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
1232 const callback = arguments[arguments.length - 1];
1233 const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
1234 const argsString = arguments.length < 3 ?
1235 '' :
1236 Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
1237 this.evaluateInConsole_(
1238 `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
Paul Lewise504fd62020-01-23 16:52:331239 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371240
1241 function onConsoleMessage(event) {
1242 const text = event.data.messageText;
1243 if (text === doneMessage) {
Paul Lewise504fd62020-01-23 16:52:331244 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371245 callback();
1246 }
1247 }
1248 };
1249
1250 TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
1251 const test = this;
1252
1253 this.startTimeline(onRecordingStarted);
1254
1255 function onRecordingStarted() {
1256 test.invokePageFunctionAsync(functionName, pageActionsDone);
1257 }
1258
1259 function pageActionsDone() {
1260 test.stopTimeline(callback);
1261 }
1262 };
1263
1264 TestSuite.prototype.enableExperiment = function(name) {
Tim van der Lippe99e59b82019-09-30 20:00:591265 Root.Runtime.experiments.enableForTest(name);
Blink Reformat4c46d092018-04-07 15:32:371266 };
1267
1268 TestSuite.prototype.checkInputEventsPresent = function() {
1269 const expectedEvents = new Set(arguments);
1270 const model = UI.panels.timeline._performanceModel.timelineModel();
1271 const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
1272 const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
1273 const prefix = 'InputLatency::';
1274 for (const e of input) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341275 if (!e.name.startsWith(prefix)) {
Blink Reformat4c46d092018-04-07 15:32:371276 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341277 }
1278 if (e.steps.length < 2) {
Blink Reformat4c46d092018-04-07 15:32:371279 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341280 }
Blink Reformat4c46d092018-04-07 15:32:371281 if (e.name.startsWith(prefix + 'Mouse') &&
Tim van der Lippe1d6e57a2019-09-30 11:55:341282 typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') {
Blink Reformat4c46d092018-04-07 15:32:371283 throw `Missing timeWaitingForMainThread on ${e.name}`;
Tim van der Lippe1d6e57a2019-09-30 11:55:341284 }
Blink Reformat4c46d092018-04-07 15:32:371285 expectedEvents.delete(e.name.substr(prefix.length));
1286 }
Tim van der Lippe1d6e57a2019-09-30 11:55:341287 if (expectedEvents.size) {
Blink Reformat4c46d092018-04-07 15:32:371288 throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341289 }
Blink Reformat4c46d092018-04-07 15:32:371290 };
1291
1292 TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
1293 this.takeControl();
1294 await self.runtime.loadModulePromise('elements');
Tim van der Lippe1d6e57a2019-09-30 11:55:341295 if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) {
Blink Reformat4c46d092018-04-07 15:32:371296 await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f));
Tim van der Lippe1d6e57a2019-09-30 11:55:341297 }
Blink Reformat4c46d092018-04-07 15:32:371298 this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest);
1299 this.releaseControl();
1300 };
1301
Andrey Lushnikovd92662b2018-05-09 03:57:001302 TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
1303 this.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331304 const targetAgent = self.SDK.targetManager.mainTarget().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.
1317 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
1318 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1319
1320 // Cause a Browser to be created with the temp profile.
1321 const {targetId} =
1322 await targetAgent.invoke_createTarget({url: 'data:text/html,', browserContextId, newWindow: true});
1323 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 = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331334 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov0eea25e2018-04-24 22:29:511335
1336 const target1 = await createIsolatedTarget(url);
1337 const target2 = await createIsolatedTarget(url);
1338
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 = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331353 self.SDK.targetManager.observeTargets(
1354 {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();
1361
1362 /**
1363 * @param {string} url
1364 * @return {!Promise<!SDK.Target>}
1365 */
1366 async function createIsolatedTarget(url) {
Andrey Lushnikov0eea25e2018-04-24 22:29:511367 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1368 browserContextIds.push(browserContextId);
1369
1370 const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
Dmitry Gozman99d7a6c2018-11-12 17:55:111371 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
Andrey Lushnikov0eea25e2018-04-24 22:29:511372
Paul Lewis4ae5f4f2020-01-23 10:19:331373 const target = self.SDK.targetManager.targets().find(target => target.id() === targetId);
Andrey Lushnikov0eea25e2018-04-24 22:29:511374 const pageAgent = target.pageAgent();
1375 await pageAgent.invoke_enable();
1376 await pageAgent.invoke_navigate({url});
1377 return target;
1378 }
1379
Andrey Lushnikov0eea25e2018-04-24 22:29:511380 async function disposeBrowserContext(browserContextId) {
Paul Lewis4ae5f4f2020-01-23 10:19:331381 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov69499702018-05-08 18:20:471382 await targetAgent.invoke_disposeBrowserContext({browserContextId});
Andrey Lushnikov0eea25e2018-04-24 22:29:511383 }
1384
1385 async function evalCode(target, code) {
1386 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1387 }
1388 };
1389
Blink Reformat4c46d092018-04-07 15:32:371390 TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
1391 this.takeControl();
1392
1393 await new Promise(callback => this._waitForTargets(2, callback));
1394
1395 async function takeLogs(target) {
1396 const code = `
1397 (function() {
1398 var result = window.logs.join(' ');
1399 window.logs = [];
1400 return result;
1401 })()
1402 `;
1403 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1404 }
1405
1406 let parentFrameOutput;
1407 let childFrameOutput;
1408
Paul Lewis4ae5f4f2020-01-23 10:19:331409 const inputAgent = self.SDK.targetManager.mainTarget().inputAgent();
1410 const runtimeAgent = self.SDK.targetManager.mainTarget().runtimeAgent();
Blink Reformat4c46d092018-04-07 15:32:371411 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
1412 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
1413 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
1414 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
1415 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
1416 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
1417 parentFrameOutput = 'Event type: mousedown button: 0 x: 10 y: 10 Event type: mouseup button: 0 x: 10 y: 20';
Paul Lewis4ae5f4f2020-01-23 10:19:331418 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371419 childFrameOutput = 'Event type: mousedown button: 0 x: 30 y: 40 Event type: mouseup button: 0 x: 30 y: 50';
Paul Lewis4ae5f4f2020-01-23 10:19:331420 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371421
1422
1423 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
Mathias Bynens23ee1aa2020-03-02 12:06:381424 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';
Paul Lewis4ae5f4f2020-01-23 10:19:331427 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371428 childFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331429 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.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';
Paul Lewis4ae5f4f2020-01-23 10:19:331436 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371437 childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
Paul Lewis4ae5f4f2020-01-23 10:19:331438 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.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 => {
1448 Host.ResourceLoader.load(url, headers, callback);
1449
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
1468 this.takeControl();
1469 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
Paul Lewis4ae5f4f2020-01-23 10:19:331474 await self.SDK.targetManager.mainTarget().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
Paul Lewis4ae5f4f2020-01-23 10:19:331481 await self.SDK.targetManager.mainTarget().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>');
1489 await testCase(fileURL, undefined, 200, [], '<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';
Paul Lewis5a922e72020-01-24 11:58:081499 self.SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
Joey Arhar723d5b52019-04-19 01:31:391500
1501 function onRequestUpdated(event) {
1502 const request = event.data;
Tim van der Lippe1d6e57a2019-09-30 11:55:341503 if (request.resourceType() !== Common.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 }
Paul Lewis4ae5f4f2020-01-23 10:19:331519 self.SDK.targetManager.addModelListener(
Joey Arhar723d5b52019-04-19 01:31:391520 SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
1521
1522 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
1523 };
1524
Blink Reformat4c46d092018-04-07 15:32:371525 /**
1526 * Serializes array of uiSourceCodes to string.
1527 * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
1528 * @return {string}
1529 */
1530 TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
1531 const names = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341532 for (let i = 0; i < uiSourceCodes.length; i++) {
Blink Reformat4c46d092018-04-07 15:32:371533 names.push('"' + uiSourceCodes[i].url() + '"');
Tim van der Lippe1d6e57a2019-09-30 11:55:341534 }
Blink Reformat4c46d092018-04-07 15:32:371535 return names.join(',');
1536 };
1537
1538 /**
1539 * Returns all loaded non anonymous uiSourceCodes.
1540 * @return {!Array.<!Workspace.UISourceCode>}
1541 */
1542 TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
1543 /**
1544 * @param {!Workspace.UISourceCode} uiSourceCode
1545 */
1546 function filterOutService(uiSourceCode) {
1547 return !uiSourceCode.project().isServiceProject();
1548 }
1549
Paul Lewis10e83a92020-01-23 14:07:581550 const uiSourceCodes = self.Workspace.workspace.uiSourceCodes();
Blink Reformat4c46d092018-04-07 15:32:371551 return uiSourceCodes.filter(filterOutService);
1552 };
1553
1554 /*
1555 * Evaluates the code in the console as if user typed it manually and invokes
1556 * the callback when the result message is received and added to the console.
1557 * @param {string} code
1558 * @param {function(string)} callback
1559 */
1560 TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
1561 function innerEvaluate() {
Paul Lewisd9907342020-01-24 13:49:471562 self.UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371563 const consoleView = Console.ConsoleView.instance();
1564 consoleView._prompt._appendCommand(code);
1565
1566 this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) {
1567 callback(viewMessage.toMessageElement().deepTextContent());
1568 }.bind(this));
1569 }
1570
1571 function showConsoleAndEvaluate() {
Paul Lewis04ccecc2020-01-22 17:15:141572 self.Common.console.showPromise().then(innerEvaluate.bind(this));
Blink Reformat4c46d092018-04-07 15:32:371573 }
1574
Paul Lewisd9907342020-01-24 13:49:471575 if (!self.UI.context.flavor(SDK.ExecutionContext)) {
1576 self.UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371577 return;
1578 }
1579 showConsoleAndEvaluate.call(this);
1580 };
1581
1582 /**
1583 * Checks that all expected scripts are present in the scripts list
1584 * in the Scripts panel.
1585 * @param {!Array.<string>} expected Regular expressions describing
1586 * expected script names.
1587 * @return {boolean} Whether all the scripts are in "scripts-files" select
1588 * box
1589 */
1590 TestSuite.prototype._scriptsAreParsed = function(expected) {
1591 const uiSourceCodes = this.nonAnonymousUISourceCodes_();
1592 // Check that at least all the expected scripts are present.
1593 const missing = expected.slice(0);
1594 for (let i = 0; i < uiSourceCodes.length; ++i) {
1595 for (let j = 0; j < missing.length; ++j) {
1596 if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
1597 missing.splice(j, 1);
1598 break;
1599 }
1600 }
1601 }
1602 return missing.length === 0;
1603 };
1604
1605 /**
1606 * Waits for script pause, checks expectations, and invokes the callback.
1607 * @param {function():void} callback
1608 */
1609 TestSuite.prototype._waitForScriptPause = function(callback) {
1610 this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback);
1611 };
1612
1613 /**
1614 * Waits until all the scripts are parsed and invokes the callback.
1615 */
1616 TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
1617 const test = this;
1618
1619 function waitForAllScripts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341620 if (test._scriptsAreParsed(expectedScripts)) {
Blink Reformat4c46d092018-04-07 15:32:371621 callback();
Tim van der Lippe1d6e57a2019-09-30 11:55:341622 } else {
Blink Reformat4c46d092018-04-07 15:32:371623 test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts);
Tim van der Lippe1d6e57a2019-09-30 11:55:341624 }
Blink Reformat4c46d092018-04-07 15:32:371625 }
1626
1627 waitForAllScripts();
1628 };
1629
1630 TestSuite.prototype._waitForTargets = function(n, callback) {
1631 checkTargets.call(this);
1632
1633 function checkTargets() {
Paul Lewis4ae5f4f2020-01-23 10:19:331634 if (self.SDK.targetManager.targets().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371635 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341636 } else {
Blink Reformat4c46d092018-04-07 15:32:371637 this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341638 }
Blink Reformat4c46d092018-04-07 15:32:371639 }
1640 };
1641
1642 TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
Paul Lewis4ae5f4f2020-01-23 10:19:331643 const runtimeModel = self.SDK.targetManager.mainTarget().model(SDK.RuntimeModel);
Blink Reformat4c46d092018-04-07 15:32:371644 checkForExecutionContexts.call(this);
1645
1646 function checkForExecutionContexts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341647 if (runtimeModel.executionContexts().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371648 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341649 } else {
Blink Reformat4c46d092018-04-07 15:32:371650 this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341651 }
Blink Reformat4c46d092018-04-07 15:32:371652 }
1653 };
1654
1655
1656 window.uiTests = new TestSuite(window.domAutomationController);
1657})(window);