blob: 99de8ebe0b0d3ca813801dc66d0bcd840822b7f4 [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: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Paul Lewis4ae5f4f2020-01-23 10:19:33704 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37705 {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Paul Lewis4ae5f4f2020-01-23 10:19:33706 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37707 {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
Paul Lewis4ae5f4f2020-01-23 10:19:33708 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37709 {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
710
711 test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
712 }
713
714 function onResultOfInput(value) {
715 // Console adds "" around the response.
716 test.assertEquals('"Abbf"', value);
717 test.releaseControl();
718 }
719
720 function onConsoleMessage(event) {
721 const message = event.data.messageText;
722 if (message === 'ready' && !receivedReady) {
723 receivedReady = true;
724 signalToShowAutofill();
725 }
726 // This log comes from the browser unittest code.
Tim van der Lippe1d6e57a2019-09-30 11:55:34727 if (message === 'didShowSuggestions') {
Blink Reformat4c46d092018-04-07 15:32:37728 selectTopAutoFill();
Tim van der Lippe1d6e57a2019-09-30 11:55:34729 }
Blink Reformat4c46d092018-04-07 15:32:37730 }
731
732 this.takeControl();
733
734 // It is possible for the ready console messagage to be already received but not handled
735 // or received later. This ensures we can catch both cases.
Paul Lewise504fd62020-01-23 16:52:33736 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37737
Paul Lewise504fd62020-01-23 16:52:33738 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:37739 if (messages.length) {
740 const text = messages[0].messageText;
741 this.assertEquals('ready', text);
742 signalToShowAutofill();
743 }
744 };
745
Pâris MEULEMANd4709cb2019-04-17 08:32:48746 TestSuite.prototype.testKeyEventUnhandled = function() {
747 function onKeyEventUnhandledKeyDown(event) {
748 this.assertEquals('keydown', event.data.type);
749 this.assertEquals('F8', event.data.key);
750 this.assertEquals(119, event.data.keyCode);
751 this.assertEquals(0, event.data.modifiers);
752 this.assertEquals('', event.data.code);
Tim van der Lippe50cfa9b2019-10-01 10:40:58753 Host.InspectorFrontendHost.events.removeEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44754 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Tim van der Lippe50cfa9b2019-10-01 10:40:58755 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44756 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33757 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48758 {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
759 }
760 function onKeyEventUnhandledKeyUp(event) {
761 this.assertEquals('keyup', event.data.type);
762 this.assertEquals('F8', event.data.key);
763 this.assertEquals(119, event.data.keyCode);
764 this.assertEquals(0, event.data.modifiers);
765 this.assertEquals('F8', event.data.code);
766 this.releaseControl();
767 }
768 this.takeControl();
Tim van der Lippe50cfa9b2019-10-01 10:40:58769 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44770 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33771 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48772 {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
773 };
774
Blink Reformat4c46d092018-04-07 15:32:37775 TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33776 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37777 {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
Paul Lewis4ae5f4f2020-01-23 10:19:33778 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37779 {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
780 };
781
Pâris MEULEMANd81f35f2019-05-07 09:04:34782 // Check that showing the certificate viewer does not crash, crbug.com/954874
783 TestSuite.prototype.testShowCertificate = function() {
Tim van der Lippe50cfa9b2019-10-01 10:40:58784 Host.InspectorFrontendHost.showCertificateViewer([
Pâris MEULEMANd81f35f2019-05-07 09:04:34785 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
786 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
787 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
788 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
789 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
790 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
791 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
792 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
793 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
794 'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
795 'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
796 'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOcIA7AVR/Ck22Uj8X' +
797 'UOECercjUrKdDyaAPcLp2TThAgMBAAGjggHZMIIB1TATBgNVHSUEDDAKBggr' +
798 'BgEFBQcDATCBrwYDVR0RBIGnMIGkgg0qLmFwcHNwb3QuY29tggsqLmEucnVu' +
799 'LmFwcIIVKi50aGlua3dpdGhnb29nbGUuY29tghAqLndpdGhnb29nbGUuY29t' +
800 'ghEqLndpdGh5b3V0dWJlLmNvbYILYXBwc3BvdC5jb22CB3J1bi5hcHCCE3Ro' +
801 'aW5rd2l0aGdvb2dsZS5jb22CDndpdGhnb29nbGUuY29tgg93aXRoeW91dHVi' +
802 'ZS5jb20waAYIKwYBBQUHAQEEXDBaMC0GCCsGAQUFBzAChiFodHRwOi8vcGtp' +
803 'Lmdvb2cvZ3NyMi9HVFNHSUFHMy5jcnQwKQYIKwYBBQUHMAGGHWh0dHA6Ly9v' +
804 'Y3NwLnBraS5nb29nL0dUU0dJQUczMB0GA1UdDgQWBBTGkpE5o0H9+Wjc05rF' +
805 'hNQiYDjBFjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFHfCuFCaZ3Z2sS3C' +
806 'htCDoH6mfrpLMCEGA1UdIAQaMBgwDAYKKwYBBAHWeQIFAzAIBgZngQwBAgIw' +
807 'MQYDVR0fBCowKDAmoCSgIoYgaHR0cDovL2NybC5wa2kuZ29vZy9HVFNHSUFH' +
808 'My5jcmwwDQYJKoZIhvcNAQELBQADggEBALqoYGqWtJW/6obEzY+ehsgfyXb+' +
809 'qNIuV09wt95cRF93HlLbBlSZ/Iz8HXX44ZT1/tGAkwKnW0gDKSSab3I8U+e9' +
810 'LHbC9VXrgAFENzu89MNKNmK5prwv+MPA2HUQPu4Pad3qXmd4+nKc/EUjtg1d' +
811 '/xKGK1Vn6JX3i5ly/rduowez3LxpSAJuIwseum331aQaKC2z2ri++96B8MPU' +
812 'KFXzvV2gVGOe3ZYqmwPaG8y38Tba+OzEh59ygl8ydJJhoI6+R3itPSy0aXUU' +
813 'lMvvAbfCobXD5kBRQ28ysgbDSDOPs3fraXpAKL92QUjsABs58XBz5vka4swu' +
814 'gg/u+ZxaKOqfIm8=',
815 'MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBM' +
816 'MSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMK' +
817 'R2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAw' +
818 'NDJaFw0yMTEyMTUwMDAwNDJaMFQxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVH' +
819 'b29nbGUgVHJ1c3QgU2VydmljZXMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5l' +
820 'dCBBdXRob3JpdHkgRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB' +
821 'AQDKUkvqHv/OJGuo2nIYaNVWXQ5IWi01CXZaz6TIHLGp/lOJ+600/4hbn7vn' +
822 '6AAB3DVzdQOts7G5pH0rJnnOFUAK71G4nzKMfHCGUksW/mona+Y2emJQ2N+a' +
823 'icwJKetPKRSIgAuPOB6Aahh8Hb2XO3h9RUk2T0HNouB2VzxoMXlkyW7XUR5m' +
824 'w6JkLHnA52XDVoRTWkNty5oCINLvGmnRsJ1zouAqYGVQMc/7sy+/EYhALrVJ' +
825 'EA8KbtyX+r8snwU5C1hUrwaW6MWOARa8qBpNQcWTkaIeoYvy/sGIJEmjR0vF' +
826 'EwHdp1cSaWIr6/4g72n7OqXwfinu7ZYW97EfoOSQJeAzAgMBAAGjggEzMIIB' +
827 'LzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF' +
828 'BwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFHfCuFCaZ3Z2sS3C' +
829 'htCDoH6mfrpLMB8GA1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUG' +
830 'CCsGAQUFBwEBBCkwJzAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdv' +
831 'b2cvZ3NyMjAyBgNVHR8EKzApMCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29n' +
832 'L2dzcjIvZ3NyMi5jcmwwPwYDVR0gBDgwNjA0BgZngQwBAgIwKjAoBggrBgEF' +
833 'BQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9yZXBvc2l0b3J5LzANBgkqhkiG9w0B' +
834 'AQsFAAOCAQEAHLeJluRT7bvs26gyAZ8so81trUISd7O45skDUmAge1cnxhG1' +
835 'P2cNmSxbWsoiCt2eux9LSD+PAj2LIYRFHW31/6xoic1k4tbWXkDCjir37xTT' +
836 'NqRAMPUyFRWSdvt+nlPqwnb8Oa2I/maSJukcxDjNSfpDh/Bd1lZNgdd/8cLd' +
837 'sE3+wypufJ9uXO1iQpnh9zbuFIwsIONGl1p3A8CgxkqI/UAih3JaGOqcpcda' +
838 'CIzkBaR9uYQ1X4k2Vg5APRLouzVy7a8IVk6wuy6pm+T7HT4LY8ibS5FEZlfA' +
839 'FLSW8NwsVz9SBK2Vqn1N0PIMn5xA6NZVc7o835DLAFshEWfC7TIe3g==',
840 'MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEg' +
841 'MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkds' +
842 'b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAw' +
843 'WhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg' +
844 'Q0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs' +
845 'U2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8o' +
846 'mUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe' +
847 '+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1' +
848 'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
849 'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
850 '4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
851 'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
852 'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
853 'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
854 'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
855 'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
856 'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
857 'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
858 'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
859 '9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
860 'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
861 '/H5COEBkEveegeGTLg=='
862 ]);
863 };
864
Blink Reformat4c46d092018-04-07 15:32:37865 // Simple sanity check to make sure network throttling is wired up
866 // See crbug.com/747724
867 TestSuite.prototype.testOfflineNetworkConditions = async function() {
868 const test = this;
Paul Lewis5a922e72020-01-24 11:58:08869 self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Blink Reformat4c46d092018-04-07 15:32:37870
871 function finishRequest(request) {
872 test.assertEquals(
873 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
874 test.releaseControl();
875 }
876
877 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
878
879 test.takeControl();
880 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
881 };
882
883 TestSuite.prototype.testEmulateNetworkConditions = function() {
884 const test = this;
885
886 function testPreset(preset, messages, next) {
887 function onConsoleMessage(event) {
888 const index = messages.indexOf(event.data.messageText);
889 if (index === -1) {
890 test.fail('Unexpected message: ' + event.data.messageText);
891 return;
892 }
893
894 messages.splice(index, 1);
895 if (!messages.length) {
Paul Lewise504fd62020-01-23 16:52:33896 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37897 next();
898 }
899 }
900
Paul Lewise504fd62020-01-23 16:52:33901 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Paul Lewis5a922e72020-01-24 11:58:08902 self.SDK.multitargetNetworkManager.setNetworkConditions(preset);
Blink Reformat4c46d092018-04-07 15:32:37903 }
904
905 test.takeControl();
906 step1();
907
908 function step1() {
909 testPreset(
910 MobileThrottling.networkPresets[2],
911 [
912 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
913 ],
914 step2);
915 }
916
917 function step2() {
918 testPreset(
919 MobileThrottling.networkPresets[1],
920 [
921 'online event: online = true',
Wolfgang Beyer585ded42020-02-25 08:42:41922 'connection change event: type = cellular; downlinkMax = 0.390625; effectiveType = 2g'
Blink Reformat4c46d092018-04-07 15:32:37923 ],
924 step3);
925 }
926
927 function step3() {
928 testPreset(
929 MobileThrottling.networkPresets[0],
Wolfgang Beyer585ded42020-02-25 08:42:41930 ['connection change event: type = cellular; downlinkMax = 1.4400000000000002; effectiveType = 3g'],
Blink Reformat4c46d092018-04-07 15:32:37931 test.releaseControl.bind(test));
932 }
933 };
934
935 TestSuite.prototype.testScreenshotRecording = function() {
936 const test = this;
937
938 function performActionsInPage(callback) {
939 let count = 0;
940 const div = document.createElement('div');
941 div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
942 document.body.appendChild(div);
943 requestAnimationFrame(frame);
944 function frame() {
945 const color = [0, 0, 0];
946 color[count % 3] = 255;
947 div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34948 if (++count > 10) {
Blink Reformat4c46d092018-04-07 15:32:37949 requestAnimationFrame(callback);
Tim van der Lippe1d6e57a2019-09-30 11:55:34950 } else {
Blink Reformat4c46d092018-04-07 15:32:37951 requestAnimationFrame(frame);
Tim van der Lippe1d6e57a2019-09-30 11:55:34952 }
Blink Reformat4c46d092018-04-07 15:32:37953 }
954 }
955
Paul Lewis6bcdb182020-01-23 11:08:05956 const captureFilmStripSetting = self.Common.settings.createSetting('timelineCaptureFilmStrip', false);
Blink Reformat4c46d092018-04-07 15:32:37957 captureFilmStripSetting.set(true);
958 test.evaluateInConsole_(performActionsInPage.toString(), function() {});
959 test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
960
961 function onTimelineDone() {
962 captureFilmStripSetting.set(false);
963 const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
964 const frames = filmStripModel.frames();
965 test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
966 loadFrameImages(frames);
967 }
968
969 function loadFrameImages(frames) {
970 const readyImages = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:34971 for (const frame of frames) {
Blink Reformat4c46d092018-04-07 15:32:37972 frame.imageDataPromise().then(onGotImageData);
Tim van der Lippe1d6e57a2019-09-30 11:55:34973 }
Blink Reformat4c46d092018-04-07 15:32:37974
975 function onGotImageData(data) {
976 const image = new Image();
977 test.assertTrue(!!data, 'No image data for frame');
978 image.addEventListener('load', onLoad);
979 image.src = 'data:image/jpg;base64,' + data;
980 }
981
982 function onLoad(event) {
983 readyImages.push(event.target);
Tim van der Lippe1d6e57a2019-09-30 11:55:34984 if (readyImages.length === frames.length) {
Blink Reformat4c46d092018-04-07 15:32:37985 validateImagesAndCompleteTest(readyImages);
Tim van der Lippe1d6e57a2019-09-30 11:55:34986 }
Blink Reformat4c46d092018-04-07 15:32:37987 }
988 }
989
990 function validateImagesAndCompleteTest(images) {
991 let redCount = 0;
992 let greenCount = 0;
993 let blueCount = 0;
994
995 const canvas = document.createElement('canvas');
996 const ctx = canvas.getContext('2d');
997 for (const image of images) {
998 test.assertTrue(image.naturalWidth > 10);
999 test.assertTrue(image.naturalHeight > 10);
1000 canvas.width = image.naturalWidth;
1001 canvas.height = image.naturalHeight;
1002 ctx.drawImage(image, 0, 0);
1003 const data = ctx.getImageData(0, 0, 1, 1);
1004 const color = Array.prototype.join.call(data.data, ',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341005 if (data.data[0] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371006 redCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341007 } else if (data.data[1] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371008 greenCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341009 } else if (data.data[2] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371010 blueCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341011 } else {
Blink Reformat4c46d092018-04-07 15:32:371012 test.fail('Unexpected color: ' + color);
Tim van der Lippe1d6e57a2019-09-30 11:55:341013 }
Blink Reformat4c46d092018-04-07 15:32:371014 }
1015 test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed');
1016 test.releaseControl();
1017 }
1018
1019 test.takeControl();
1020 };
1021
1022 TestSuite.prototype.testSettings = function() {
1023 const test = this;
1024
1025 createSettings();
1026 test.takeControl();
1027 setTimeout(reset, 0);
1028
1029 function createSettings() {
Paul Lewis6bcdb182020-01-23 11:08:051030 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371031 localSetting.set({s: 'local', n: 1});
Paul Lewis6bcdb182020-01-23 11:08:051032 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371033 globalSetting.set({s: 'global', n: 2});
1034 }
1035
1036 function reset() {
Tim van der Lippe99e59b82019-09-30 20:00:591037 Root.Runtime.experiments.clearForTest();
Tim van der Lippe50cfa9b2019-10-01 10:40:581038 Host.InspectorFrontendHost.getPreferences(gotPreferences);
Blink Reformat4c46d092018-04-07 15:32:371039 }
1040
1041 function gotPreferences(prefs) {
1042 Main.Main._instanceForTest._createSettings(prefs);
1043
Paul Lewis6bcdb182020-01-23 11:08:051044 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371045 test.assertEquals('object', typeof localSetting.get());
1046 test.assertEquals('local', localSetting.get().s);
1047 test.assertEquals(1, localSetting.get().n);
Paul Lewis6bcdb182020-01-23 11:08:051048 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371049 test.assertEquals('object', typeof globalSetting.get());
1050 test.assertEquals('global', globalSetting.get().s);
1051 test.assertEquals(2, globalSetting.get().n);
1052 test.releaseControl();
1053 }
1054 };
1055
1056 TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
1057 const test = this;
1058 test.takeControl();
Paul Lewise504fd62020-01-23 16:52:331059 const messages = self.SDK.consoleModel.messages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341060 if (messages.length === 1) {
Blink Reformat4c46d092018-04-07 15:32:371061 checkMessages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341062 } else {
Paul Lewise504fd62020-01-23 16:52:331063 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
Tim van der Lippe1d6e57a2019-09-30 11:55:341064 }
Blink Reformat4c46d092018-04-07 15:32:371065
1066 function checkMessages() {
Paul Lewise504fd62020-01-23 16:52:331067 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371068 test.assertEquals(1, messages.length);
1069 test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
1070 test.releaseControl();
1071 }
1072 };
1073
1074 TestSuite.prototype.testConsoleContextNames = function() {
1075 const test = this;
1076 test.takeControl();
1077 this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
1078
1079 function onExecutionContexts() {
1080 const consoleView = Console.ConsoleView.instance();
1081 const selector = consoleView._consoleContextSelector;
1082 const values = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341083 for (const item of selector._items) {
Blink Reformat4c46d092018-04-07 15:32:371084 values.push(selector.titleFor(item));
Tim van der Lippe1d6e57a2019-09-30 11:55:341085 }
Blink Reformat4c46d092018-04-07 15:32:371086 test.assertEquals('top', values[0]);
1087 test.assertEquals('Simple content script', values[1]);
1088 test.releaseControl();
1089 }
1090 };
1091
1092 TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
1093 const test = this;
1094 test.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331095 self.SDK.targetManager.addModelListener(
Blink Reformat4c46d092018-04-07 15:32:371096 SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
1097
1098 this.evaluateInConsole_(`
1099 let img = document.createElement('img');
1100 img.src = "${url}";
1101 document.body.appendChild(img);
1102 `, () => {});
1103
1104 let count = 0;
1105 function onResponseReceived(event) {
1106 const networkRequest = event.data;
Tim van der Lippe1d6e57a2019-09-30 11:55:341107 if (!networkRequest.url().startsWith('http')) {
Blink Reformat4c46d092018-04-07 15:32:371108 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341109 }
Blink Reformat4c46d092018-04-07 15:32:371110 switch (++count) {
1111 case 1: // Original redirect
1112 test.assertEquals(301, networkRequest.statusCode);
1113 test.assertEquals('Moved Permanently', networkRequest.statusText);
1114 test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
1115 break;
1116
1117 case 2: // HSTS internal redirect
1118 test.assertTrue(networkRequest.url().startsWith('http://'));
Blink Reformat4c46d092018-04-07 15:32:371119 test.assertEquals(307, networkRequest.statusCode);
1120 test.assertEquals('Internal Redirect', networkRequest.statusText);
1121 test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
1122 test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
1123 break;
1124
1125 case 3: // Final response
1126 test.assertTrue(networkRequest.url().startsWith('https://'));
1127 test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
1128 test.assertEquals(200, networkRequest.statusCode);
1129 test.assertEquals('OK', networkRequest.statusText);
1130 test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
1131 test.releaseControl();
1132 }
1133 }
1134 };
1135
1136 TestSuite.prototype.testDOMWarnings = function() {
Paul Lewise504fd62020-01-23 16:52:331137 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371138 this.assertEquals(1, messages.length);
1139 const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
1140 this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
1141 };
1142
1143 TestSuite.prototype.waitForTestResultsInConsole = function() {
Paul Lewise504fd62020-01-23 16:52:331144 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371145 for (let i = 0; i < messages.length; ++i) {
1146 const text = messages[i].messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341147 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371148 return;
Mathias Bynensf06e8c02020-02-28 13:58:281149 }
1150 if (/^FAIL/.test(text)) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341151 this.fail(text);
1152 } // This will throw.
Blink Reformat4c46d092018-04-07 15:32:371153 }
1154 // Neither PASS nor FAIL, so wait for more messages.
1155 function onConsoleMessage(event) {
1156 const text = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341157 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371158 this.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:341159 } else if (/^FAIL/.test(text)) {
Blink Reformat4c46d092018-04-07 15:32:371160 this.fail(text);
Tim van der Lippe1d6e57a2019-09-30 11:55:341161 }
Blink Reformat4c46d092018-04-07 15:32:371162 }
1163
Paul Lewise504fd62020-01-23 16:52:331164 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:371165 this.takeControl();
1166 };
1167
1168 TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
1169 const original = receiver[methodName];
1170 if (typeof original !== 'function') {
Mathias Bynens23ee1aa2020-03-02 12:06:381171 this.fail(`TestSuite._overrideMethod: ${methodName} is not a function`);
Blink Reformat4c46d092018-04-07 15:32:371172 return;
1173 }
1174 receiver[methodName] = function() {
1175 let value;
1176 try {
1177 value = original.apply(receiver, arguments);
1178 } finally {
1179 receiver[methodName] = original;
1180 }
1181 override.apply(original, arguments);
1182 return value;
1183 };
1184 };
1185
1186 TestSuite.prototype.startTimeline = function(callback) {
1187 const test = this;
1188 this.showPanel('timeline').then(function() {
1189 const timeline = UI.panels.timeline;
1190 test._overrideMethod(timeline, '_recordingStarted', callback);
1191 timeline._toggleRecording();
1192 });
1193 };
1194
1195 TestSuite.prototype.stopTimeline = function(callback) {
1196 const timeline = UI.panels.timeline;
1197 this._overrideMethod(timeline, 'loadingComplete', callback);
1198 timeline._toggleRecording();
1199 };
1200
1201 TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
1202 const callback = arguments[arguments.length - 1];
1203 const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
1204 const argsString = arguments.length < 3 ?
1205 '' :
1206 Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
1207 this.evaluateInConsole_(
1208 `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
Paul Lewise504fd62020-01-23 16:52:331209 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371210
1211 function onConsoleMessage(event) {
1212 const text = event.data.messageText;
1213 if (text === doneMessage) {
Paul Lewise504fd62020-01-23 16:52:331214 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371215 callback();
1216 }
1217 }
1218 };
1219
1220 TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
1221 const test = this;
1222
1223 this.startTimeline(onRecordingStarted);
1224
1225 function onRecordingStarted() {
1226 test.invokePageFunctionAsync(functionName, pageActionsDone);
1227 }
1228
1229 function pageActionsDone() {
1230 test.stopTimeline(callback);
1231 }
1232 };
1233
1234 TestSuite.prototype.enableExperiment = function(name) {
Tim van der Lippe99e59b82019-09-30 20:00:591235 Root.Runtime.experiments.enableForTest(name);
Blink Reformat4c46d092018-04-07 15:32:371236 };
1237
1238 TestSuite.prototype.checkInputEventsPresent = function() {
1239 const expectedEvents = new Set(arguments);
1240 const model = UI.panels.timeline._performanceModel.timelineModel();
1241 const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
1242 const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
1243 const prefix = 'InputLatency::';
1244 for (const e of input) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341245 if (!e.name.startsWith(prefix)) {
Blink Reformat4c46d092018-04-07 15:32:371246 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341247 }
1248 if (e.steps.length < 2) {
Blink Reformat4c46d092018-04-07 15:32:371249 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341250 }
Blink Reformat4c46d092018-04-07 15:32:371251 if (e.name.startsWith(prefix + 'Mouse') &&
Tim van der Lippe1d6e57a2019-09-30 11:55:341252 typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') {
Blink Reformat4c46d092018-04-07 15:32:371253 throw `Missing timeWaitingForMainThread on ${e.name}`;
Tim van der Lippe1d6e57a2019-09-30 11:55:341254 }
Blink Reformat4c46d092018-04-07 15:32:371255 expectedEvents.delete(e.name.substr(prefix.length));
1256 }
Tim van der Lippe1d6e57a2019-09-30 11:55:341257 if (expectedEvents.size) {
Blink Reformat4c46d092018-04-07 15:32:371258 throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341259 }
Blink Reformat4c46d092018-04-07 15:32:371260 };
1261
1262 TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
1263 this.takeControl();
1264 await self.runtime.loadModulePromise('elements');
Tim van der Lippe1d6e57a2019-09-30 11:55:341265 if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) {
Blink Reformat4c46d092018-04-07 15:32:371266 await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f));
Tim van der Lippe1d6e57a2019-09-30 11:55:341267 }
Blink Reformat4c46d092018-04-07 15:32:371268 this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest);
1269 this.releaseControl();
1270 };
1271
Andrey Lushnikovd92662b2018-05-09 03:57:001272 TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
1273 this.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331274 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikovd92662b2018-05-09 03:57:001275 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1276 const response1 = await targetAgent.invoke_getBrowserContexts();
1277 this.assertEquals(response1.browserContextIds.length, 1);
1278 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1279 const response2 = await targetAgent.invoke_getBrowserContexts();
1280 this.assertEquals(response2.browserContextIds.length, 0);
1281 this.releaseControl();
1282 };
1283
Andrey Lushnikov0eea25e2018-04-24 22:29:511284 TestSuite.prototype.testCreateBrowserContext = async function(url) {
1285 this.takeControl();
1286 const browserContextIds = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331287 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov0eea25e2018-04-24 22:29:511288
1289 const target1 = await createIsolatedTarget(url);
1290 const target2 = await createIsolatedTarget(url);
1291
Andrey Lushnikov07477b42018-05-08 22:00:521292 const response = await targetAgent.invoke_getBrowserContexts();
1293 this.assertEquals(response.browserContextIds.length, 2);
1294 this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
1295 this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
1296
Andrey Lushnikov0eea25e2018-04-24 22:29:511297 await evalCode(target1, 'localStorage.setItem("page1", "page1")');
1298 await evalCode(target2, 'localStorage.setItem("page2", "page2")');
1299
1300 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
1301 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
1302 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
1303 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
1304
Andrey Lushnikov69499702018-05-08 18:20:471305 const removedTargets = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331306 self.SDK.targetManager.observeTargets(
1307 {targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
Andrey Lushnikov69499702018-05-08 18:20:471308 await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
1309 this.assertEquals(removedTargets.length, 2);
1310 this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
1311 this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
Andrey Lushnikov0eea25e2018-04-24 22:29:511312
1313 this.releaseControl();
1314
1315 /**
1316 * @param {string} url
1317 * @return {!Promise<!SDK.Target>}
1318 */
1319 async function createIsolatedTarget(url) {
Andrey Lushnikov0eea25e2018-04-24 22:29:511320 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1321 browserContextIds.push(browserContextId);
1322
1323 const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
Dmitry Gozman99d7a6c2018-11-12 17:55:111324 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
Andrey Lushnikov0eea25e2018-04-24 22:29:511325
Paul Lewis4ae5f4f2020-01-23 10:19:331326 const target = self.SDK.targetManager.targets().find(target => target.id() === targetId);
Andrey Lushnikov0eea25e2018-04-24 22:29:511327 const pageAgent = target.pageAgent();
1328 await pageAgent.invoke_enable();
1329 await pageAgent.invoke_navigate({url});
1330 return target;
1331 }
1332
Andrey Lushnikov0eea25e2018-04-24 22:29:511333 async function disposeBrowserContext(browserContextId) {
Paul Lewis4ae5f4f2020-01-23 10:19:331334 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov69499702018-05-08 18:20:471335 await targetAgent.invoke_disposeBrowserContext({browserContextId});
Andrey Lushnikov0eea25e2018-04-24 22:29:511336 }
1337
1338 async function evalCode(target, code) {
1339 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1340 }
1341 };
1342
Blink Reformat4c46d092018-04-07 15:32:371343 TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
1344 this.takeControl();
1345
1346 await new Promise(callback => this._waitForTargets(2, callback));
1347
1348 async function takeLogs(target) {
1349 const code = `
1350 (function() {
1351 var result = window.logs.join(' ');
1352 window.logs = [];
1353 return result;
1354 })()
1355 `;
1356 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1357 }
1358
1359 let parentFrameOutput;
1360 let childFrameOutput;
1361
Paul Lewis4ae5f4f2020-01-23 10:19:331362 const inputAgent = self.SDK.targetManager.mainTarget().inputAgent();
1363 const runtimeAgent = self.SDK.targetManager.mainTarget().runtimeAgent();
Blink Reformat4c46d092018-04-07 15:32:371364 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
1365 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
1366 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
1367 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
1368 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
1369 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
1370 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:331371 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371372 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:331373 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371374
1375
1376 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
Mathias Bynens23ee1aa2020-03-02 12:06:381377 await runtimeAgent.invoke_evaluate({expression: "document.querySelector('iframe').focus()"});
Blink Reformat4c46d092018-04-07 15:32:371378 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
1379 parentFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331380 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371381 childFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331382 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371383
1384 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
1385 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1386 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
1387 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1388 parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
Paul Lewis4ae5f4f2020-01-23 10:19:331389 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371390 childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
Paul Lewis4ae5f4f2020-01-23 10:19:331391 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371392
1393 this.releaseControl();
1394 };
1395
Andrey Kosyakov4f7fb052019-03-19 15:53:431396 TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
Blink Reformat4c46d092018-04-07 15:32:371397 const test = this;
1398 const loggedHeaders = new Set(['cache-control', 'pragma']);
1399 function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
1400 return new Promise(fulfill => {
1401 Host.ResourceLoader.load(url, headers, callback);
1402
Sigurd Schneidera327cde2020-01-21 15:48:121403 function callback(success, headers, content, errorDescription) {
1404 test.assertEquals(expectedStatus, errorDescription.statusCode);
Blink Reformat4c46d092018-04-07 15:32:371405
1406 const headersArray = [];
1407 for (const name in headers) {
1408 const nameLower = name.toLowerCase();
Tim van der Lippe1d6e57a2019-09-30 11:55:341409 if (loggedHeaders.has(nameLower)) {
Blink Reformat4c46d092018-04-07 15:32:371410 headersArray.push(nameLower);
Tim van der Lippe1d6e57a2019-09-30 11:55:341411 }
Blink Reformat4c46d092018-04-07 15:32:371412 }
1413 headersArray.sort();
1414 test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
1415 test.assertEquals(expectedContent, content);
1416 fulfill();
1417 }
1418 });
1419 }
1420
1421 this.takeControl();
1422 await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
1423 await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
1424 await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
1425 await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
1426
Paul Lewis4ae5f4f2020-01-23 10:19:331427 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Blink Reformat4c46d092018-04-07 15:32:371428 expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
1429 {credentials: 'include'})`,
1430 awaitPromise: true
1431 });
1432 await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
1433
Paul Lewis4ae5f4f2020-01-23 10:19:331434 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Andrey Kosyakov73081cc2019-01-08 03:50:591435 expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
1436 {credentials: 'include'})`,
1437 awaitPromise: true
1438 });
1439 await testCase(
1440 baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
Andrey Kosyakov4f7fb052019-03-19 15:53:431441 await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
1442 await testCase(fileURL, undefined, 200, [], '<html>\n<body>\nDummy page.\n</body>\n</html>\n');
Rob Paveza30df0482019-10-09 23:15:491443 await testCase(fileURL + 'thisfileshouldnotbefound', undefined, 404, [], '');
Andrey Kosyakov73081cc2019-01-08 03:50:591444
Blink Reformat4c46d092018-04-07 15:32:371445 this.releaseControl();
1446 };
1447
Joey Arhar723d5b52019-04-19 01:31:391448 TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
1449 this.takeControl();
1450
1451 const testUserAgent = 'test user agent';
Paul Lewis5a922e72020-01-24 11:58:081452 self.SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
Joey Arhar723d5b52019-04-19 01:31:391453
1454 function onRequestUpdated(event) {
1455 const request = event.data;
Tim van der Lippe1d6e57a2019-09-30 11:55:341456 if (request.resourceType() !== Common.resourceTypes.WebSocket) {
Joey Arhar723d5b52019-04-19 01:31:391457 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341458 }
1459 if (!request.requestHeadersText()) {
Joey Arhar723d5b52019-04-19 01:31:391460 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341461 }
Joey Arhar723d5b52019-04-19 01:31:391462
1463 let actualUserAgent = 'no user-agent header';
1464 for (const {name, value} of request.requestHeaders()) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341465 if (name.toLowerCase() === 'user-agent') {
Joey Arhar723d5b52019-04-19 01:31:391466 actualUserAgent = value;
Tim van der Lippe1d6e57a2019-09-30 11:55:341467 }
Joey Arhar723d5b52019-04-19 01:31:391468 }
1469 this.assertEquals(testUserAgent, actualUserAgent);
1470 this.releaseControl();
1471 }
Paul Lewis4ae5f4f2020-01-23 10:19:331472 self.SDK.targetManager.addModelListener(
Joey Arhar723d5b52019-04-19 01:31:391473 SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
1474
1475 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
1476 };
1477
Blink Reformat4c46d092018-04-07 15:32:371478 /**
1479 * Serializes array of uiSourceCodes to string.
1480 * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
1481 * @return {string}
1482 */
1483 TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
1484 const names = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341485 for (let i = 0; i < uiSourceCodes.length; i++) {
Blink Reformat4c46d092018-04-07 15:32:371486 names.push('"' + uiSourceCodes[i].url() + '"');
Tim van der Lippe1d6e57a2019-09-30 11:55:341487 }
Blink Reformat4c46d092018-04-07 15:32:371488 return names.join(',');
1489 };
1490
1491 /**
1492 * Returns all loaded non anonymous uiSourceCodes.
1493 * @return {!Array.<!Workspace.UISourceCode>}
1494 */
1495 TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
1496 /**
1497 * @param {!Workspace.UISourceCode} uiSourceCode
1498 */
1499 function filterOutService(uiSourceCode) {
1500 return !uiSourceCode.project().isServiceProject();
1501 }
1502
Paul Lewis10e83a92020-01-23 14:07:581503 const uiSourceCodes = self.Workspace.workspace.uiSourceCodes();
Blink Reformat4c46d092018-04-07 15:32:371504 return uiSourceCodes.filter(filterOutService);
1505 };
1506
1507 /*
1508 * Evaluates the code in the console as if user typed it manually and invokes
1509 * the callback when the result message is received and added to the console.
1510 * @param {string} code
1511 * @param {function(string)} callback
1512 */
1513 TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
1514 function innerEvaluate() {
Paul Lewisd9907342020-01-24 13:49:471515 self.UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371516 const consoleView = Console.ConsoleView.instance();
1517 consoleView._prompt._appendCommand(code);
1518
1519 this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) {
1520 callback(viewMessage.toMessageElement().deepTextContent());
1521 }.bind(this));
1522 }
1523
1524 function showConsoleAndEvaluate() {
Paul Lewis04ccecc2020-01-22 17:15:141525 self.Common.console.showPromise().then(innerEvaluate.bind(this));
Blink Reformat4c46d092018-04-07 15:32:371526 }
1527
Paul Lewisd9907342020-01-24 13:49:471528 if (!self.UI.context.flavor(SDK.ExecutionContext)) {
1529 self.UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371530 return;
1531 }
1532 showConsoleAndEvaluate.call(this);
1533 };
1534
1535 /**
1536 * Checks that all expected scripts are present in the scripts list
1537 * in the Scripts panel.
1538 * @param {!Array.<string>} expected Regular expressions describing
1539 * expected script names.
1540 * @return {boolean} Whether all the scripts are in "scripts-files" select
1541 * box
1542 */
1543 TestSuite.prototype._scriptsAreParsed = function(expected) {
1544 const uiSourceCodes = this.nonAnonymousUISourceCodes_();
1545 // Check that at least all the expected scripts are present.
1546 const missing = expected.slice(0);
1547 for (let i = 0; i < uiSourceCodes.length; ++i) {
1548 for (let j = 0; j < missing.length; ++j) {
1549 if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
1550 missing.splice(j, 1);
1551 break;
1552 }
1553 }
1554 }
1555 return missing.length === 0;
1556 };
1557
1558 /**
1559 * Waits for script pause, checks expectations, and invokes the callback.
1560 * @param {function():void} callback
1561 */
1562 TestSuite.prototype._waitForScriptPause = function(callback) {
1563 this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback);
1564 };
1565
1566 /**
1567 * Waits until all the scripts are parsed and invokes the callback.
1568 */
1569 TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
1570 const test = this;
1571
1572 function waitForAllScripts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341573 if (test._scriptsAreParsed(expectedScripts)) {
Blink Reformat4c46d092018-04-07 15:32:371574 callback();
Tim van der Lippe1d6e57a2019-09-30 11:55:341575 } else {
Blink Reformat4c46d092018-04-07 15:32:371576 test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts);
Tim van der Lippe1d6e57a2019-09-30 11:55:341577 }
Blink Reformat4c46d092018-04-07 15:32:371578 }
1579
1580 waitForAllScripts();
1581 };
1582
1583 TestSuite.prototype._waitForTargets = function(n, callback) {
1584 checkTargets.call(this);
1585
1586 function checkTargets() {
Paul Lewis4ae5f4f2020-01-23 10:19:331587 if (self.SDK.targetManager.targets().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371588 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341589 } else {
Blink Reformat4c46d092018-04-07 15:32:371590 this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341591 }
Blink Reformat4c46d092018-04-07 15:32:371592 }
1593 };
1594
1595 TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
Paul Lewis4ae5f4f2020-01-23 10:19:331596 const runtimeModel = self.SDK.targetManager.mainTarget().model(SDK.RuntimeModel);
Blink Reformat4c46d092018-04-07 15:32:371597 checkForExecutionContexts.call(this);
1598
1599 function checkForExecutionContexts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341600 if (runtimeModel.executionContexts().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371601 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341602 } else {
Blink Reformat4c46d092018-04-07 15:32:371603 this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341604 }
Blink Reformat4c46d092018-04-07 15:32:371605 }
1606 };
1607
1608
1609 window.uiTests = new TestSuite(window.domAutomationController);
1610})(window);