blob: 070ac7cadae6f34d83240e08b1d8ed2d8a1bddea [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
Blink Reformat4c46d092018-04-07 15:32:3742 const TestSuite = class {
43 /**
44 * Test suite for interactive UI tests.
45 * @param {Object} domAutomationController DomAutomationController instance.
46 */
47 constructor(domAutomationController) {
48 this.domAutomationController_ = domAutomationController;
49 this.controlTaken_ = false;
50 this.timerId_ = -1;
51 this._asyncInvocationId = 0;
52 }
53
54 /**
55 * Key event with given key identifier.
56 */
57 static createKeyEvent(key) {
58 return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key});
59 }
60 };
61
62 /**
63 * Reports test failure.
64 * @param {string} message Failure description.
65 */
66 TestSuite.prototype.fail = function(message) {
Tim van der Lippe1d6e57a2019-09-30 11:55:3467 if (this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:3768 this.reportFailure_(message);
Tim van der Lippe1d6e57a2019-09-30 11:55:3469 } else {
Blink Reformat4c46d092018-04-07 15:32:3770 throw message;
Tim van der Lippe1d6e57a2019-09-30 11:55:3471 }
Blink Reformat4c46d092018-04-07 15:32:3772 };
73
74 /**
75 * Equals assertion tests that expected === actual.
76 * @param {!Object|boolean} expected Expected object.
77 * @param {!Object|boolean} actual Actual object.
78 * @param {string} opt_message User message to print if the test fails.
79 */
80 TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
81 if (expected !== actual) {
82 let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
Tim van der Lippe1d6e57a2019-09-30 11:55:3483 if (opt_message) {
Blink Reformat4c46d092018-04-07 15:32:3784 message = opt_message + '(' + message + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:3485 }
Blink Reformat4c46d092018-04-07 15:32:3786 this.fail(message);
87 }
88 };
89
90 /**
91 * True assertion tests that value == true.
92 * @param {!Object} value Actual object.
93 * @param {string} opt_message User message to print if the test fails.
94 */
95 TestSuite.prototype.assertTrue = function(value, opt_message) {
Tim van der Lipped7cfd142021-01-07 12:17:2496 this.assertEquals(true, Boolean(value), opt_message);
Blink Reformat4c46d092018-04-07 15:32:3797 };
98
99 /**
100 * Takes control over execution.
101 */
102 TestSuite.prototype.takeControl = function() {
103 this.controlTaken_ = true;
104 // Set up guard timer.
105 const self = this;
106 this.timerId_ = setTimeout(function() {
107 self.reportFailure_('Timeout exceeded: 20 sec');
108 }, 20000);
109 };
110
111 /**
112 * Releases control over execution.
113 */
114 TestSuite.prototype.releaseControl = function() {
115 if (this.timerId_ !== -1) {
116 clearTimeout(this.timerId_);
117 this.timerId_ = -1;
118 }
119 this.controlTaken_ = false;
120 this.reportOk_();
121 };
122
123 /**
124 * Async tests use this one to report that they are completed.
125 */
126 TestSuite.prototype.reportOk_ = function() {
127 this.domAutomationController_.send('[OK]');
128 };
129
130 /**
131 * Async tests use this one to report failures.
132 */
133 TestSuite.prototype.reportFailure_ = function(error) {
134 if (this.timerId_ !== -1) {
135 clearTimeout(this.timerId_);
136 this.timerId_ = -1;
137 }
138 this.domAutomationController_.send('[FAILED] ' + error);
139 };
140
141 /**
142 * Run specified test on a fresh instance of the test suite.
143 * @param {Array<string>} args method name followed by its parameters.
144 */
145 TestSuite.prototype.dispatchOnTestSuite = function(args) {
146 const methodName = args.shift();
147 try {
148 this[methodName].apply(this, args);
Tim van der Lippe1d6e57a2019-09-30 11:55:34149 if (!this.controlTaken_) {
Blink Reformat4c46d092018-04-07 15:32:37150 this.reportOk_();
Tim van der Lippe1d6e57a2019-09-30 11:55:34151 }
Blink Reformat4c46d092018-04-07 15:32:37152 } catch (e) {
153 this.reportFailure_(e);
154 }
155 };
156
157 /**
158 * Wrap an async method with TestSuite.{takeControl(), releaseControl()}
159 * and invoke TestSuite.reportOk_ upon completion.
160 * @param {Array<string>} args method name followed by its parameters.
161 */
162 TestSuite.prototype.waitForAsync = function(var_args) {
163 const args = Array.prototype.slice.call(arguments);
164 this.takeControl();
165 args.push(this.releaseControl.bind(this));
166 this.dispatchOnTestSuite(args);
167 };
168
169 /**
170 * Overrides the method with specified name until it's called first time.
171 * @param {!Object} receiver An object whose method to override.
172 * @param {string} methodName Name of the method to override.
173 * @param {!Function} override A function that should be called right after the
174 * overridden method returns.
175 * @param {?boolean} opt_sticky Whether restore original method after first run
176 * or not.
177 */
178 TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) {
179 const orig = receiver[methodName];
Tim van der Lippe1d6e57a2019-09-30 11:55:34180 if (typeof orig !== 'function') {
Blink Reformat4c46d092018-04-07 15:32:37181 this.fail('Cannot find method to override: ' + methodName);
Tim van der Lippe1d6e57a2019-09-30 11:55:34182 }
Blink Reformat4c46d092018-04-07 15:32:37183 const test = this;
184 receiver[methodName] = function(var_args) {
185 let result;
186 try {
187 result = orig.apply(this, arguments);
188 } finally {
Tim van der Lippe1d6e57a2019-09-30 11:55:34189 if (!opt_sticky) {
Blink Reformat4c46d092018-04-07 15:32:37190 receiver[methodName] = orig;
Tim van der Lippe1d6e57a2019-09-30 11:55:34191 }
Blink Reformat4c46d092018-04-07 15:32:37192 }
193 // In case of exception the override won't be called.
194 try {
195 override.apply(this, arguments);
196 } catch (e) {
197 test.fail('Exception in overriden method \'' + methodName + '\': ' + e);
198 }
199 return result;
200 };
201 };
202
203 /**
204 * Waits for current throttler invocations, if any.
205 * @param {!Common.Throttler} throttler
206 * @param {function()} callback
207 */
208 TestSuite.prototype.waitForThrottler = function(throttler, callback) {
209 const test = this;
210 let scheduleShouldFail = true;
211 test.addSniffer(throttler, 'schedule', onSchedule);
212
213 function hasSomethingScheduled() {
214 return throttler._isRunningProcess || throttler._process;
215 }
216
217 function checkState() {
218 if (!hasSomethingScheduled()) {
219 scheduleShouldFail = false;
220 callback();
221 return;
222 }
223
224 test.addSniffer(throttler, '_processCompletedForTests', checkState);
225 }
226
227 function onSchedule() {
Tim van der Lippe1d6e57a2019-09-30 11:55:34228 if (scheduleShouldFail) {
Blink Reformat4c46d092018-04-07 15:32:37229 test.fail('Unexpected Throttler.schedule');
Tim van der Lippe1d6e57a2019-09-30 11:55:34230 }
Blink Reformat4c46d092018-04-07 15:32:37231 }
232
233 checkState();
234 };
235
236 /**
237 * @param {string} panelName Name of the panel to show.
238 */
239 TestSuite.prototype.showPanel = function(panelName) {
Paul Lewis0a7c6b62020-01-23 16:16:22240 return self.UI.inspectorView.showPanel(panelName);
Blink Reformat4c46d092018-04-07 15:32:37241 };
242
243 // UI Tests
244
245 /**
246 * Tests that scripts tab can be open and populated with inspected scripts.
247 */
248 TestSuite.prototype.testShowScriptsTab = function() {
249 const test = this;
250 this.showPanel('sources').then(function() {
251 // There should be at least main page script.
252 this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
253 test.releaseControl();
254 });
255 }.bind(this));
256 // Wait until all scripts are added to the debugger.
257 this.takeControl();
258 };
259
260 /**
261 * Tests that scripts tab is populated with inspected scripts even if it
262 * hadn't been shown by the moment inspected paged refreshed.
263 * @see http://crbug.com/26312
264 */
265 TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() {
266 const test = this;
Paul Lewis4ae5f4f2020-01-23 10:19:33267 const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
Blink Reformat4c46d092018-04-07 15:32:37268 debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
269
270 this.showPanel('elements').then(function() {
271 // Reload inspected page. It will reset the debugger agent.
272 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
273 });
274
275 function waitUntilScriptIsParsed() {
276 debuggerModel.removeEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
277 test.showPanel('sources').then(function() {
278 test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
279 test.releaseControl();
280 });
281 });
282 }
283
284 // Wait until all scripts are added to the debugger.
285 this.takeControl();
286 };
287
288 /**
289 * Tests that scripts list contains content scripts.
290 */
291 TestSuite.prototype.testContentScriptIsPresent = function() {
292 const test = this;
293 this.showPanel('sources').then(function() {
294 test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() {
295 test.releaseControl();
296 });
297 });
298
299 // Wait until all scripts are added to the debugger.
300 this.takeControl();
301 };
302
303 /**
304 * Tests that scripts are not duplicaed on Scripts tab switch.
305 */
306 TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() {
307 const test = this;
308
309 function switchToElementsTab() {
310 test.showPanel('elements').then(function() {
311 setTimeout(switchToScriptsTab, 0);
312 });
313 }
314
315 function switchToScriptsTab() {
316 test.showPanel('sources').then(function() {
317 setTimeout(checkScriptsPanel, 0);
318 });
319 }
320
321 function checkScriptsPanel() {
322 test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.');
323 checkNoDuplicates();
324 test.releaseControl();
325 }
326
327 function checkNoDuplicates() {
328 const uiSourceCodes = test.nonAnonymousUISourceCodes_();
329 for (let i = 0; i < uiSourceCodes.length; i++) {
330 for (let j = i + 1; j < uiSourceCodes.length; j++) {
331 test.assertTrue(
332 uiSourceCodes[i].url() !== uiSourceCodes[j].url(),
333 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes));
334 }
335 }
336 }
337
338 this.showPanel('sources').then(function() {
339 test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
340 checkNoDuplicates();
341 setTimeout(switchToElementsTab, 0);
342 });
343 });
344
345 // Wait until all scripts are added to the debugger.
346 this.takeControl();
347 };
348
349 // Tests that debugger works correctly if pause event occurs when DevTools
350 // frontend is being loaded.
351 TestSuite.prototype.testPauseWhenLoadingDevTools = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33352 const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34353 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37354 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34355 }
Blink Reformat4c46d092018-04-07 15:32:37356
357 this.showPanel('sources').then(function() {
358 // Script execution can already be paused.
359
360 this._waitForScriptPause(this.releaseControl.bind(this));
361 }.bind(this));
362
363 this.takeControl();
364 };
365
366 // Tests that pressing "Pause" will pause script execution if the script
367 // is already running.
368 TestSuite.prototype.testPauseWhenScriptIsRunning = function() {
369 this.showPanel('sources').then(function() {
370 this.evaluateInConsole_('setTimeout("handleClick()", 0)', didEvaluateInConsole.bind(this));
371 }.bind(this));
372
373 function didEvaluateInConsole(resultText) {
374 this.assertTrue(!isNaN(resultText), 'Failed to get timer id: ' + resultText);
375 // Wait for some time to make sure that inspected page is running the
376 // infinite loop.
377 setTimeout(testScriptPause.bind(this), 300);
378 }
379
380 function testScriptPause() {
381 // The script should be in infinite loop. Click "Pause" button to
382 // pause it and wait for the result.
383 UI.panels.sources._togglePause();
384
385 this._waitForScriptPause(this.releaseControl.bind(this));
386 }
387
388 this.takeControl();
389 };
390
391 /**
392 * Tests network size.
393 */
394 TestSuite.prototype.testNetworkSize = function() {
395 const test = this;
396
397 function finishRequest(request, finishTime) {
398 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
399 test.releaseControl();
400 }
401
402 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
403
404 // Reload inspected page to sniff network events
405 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
406
407 this.takeControl();
408 };
409
410 /**
411 * Tests network sync size.
412 */
413 TestSuite.prototype.testNetworkSyncSize = function() {
414 const test = this;
415
416 function finishRequest(request, finishTime) {
417 test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
418 test.releaseControl();
419 }
420
421 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
422
423 // Send synchronous XHR to sniff network events
424 test.evaluateInConsole_(
425 'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {});
426
427 this.takeControl();
428 };
429
430 /**
431 * Tests network raw headers text.
432 */
433 TestSuite.prototype.testNetworkRawHeadersText = function() {
434 const test = this;
435
436 function finishRequest(request, finishTime) {
Tim van der Lippe1d6e57a2019-09-30 11:55:34437 if (!request.responseHeadersText) {
Blink Reformat4c46d092018-04-07 15:32:37438 test.fail('Failure: resource does not have response headers text');
Tim van der Lippe1d6e57a2019-09-30 11:55:34439 }
Blink Reformat4c46d092018-04-07 15:32:37440 const index = request.responseHeadersText.indexOf('Date:');
441 test.assertEquals(
442 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length');
443 test.releaseControl();
444 }
445
446 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
447
448 // Reload inspected page to sniff network events
449 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
450
451 this.takeControl();
452 };
453
454 /**
455 * Tests network timing.
456 */
457 TestSuite.prototype.testNetworkTiming = function() {
458 const test = this;
459
460 function finishRequest(request, finishTime) {
461 // Setting relaxed expectations to reduce flakiness.
462 // Server sends headers after 100ms, then sends data during another 100ms.
463 // We expect these times to be measured at least as 70ms.
464 test.assertTrue(
465 request.timing.receiveHeadersEnd - request.timing.connectStart >= 70,
466 'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' +
467 'receiveHeadersEnd=' + request.timing.receiveHeadersEnd + ', connectStart=' +
468 request.timing.connectStart + '.');
469 test.assertTrue(
470 request.responseReceivedTime - request.startTime >= 0.07,
471 'Time between responseReceivedTime and startTime should be >=0.07s, but was ' +
472 'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.');
473 test.assertTrue(
474 request.endTime - request.startTime >= 0.14,
475 'Time between endTime and startTime should be >=0.14s, but was ' +
476 'endtime=' + request.endTime + ', startTime=' + request.startTime + '.');
477
478 test.releaseControl();
479 }
480
481 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
482
483 // Reload inspected page to sniff network events
484 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
485
486 this.takeControl();
487 };
488
489 TestSuite.prototype.testPushTimes = function(url) {
490 const test = this;
491 let pendingRequestCount = 2;
492
493 function finishRequest(request, finishTime) {
494 test.assertTrue(
495 typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0,
496 `pushStart is invalid: ${request.timing.pushStart}`);
497 test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`);
498 test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime');
499 if (request.url().endsWith('?pushUseNullEndTime')) {
500 test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`);
501 } else {
502 test.assertTrue(
503 request.timing.pushStart < request.timing.pushEnd,
504 `pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`);
505 // The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant.
506 test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime');
507 test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime');
508 }
Tim van der Lippe1d6e57a2019-09-30 11:55:34509 if (!--pendingRequestCount) {
Blink Reformat4c46d092018-04-07 15:32:37510 test.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:34511 }
Blink Reformat4c46d092018-04-07 15:32:37512 }
513
514 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest, true);
515
516 test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {});
517 test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {});
518 this.takeControl();
519 };
520
521 TestSuite.prototype.testConsoleOnNavigateBack = function() {
522
523 function filteredMessages() {
Paul Lewise504fd62020-01-23 16:52:33524 return self.SDK.consoleModel.messages().filter(a => a.source !== SDK.ConsoleMessage.MessageSource.Violation);
Blink Reformat4c46d092018-04-07 15:32:37525 }
526
Tim van der Lippe1d6e57a2019-09-30 11:55:34527 if (filteredMessages().length === 1) {
Blink Reformat4c46d092018-04-07 15:32:37528 firstConsoleMessageReceived.call(this, null);
Tim van der Lippe1d6e57a2019-09-30 11:55:34529 } else {
Paul Lewise504fd62020-01-23 16:52:33530 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Tim van der Lippe1d6e57a2019-09-30 11:55:34531 }
Blink Reformat4c46d092018-04-07 15:32:37532
533
534 function firstConsoleMessageReceived(event) {
Tim van der Lippe1d6e57a2019-09-30 11:55:34535 if (event && event.data.source === SDK.ConsoleMessage.MessageSource.Violation) {
Blink Reformat4c46d092018-04-07 15:32:37536 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34537 }
Paul Lewise504fd62020-01-23 16:52:33538 self.SDK.consoleModel.removeEventListener(
539 SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
Blink Reformat4c46d092018-04-07 15:32:37540 this.evaluateInConsole_('clickLink();', didClickLink.bind(this));
541 }
542
543 function didClickLink() {
544 // Check that there are no new messages(command is not a message).
545 this.assertEquals(3, filteredMessages().length);
546 this.evaluateInConsole_('history.back();', didNavigateBack.bind(this));
547 }
548
549 function didNavigateBack() {
550 // Make sure navigation completed and possible console messages were pushed.
551 this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this));
552 }
553
554 function didCompleteNavigation() {
555 this.assertEquals(7, filteredMessages().length);
556 this.releaseControl();
557 }
558
559 this.takeControl();
560 };
561
562 TestSuite.prototype.testSharedWorker = function() {
563 function didEvaluateInConsole(resultText) {
564 this.assertEquals('2011', resultText);
565 this.releaseControl();
566 }
567 this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this));
568 this.takeControl();
569 };
570
571 TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() {
572 // Make sure the worker is loaded.
573 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00574 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37575
576 function callback() {
Simon Zündb6414c92020-03-19 07:16:40577 ProtocolClient.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37578 }
579 };
580
581 TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() {
582 this.takeControl();
Joey Arhara6abfa22019-08-08 12:23:00583 this._waitForTargets(1, callback.bind(this));
Blink Reformat4c46d092018-04-07 15:32:37584
585 function callback() {
Paul Lewis4ae5f4f2020-01-23 10:19:33586 const debuggerModel = self.SDK.targetManager.models(SDK.DebuggerModel)[0];
Blink Reformat4c46d092018-04-07 15:32:37587 if (debuggerModel.isPaused()) {
Paul Lewise504fd62020-01-23 16:52:33588 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31589 debuggerModel.resume();
Blink Reformat4c46d092018-04-07 15:32:37590 return;
591 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31592 this._waitForScriptPause(callback.bind(this));
593 }
594
595 function onConsoleMessage(event) {
596 const message = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:34597 if (message !== 'connected') {
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31598 this.fail('Unexpected message: ' + message);
Tim van der Lippe1d6e57a2019-09-30 11:55:34599 }
Alexey Kozyatinskiy88f257f2018-09-21 01:12:31600 this.releaseControl();
Blink Reformat4c46d092018-04-07 15:32:37601 }
602 };
603
Joey Arhar0585e6f2018-10-30 23:11:18604 TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
605 this.takeControl();
606 this.showPanel('network').then(() => {
Tim van der Lippe1d6e57a2019-09-30 11:55:34607 if (!document.querySelector('#network-container')) {
Joey Arhar0585e6f2018-10-30 23:11:18608 this.fail('unable to find #network-container');
Tim van der Lippe1d6e57a2019-09-30 11:55:34609 }
Joey Arhar0585e6f2018-10-30 23:11:18610 this.releaseControl();
611 });
612 };
613
Blink Reformat4c46d092018-04-07 15:32:37614 TestSuite.prototype.enableTouchEmulation = function() {
615 const deviceModeModel = new Emulation.DeviceModeModel(function() {});
Paul Lewis4ae5f4f2020-01-23 10:19:33616 deviceModeModel._target = self.SDK.targetManager.mainTarget();
Blink Reformat4c46d092018-04-07 15:32:37617 deviceModeModel._applyTouch(true, true);
618 };
619
620 TestSuite.prototype.waitForDebuggerPaused = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33621 const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
Tim van der Lippe1d6e57a2019-09-30 11:55:34622 if (debuggerModel.debuggerPausedDetails) {
Blink Reformat4c46d092018-04-07 15:32:37623 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:34624 }
Blink Reformat4c46d092018-04-07 15:32:37625
626 this.takeControl();
627 this._waitForScriptPause(this.releaseControl.bind(this));
628 };
629
630 TestSuite.prototype.switchToPanel = function(panelName) {
631 this.showPanel(panelName).then(this.releaseControl.bind(this));
632 this.takeControl();
633 };
634
635 // Regression test for crbug.com/370035.
636 TestSuite.prototype.testDeviceMetricsOverrides = function() {
637 function dumpPageMetrics() {
638 return JSON.stringify(
639 {width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
640 }
641
642 const test = this;
643
644 async function testOverrides(params, metrics, callback) {
Paul Lewis4ae5f4f2020-01-23 10:19:33645 await self.SDK.targetManager.mainTarget().emulationAgent().invoke_setDeviceMetricsOverride(params);
Blink Reformat4c46d092018-04-07 15:32:37646 test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics);
647
648 function checkMetrics(consoleResult) {
649 test.assertEquals(
650 '"' + JSON.stringify(metrics) + '"', consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params));
651 callback();
652 }
653 }
654
655 function step1() {
656 testOverrides(
657 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
658 {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
659 }
660
661 function step2() {
662 testOverrides(
663 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
664 {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
665 }
666
667 function step3() {
668 testOverrides(
669 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
670 {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
671 }
672
673 function step4() {
674 testOverrides(
675 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
676 {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
677 }
678
679 function finish() {
680 test.releaseControl();
681 }
682
683 test.takeControl();
684 step1();
685 };
686
687 TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
688 const test = this;
689 let receivedReady = false;
690
691 function signalToShowAutofill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33692 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37693 {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Paul Lewis4ae5f4f2020-01-23 10:19:33694 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37695 {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
696 }
697
698 function selectTopAutoFill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33699 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37700 {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
Paul Lewis4ae5f4f2020-01-23 10:19:33701 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37702 {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
703
704 test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
705 }
706
707 function onResultOfInput(value) {
708 // Console adds "" around the response.
709 test.assertEquals('"Abbf"', value);
710 test.releaseControl();
711 }
712
713 function onConsoleMessage(event) {
714 const message = event.data.messageText;
715 if (message === 'ready' && !receivedReady) {
716 receivedReady = true;
717 signalToShowAutofill();
718 }
719 // This log comes from the browser unittest code.
Tim van der Lippe1d6e57a2019-09-30 11:55:34720 if (message === 'didShowSuggestions') {
Blink Reformat4c46d092018-04-07 15:32:37721 selectTopAutoFill();
Tim van der Lippe1d6e57a2019-09-30 11:55:34722 }
Blink Reformat4c46d092018-04-07 15:32:37723 }
724
725 this.takeControl();
726
727 // It is possible for the ready console messagage to be already received but not handled
728 // or received later. This ensures we can catch both cases.
Paul Lewise504fd62020-01-23 16:52:33729 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37730
Paul Lewise504fd62020-01-23 16:52:33731 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:37732 if (messages.length) {
733 const text = messages[0].messageText;
734 this.assertEquals('ready', text);
735 signalToShowAutofill();
736 }
737 };
738
Pâris MEULEMANd4709cb2019-04-17 08:32:48739 TestSuite.prototype.testKeyEventUnhandled = function() {
740 function onKeyEventUnhandledKeyDown(event) {
741 this.assertEquals('keydown', event.data.type);
742 this.assertEquals('F8', event.data.key);
743 this.assertEquals(119, event.data.keyCode);
744 this.assertEquals(0, event.data.modifiers);
745 this.assertEquals('', event.data.code);
Tim van der Lippe50cfa9b2019-10-01 10:40:58746 Host.InspectorFrontendHost.events.removeEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44747 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Tim van der Lippe50cfa9b2019-10-01 10:40:58748 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44749 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33750 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48751 {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
752 }
753 function onKeyEventUnhandledKeyUp(event) {
754 this.assertEquals('keyup', event.data.type);
755 this.assertEquals('F8', event.data.key);
756 this.assertEquals(119, event.data.keyCode);
757 this.assertEquals(0, event.data.modifiers);
758 this.assertEquals('F8', event.data.code);
759 this.releaseControl();
760 }
761 this.takeControl();
Tim van der Lippe50cfa9b2019-10-01 10:40:58762 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44763 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33764 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48765 {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
766 };
767
Jack Lynchb514f9f2020-06-19 21:16:45768 // Tests that the keys that are forwarded from the browser update
769 // when their shortcuts change
770 TestSuite.prototype.testForwardedKeysChanged = function() {
Jack Lynch080a0fd2020-06-15 19:55:19771 this.takeControl();
772
773 this.addSniffer(self.UI.shortcutRegistry, '_registerBindings', () => {
774 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
775 {type: 'rawKeyDown', key: 'F1', windowsVirtualKeyCode: 112, nativeVirtualKeyCode: 112});
776 });
777 this.addSniffer(self.UI.shortcutRegistry, 'handleKey', key => {
778 this.assertEquals(112, key);
779 this.releaseControl();
780 });
781
782 self.Common.settings.moduleSetting('activeKeybindSet').set('vsCode');
783 };
784
Blink Reformat4c46d092018-04-07 15:32:37785 TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33786 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37787 {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
Paul Lewis4ae5f4f2020-01-23 10:19:33788 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37789 {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
790 };
791
Pâris MEULEMANd81f35f2019-05-07 09:04:34792 // Check that showing the certificate viewer does not crash, crbug.com/954874
793 TestSuite.prototype.testShowCertificate = function() {
Tim van der Lippe50cfa9b2019-10-01 10:40:58794 Host.InspectorFrontendHost.showCertificateViewer([
Pâris MEULEMANd81f35f2019-05-07 09:04:34795 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
796 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
797 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
798 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
799 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
800 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
801 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
802 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
803 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
804 'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
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P3ojY+x1J96relc8geMJgEtslQIxq' +
871 '/H5COEBkEveegeGTLg=='
872 ]);
873 };
874
Blink Reformat4c46d092018-04-07 15:32:37875 // Simple sanity check to make sure network throttling is wired up
876 // See crbug.com/747724
877 TestSuite.prototype.testOfflineNetworkConditions = async function() {
878 const test = this;
Paul Lewis5a922e72020-01-24 11:58:08879 self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Blink Reformat4c46d092018-04-07 15:32:37880
881 function finishRequest(request) {
882 test.assertEquals(
883 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
884 test.releaseControl();
885 }
886
887 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
888
889 test.takeControl();
890 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
891 };
892
893 TestSuite.prototype.testEmulateNetworkConditions = function() {
894 const test = this;
895
896 function testPreset(preset, messages, next) {
897 function onConsoleMessage(event) {
898 const index = messages.indexOf(event.data.messageText);
899 if (index === -1) {
900 test.fail('Unexpected message: ' + event.data.messageText);
901 return;
902 }
903
904 messages.splice(index, 1);
905 if (!messages.length) {
Paul Lewise504fd62020-01-23 16:52:33906 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37907 next();
908 }
909 }
910
Paul Lewise504fd62020-01-23 16:52:33911 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Paul Lewis5a922e72020-01-24 11:58:08912 self.SDK.multitargetNetworkManager.setNetworkConditions(preset);
Blink Reformat4c46d092018-04-07 15:32:37913 }
914
915 test.takeControl();
916 step1();
917
918 function step1() {
919 testPreset(
920 MobileThrottling.networkPresets[2],
921 [
922 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
923 ],
924 step2);
925 }
926
927 function step2() {
928 testPreset(
929 MobileThrottling.networkPresets[1],
930 [
931 'online event: online = true',
Wolfgang Beyerd451ecd2020-10-23 08:35:54932 'connection change event: type = cellular; downlinkMax = 0.3814697265625; effectiveType = 2g'
Blink Reformat4c46d092018-04-07 15:32:37933 ],
934 step3);
935 }
936
937 function step3() {
938 testPreset(
939 MobileThrottling.networkPresets[0],
Wolfgang Beyerd451ecd2020-10-23 08:35:54940 ['connection change event: type = cellular; downlinkMax = 1.373291015625; effectiveType = 3g'],
Blink Reformat4c46d092018-04-07 15:32:37941 test.releaseControl.bind(test));
942 }
943 };
944
945 TestSuite.prototype.testScreenshotRecording = function() {
946 const test = this;
947
948 function performActionsInPage(callback) {
949 let count = 0;
950 const div = document.createElement('div');
951 div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
952 document.body.appendChild(div);
953 requestAnimationFrame(frame);
954 function frame() {
955 const color = [0, 0, 0];
956 color[count % 3] = 255;
957 div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34958 if (++count > 10) {
Blink Reformat4c46d092018-04-07 15:32:37959 requestAnimationFrame(callback);
Tim van der Lippe1d6e57a2019-09-30 11:55:34960 } else {
Blink Reformat4c46d092018-04-07 15:32:37961 requestAnimationFrame(frame);
Tim van der Lippe1d6e57a2019-09-30 11:55:34962 }
Blink Reformat4c46d092018-04-07 15:32:37963 }
964 }
965
Paul Lewis6bcdb182020-01-23 11:08:05966 const captureFilmStripSetting = self.Common.settings.createSetting('timelineCaptureFilmStrip', false);
Blink Reformat4c46d092018-04-07 15:32:37967 captureFilmStripSetting.set(true);
968 test.evaluateInConsole_(performActionsInPage.toString(), function() {});
969 test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
970
971 function onTimelineDone() {
972 captureFilmStripSetting.set(false);
973 const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
974 const frames = filmStripModel.frames();
975 test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
976 loadFrameImages(frames);
977 }
978
979 function loadFrameImages(frames) {
980 const readyImages = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:34981 for (const frame of frames) {
Blink Reformat4c46d092018-04-07 15:32:37982 frame.imageDataPromise().then(onGotImageData);
Tim van der Lippe1d6e57a2019-09-30 11:55:34983 }
Blink Reformat4c46d092018-04-07 15:32:37984
985 function onGotImageData(data) {
986 const image = new Image();
Tim van der Lipped7cfd142021-01-07 12:17:24987 test.assertTrue(Boolean(data), 'No image data for frame');
Blink Reformat4c46d092018-04-07 15:32:37988 image.addEventListener('load', onLoad);
989 image.src = 'data:image/jpg;base64,' + data;
990 }
991
992 function onLoad(event) {
993 readyImages.push(event.target);
Tim van der Lippe1d6e57a2019-09-30 11:55:34994 if (readyImages.length === frames.length) {
Blink Reformat4c46d092018-04-07 15:32:37995 validateImagesAndCompleteTest(readyImages);
Tim van der Lippe1d6e57a2019-09-30 11:55:34996 }
Blink Reformat4c46d092018-04-07 15:32:37997 }
998 }
999
1000 function validateImagesAndCompleteTest(images) {
1001 let redCount = 0;
1002 let greenCount = 0;
1003 let blueCount = 0;
1004
1005 const canvas = document.createElement('canvas');
1006 const ctx = canvas.getContext('2d');
1007 for (const image of images) {
1008 test.assertTrue(image.naturalWidth > 10);
1009 test.assertTrue(image.naturalHeight > 10);
1010 canvas.width = image.naturalWidth;
1011 canvas.height = image.naturalHeight;
1012 ctx.drawImage(image, 0, 0);
1013 const data = ctx.getImageData(0, 0, 1, 1);
1014 const color = Array.prototype.join.call(data.data, ',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341015 if (data.data[0] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371016 redCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341017 } else if (data.data[1] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371018 greenCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341019 } else if (data.data[2] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371020 blueCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341021 } else {
Blink Reformat4c46d092018-04-07 15:32:371022 test.fail('Unexpected color: ' + color);
Tim van der Lippe1d6e57a2019-09-30 11:55:341023 }
Blink Reformat4c46d092018-04-07 15:32:371024 }
1025 test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed');
1026 test.releaseControl();
1027 }
1028
1029 test.takeControl();
1030 };
1031
1032 TestSuite.prototype.testSettings = function() {
1033 const test = this;
1034
1035 createSettings();
1036 test.takeControl();
1037 setTimeout(reset, 0);
1038
1039 function createSettings() {
Paul Lewis6bcdb182020-01-23 11:08:051040 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371041 localSetting.set({s: 'local', n: 1});
Paul Lewis6bcdb182020-01-23 11:08:051042 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371043 globalSetting.set({s: 'global', n: 2});
1044 }
1045
1046 function reset() {
Tim van der Lippe99e59b82019-09-30 20:00:591047 Root.Runtime.experiments.clearForTest();
Tim van der Lippe50cfa9b2019-10-01 10:40:581048 Host.InspectorFrontendHost.getPreferences(gotPreferences);
Blink Reformat4c46d092018-04-07 15:32:371049 }
1050
1051 function gotPreferences(prefs) {
1052 Main.Main._instanceForTest._createSettings(prefs);
1053
Paul Lewis6bcdb182020-01-23 11:08:051054 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371055 test.assertEquals('object', typeof localSetting.get());
1056 test.assertEquals('local', localSetting.get().s);
1057 test.assertEquals(1, localSetting.get().n);
Paul Lewis6bcdb182020-01-23 11:08:051058 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371059 test.assertEquals('object', typeof globalSetting.get());
1060 test.assertEquals('global', globalSetting.get().s);
1061 test.assertEquals(2, globalSetting.get().n);
1062 test.releaseControl();
1063 }
1064 };
1065
1066 TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
1067 const test = this;
1068 test.takeControl();
Paul Lewise504fd62020-01-23 16:52:331069 const messages = self.SDK.consoleModel.messages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341070 if (messages.length === 1) {
Blink Reformat4c46d092018-04-07 15:32:371071 checkMessages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341072 } else {
Paul Lewise504fd62020-01-23 16:52:331073 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
Tim van der Lippe1d6e57a2019-09-30 11:55:341074 }
Blink Reformat4c46d092018-04-07 15:32:371075
1076 function checkMessages() {
Paul Lewise504fd62020-01-23 16:52:331077 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371078 test.assertEquals(1, messages.length);
1079 test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
1080 test.releaseControl();
1081 }
1082 };
1083
1084 TestSuite.prototype.testConsoleContextNames = function() {
1085 const test = this;
1086 test.takeControl();
1087 this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
1088
1089 function onExecutionContexts() {
1090 const consoleView = Console.ConsoleView.instance();
1091 const selector = consoleView._consoleContextSelector;
1092 const values = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341093 for (const item of selector._items) {
Blink Reformat4c46d092018-04-07 15:32:371094 values.push(selector.titleFor(item));
Tim van der Lippe1d6e57a2019-09-30 11:55:341095 }
Blink Reformat4c46d092018-04-07 15:32:371096 test.assertEquals('top', values[0]);
1097 test.assertEquals('Simple content script', values[1]);
1098 test.releaseControl();
1099 }
1100 };
1101
1102 TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
1103 const test = this;
1104 test.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331105 self.SDK.targetManager.addModelListener(
Blink Reformat4c46d092018-04-07 15:32:371106 SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
1107
1108 this.evaluateInConsole_(`
1109 let img = document.createElement('img');
1110 img.src = "${url}";
1111 document.body.appendChild(img);
1112 `, () => {});
1113
1114 let count = 0;
1115 function onResponseReceived(event) {
Songtao Xia1e692682020-06-19 13:56:391116 const networkRequest = event.data.request;
Tim van der Lippe1d6e57a2019-09-30 11:55:341117 if (!networkRequest.url().startsWith('http')) {
Blink Reformat4c46d092018-04-07 15:32:371118 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341119 }
Blink Reformat4c46d092018-04-07 15:32:371120 switch (++count) {
1121 case 1: // Original redirect
1122 test.assertEquals(301, networkRequest.statusCode);
1123 test.assertEquals('Moved Permanently', networkRequest.statusText);
1124 test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
1125 break;
1126
1127 case 2: // HSTS internal redirect
1128 test.assertTrue(networkRequest.url().startsWith('http://'));
Blink Reformat4c46d092018-04-07 15:32:371129 test.assertEquals(307, networkRequest.statusCode);
1130 test.assertEquals('Internal Redirect', networkRequest.statusText);
1131 test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
1132 test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
1133 break;
1134
1135 case 3: // Final response
1136 test.assertTrue(networkRequest.url().startsWith('https://'));
1137 test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
1138 test.assertEquals(200, networkRequest.statusCode);
1139 test.assertEquals('OK', networkRequest.statusText);
1140 test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
1141 test.releaseControl();
1142 }
1143 }
1144 };
1145
1146 TestSuite.prototype.testDOMWarnings = function() {
Paul Lewise504fd62020-01-23 16:52:331147 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371148 this.assertEquals(1, messages.length);
1149 const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
1150 this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
1151 };
1152
1153 TestSuite.prototype.waitForTestResultsInConsole = function() {
Paul Lewise504fd62020-01-23 16:52:331154 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371155 for (let i = 0; i < messages.length; ++i) {
1156 const text = messages[i].messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341157 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371158 return;
Mathias Bynensf06e8c02020-02-28 13:58:281159 }
1160 if (/^FAIL/.test(text)) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341161 this.fail(text);
1162 } // This will throw.
Blink Reformat4c46d092018-04-07 15:32:371163 }
1164 // Neither PASS nor FAIL, so wait for more messages.
1165 function onConsoleMessage(event) {
1166 const text = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341167 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371168 this.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:341169 } else if (/^FAIL/.test(text)) {
Blink Reformat4c46d092018-04-07 15:32:371170 this.fail(text);
Tim van der Lippe1d6e57a2019-09-30 11:55:341171 }
Blink Reformat4c46d092018-04-07 15:32:371172 }
1173
Paul Lewise504fd62020-01-23 16:52:331174 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:371175 this.takeControl();
1176 };
1177
Andrey Kosyakova08cb9b2020-04-01 21:49:521178 TestSuite.prototype.waitForTestResultsAsMessage = function() {
1179 const onMessage = event => {
1180 if (!event.data.testOutput) {
1181 return;
1182 }
1183 top.removeEventListener('message', onMessage);
1184 const text = event.data.testOutput;
1185 if (text === 'PASS') {
1186 this.releaseControl();
1187 } else {
1188 this.fail(text);
1189 }
1190 };
1191 top.addEventListener('message', onMessage);
1192 this.takeControl();
1193 };
1194
Blink Reformat4c46d092018-04-07 15:32:371195 TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
1196 const original = receiver[methodName];
1197 if (typeof original !== 'function') {
Mathias Bynens23ee1aa2020-03-02 12:06:381198 this.fail(`TestSuite._overrideMethod: ${methodName} is not a function`);
Blink Reformat4c46d092018-04-07 15:32:371199 return;
1200 }
1201 receiver[methodName] = function() {
1202 let value;
1203 try {
1204 value = original.apply(receiver, arguments);
1205 } finally {
1206 receiver[methodName] = original;
1207 }
1208 override.apply(original, arguments);
1209 return value;
1210 };
1211 };
1212
1213 TestSuite.prototype.startTimeline = function(callback) {
1214 const test = this;
1215 this.showPanel('timeline').then(function() {
1216 const timeline = UI.panels.timeline;
1217 test._overrideMethod(timeline, '_recordingStarted', callback);
1218 timeline._toggleRecording();
1219 });
1220 };
1221
1222 TestSuite.prototype.stopTimeline = function(callback) {
1223 const timeline = UI.panels.timeline;
1224 this._overrideMethod(timeline, 'loadingComplete', callback);
1225 timeline._toggleRecording();
1226 };
1227
1228 TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
1229 const callback = arguments[arguments.length - 1];
1230 const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
1231 const argsString = arguments.length < 3 ?
1232 '' :
1233 Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
1234 this.evaluateInConsole_(
1235 `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
Paul Lewise504fd62020-01-23 16:52:331236 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371237
1238 function onConsoleMessage(event) {
1239 const text = event.data.messageText;
1240 if (text === doneMessage) {
Paul Lewise504fd62020-01-23 16:52:331241 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371242 callback();
1243 }
1244 }
1245 };
1246
1247 TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
1248 const test = this;
1249
1250 this.startTimeline(onRecordingStarted);
1251
1252 function onRecordingStarted() {
1253 test.invokePageFunctionAsync(functionName, pageActionsDone);
1254 }
1255
1256 function pageActionsDone() {
1257 test.stopTimeline(callback);
1258 }
1259 };
1260
1261 TestSuite.prototype.enableExperiment = function(name) {
Tim van der Lippe99e59b82019-09-30 20:00:591262 Root.Runtime.experiments.enableForTest(name);
Blink Reformat4c46d092018-04-07 15:32:371263 };
1264
1265 TestSuite.prototype.checkInputEventsPresent = function() {
1266 const expectedEvents = new Set(arguments);
1267 const model = UI.panels.timeline._performanceModel.timelineModel();
1268 const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
1269 const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
1270 const prefix = 'InputLatency::';
1271 for (const e of input) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341272 if (!e.name.startsWith(prefix)) {
Blink Reformat4c46d092018-04-07 15:32:371273 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341274 }
1275 if (e.steps.length < 2) {
Blink Reformat4c46d092018-04-07 15:32:371276 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341277 }
Blink Reformat4c46d092018-04-07 15:32:371278 if (e.name.startsWith(prefix + 'Mouse') &&
Tim van der Lippe1d6e57a2019-09-30 11:55:341279 typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') {
Blink Reformat4c46d092018-04-07 15:32:371280 throw `Missing timeWaitingForMainThread on ${e.name}`;
Tim van der Lippe1d6e57a2019-09-30 11:55:341281 }
Blink Reformat4c46d092018-04-07 15:32:371282 expectedEvents.delete(e.name.substr(prefix.length));
1283 }
Tim van der Lippe1d6e57a2019-09-30 11:55:341284 if (expectedEvents.size) {
Blink Reformat4c46d092018-04-07 15:32:371285 throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341286 }
Blink Reformat4c46d092018-04-07 15:32:371287 };
1288
1289 TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
1290 this.takeControl();
1291 await self.runtime.loadModulePromise('elements');
Tim van der Lippe1d6e57a2019-09-30 11:55:341292 if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) {
Blink Reformat4c46d092018-04-07 15:32:371293 await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f));
Tim van der Lippe1d6e57a2019-09-30 11:55:341294 }
Blink Reformat4c46d092018-04-07 15:32:371295 this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest);
1296 this.releaseControl();
1297 };
1298
Andrey Lushnikovd92662b2018-05-09 03:57:001299 TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
1300 this.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331301 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikovd92662b2018-05-09 03:57:001302 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1303 const response1 = await targetAgent.invoke_getBrowserContexts();
1304 this.assertEquals(response1.browserContextIds.length, 1);
1305 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1306 const response2 = await targetAgent.invoke_getBrowserContexts();
1307 this.assertEquals(response2.browserContextIds.length, 0);
1308 this.releaseControl();
1309 };
1310
Peter Marshalld2f58c32020-04-21 13:23:131311 TestSuite.prototype.testNewWindowFromBrowserContext = async function(url) {
1312 this.takeControl();
1313 // Create a BrowserContext.
1314 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
1315 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1316
1317 // Cause a Browser to be created with the temp profile.
1318 const {targetId} =
1319 await targetAgent.invoke_createTarget({url: 'data:text/html,', browserContextId, newWindow: true});
1320 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
1321
1322 // Destroy the temp profile.
1323 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1324
1325 this.releaseControl();
1326 };
1327
Andrey Lushnikov0eea25e2018-04-24 22:29:511328 TestSuite.prototype.testCreateBrowserContext = async function(url) {
1329 this.takeControl();
1330 const browserContextIds = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331331 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov0eea25e2018-04-24 22:29:511332
1333 const target1 = await createIsolatedTarget(url);
1334 const target2 = await createIsolatedTarget(url);
1335
Andrey Lushnikov07477b42018-05-08 22:00:521336 const response = await targetAgent.invoke_getBrowserContexts();
1337 this.assertEquals(response.browserContextIds.length, 2);
1338 this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
1339 this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
1340
Andrey Lushnikov0eea25e2018-04-24 22:29:511341 await evalCode(target1, 'localStorage.setItem("page1", "page1")');
1342 await evalCode(target2, 'localStorage.setItem("page2", "page2")');
1343
1344 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
1345 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
1346 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
1347 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
1348
Andrey Lushnikov69499702018-05-08 18:20:471349 const removedTargets = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331350 self.SDK.targetManager.observeTargets(
1351 {targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
Andrey Lushnikov69499702018-05-08 18:20:471352 await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
1353 this.assertEquals(removedTargets.length, 2);
1354 this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
1355 this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
Andrey Lushnikov0eea25e2018-04-24 22:29:511356
1357 this.releaseControl();
1358
1359 /**
1360 * @param {string} url
1361 * @return {!Promise<!SDK.Target>}
1362 */
1363 async function createIsolatedTarget(url) {
Andrey Lushnikov0eea25e2018-04-24 22:29:511364 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1365 browserContextIds.push(browserContextId);
1366
1367 const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
Dmitry Gozman99d7a6c2018-11-12 17:55:111368 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
Andrey Lushnikov0eea25e2018-04-24 22:29:511369
Paul Lewis4ae5f4f2020-01-23 10:19:331370 const target = self.SDK.targetManager.targets().find(target => target.id() === targetId);
Andrey Lushnikov0eea25e2018-04-24 22:29:511371 const pageAgent = target.pageAgent();
1372 await pageAgent.invoke_enable();
1373 await pageAgent.invoke_navigate({url});
1374 return target;
1375 }
1376
Andrey Lushnikov0eea25e2018-04-24 22:29:511377 async function disposeBrowserContext(browserContextId) {
Paul Lewis4ae5f4f2020-01-23 10:19:331378 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov69499702018-05-08 18:20:471379 await targetAgent.invoke_disposeBrowserContext({browserContextId});
Andrey Lushnikov0eea25e2018-04-24 22:29:511380 }
1381
1382 async function evalCode(target, code) {
1383 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1384 }
1385 };
1386
Blink Reformat4c46d092018-04-07 15:32:371387 TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
1388 this.takeControl();
1389
1390 await new Promise(callback => this._waitForTargets(2, callback));
1391
1392 async function takeLogs(target) {
1393 const code = `
1394 (function() {
1395 var result = window.logs.join(' ');
1396 window.logs = [];
1397 return result;
1398 })()
1399 `;
1400 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1401 }
1402
1403 let parentFrameOutput;
1404 let childFrameOutput;
1405
Paul Lewis4ae5f4f2020-01-23 10:19:331406 const inputAgent = self.SDK.targetManager.mainTarget().inputAgent();
1407 const runtimeAgent = self.SDK.targetManager.mainTarget().runtimeAgent();
Blink Reformat4c46d092018-04-07 15:32:371408 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
1409 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
1410 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
1411 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
1412 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
1413 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
1414 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:331415 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371416 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:331417 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371418
1419
1420 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
Mathias Bynens23ee1aa2020-03-02 12:06:381421 await runtimeAgent.invoke_evaluate({expression: "document.querySelector('iframe').focus()"});
Blink Reformat4c46d092018-04-07 15:32:371422 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
1423 parentFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331424 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371425 childFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331426 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371427
1428 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
1429 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1430 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
1431 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1432 parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
Paul Lewis4ae5f4f2020-01-23 10:19:331433 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371434 childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
Paul Lewis4ae5f4f2020-01-23 10:19:331435 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371436
1437 this.releaseControl();
1438 };
1439
Andrey Kosyakov4f7fb052019-03-19 15:53:431440 TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
Blink Reformat4c46d092018-04-07 15:32:371441 const test = this;
1442 const loggedHeaders = new Set(['cache-control', 'pragma']);
1443 function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
1444 return new Promise(fulfill => {
1445 Host.ResourceLoader.load(url, headers, callback);
1446
Sigurd Schneidera327cde2020-01-21 15:48:121447 function callback(success, headers, content, errorDescription) {
1448 test.assertEquals(expectedStatus, errorDescription.statusCode);
Blink Reformat4c46d092018-04-07 15:32:371449
1450 const headersArray = [];
1451 for (const name in headers) {
1452 const nameLower = name.toLowerCase();
Tim van der Lippe1d6e57a2019-09-30 11:55:341453 if (loggedHeaders.has(nameLower)) {
Blink Reformat4c46d092018-04-07 15:32:371454 headersArray.push(nameLower);
Tim van der Lippe1d6e57a2019-09-30 11:55:341455 }
Blink Reformat4c46d092018-04-07 15:32:371456 }
1457 headersArray.sort();
1458 test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
1459 test.assertEquals(expectedContent, content);
1460 fulfill();
1461 }
1462 });
1463 }
1464
1465 this.takeControl();
1466 await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
1467 await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
1468 await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
1469 await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
1470
Paul Lewis4ae5f4f2020-01-23 10:19:331471 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Blink Reformat4c46d092018-04-07 15:32:371472 expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
1473 {credentials: 'include'})`,
1474 awaitPromise: true
1475 });
1476 await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
1477
Paul Lewis4ae5f4f2020-01-23 10:19:331478 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Andrey Kosyakov73081cc2019-01-08 03:50:591479 expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
1480 {credentials: 'include'})`,
1481 awaitPromise: true
1482 });
1483 await testCase(
1484 baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
Andrey Kosyakov4f7fb052019-03-19 15:53:431485 await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
1486 await testCase(fileURL, undefined, 200, [], '<html>\n<body>\nDummy page.\n</body>\n</html>\n');
Rob Paveza30df0482019-10-09 23:15:491487 await testCase(fileURL + 'thisfileshouldnotbefound', undefined, 404, [], '');
Andrey Kosyakov73081cc2019-01-08 03:50:591488
Blink Reformat4c46d092018-04-07 15:32:371489 this.releaseControl();
1490 };
1491
Joey Arhar723d5b52019-04-19 01:31:391492 TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
1493 this.takeControl();
1494
1495 const testUserAgent = 'test user agent';
Paul Lewis5a922e72020-01-24 11:58:081496 self.SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
Joey Arhar723d5b52019-04-19 01:31:391497
1498 function onRequestUpdated(event) {
1499 const request = event.data;
Tim van der Lippe1d6e57a2019-09-30 11:55:341500 if (request.resourceType() !== Common.resourceTypes.WebSocket) {
Joey Arhar723d5b52019-04-19 01:31:391501 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341502 }
1503 if (!request.requestHeadersText()) {
Joey Arhar723d5b52019-04-19 01:31:391504 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341505 }
Joey Arhar723d5b52019-04-19 01:31:391506
1507 let actualUserAgent = 'no user-agent header';
1508 for (const {name, value} of request.requestHeaders()) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341509 if (name.toLowerCase() === 'user-agent') {
Joey Arhar723d5b52019-04-19 01:31:391510 actualUserAgent = value;
Tim van der Lippe1d6e57a2019-09-30 11:55:341511 }
Joey Arhar723d5b52019-04-19 01:31:391512 }
1513 this.assertEquals(testUserAgent, actualUserAgent);
1514 this.releaseControl();
1515 }
Paul Lewis4ae5f4f2020-01-23 10:19:331516 self.SDK.targetManager.addModelListener(
Joey Arhar723d5b52019-04-19 01:31:391517 SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
1518
1519 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
1520 };
1521
Blink Reformat4c46d092018-04-07 15:32:371522 /**
1523 * Serializes array of uiSourceCodes to string.
1524 * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
1525 * @return {string}
1526 */
1527 TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
1528 const names = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341529 for (let i = 0; i < uiSourceCodes.length; i++) {
Blink Reformat4c46d092018-04-07 15:32:371530 names.push('"' + uiSourceCodes[i].url() + '"');
Tim van der Lippe1d6e57a2019-09-30 11:55:341531 }
Blink Reformat4c46d092018-04-07 15:32:371532 return names.join(',');
1533 };
1534
1535 /**
1536 * Returns all loaded non anonymous uiSourceCodes.
1537 * @return {!Array.<!Workspace.UISourceCode>}
1538 */
1539 TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
1540 /**
1541 * @param {!Workspace.UISourceCode} uiSourceCode
1542 */
1543 function filterOutService(uiSourceCode) {
1544 return !uiSourceCode.project().isServiceProject();
1545 }
1546
Paul Lewis10e83a92020-01-23 14:07:581547 const uiSourceCodes = self.Workspace.workspace.uiSourceCodes();
Blink Reformat4c46d092018-04-07 15:32:371548 return uiSourceCodes.filter(filterOutService);
1549 };
1550
1551 /*
1552 * Evaluates the code in the console as if user typed it manually and invokes
1553 * the callback when the result message is received and added to the console.
1554 * @param {string} code
1555 * @param {function(string)} callback
1556 */
1557 TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
1558 function innerEvaluate() {
Paul Lewisd9907342020-01-24 13:49:471559 self.UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371560 const consoleView = Console.ConsoleView.instance();
1561 consoleView._prompt._appendCommand(code);
1562
1563 this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) {
1564 callback(viewMessage.toMessageElement().deepTextContent());
1565 }.bind(this));
1566 }
1567
1568 function showConsoleAndEvaluate() {
Paul Lewis04ccecc2020-01-22 17:15:141569 self.Common.console.showPromise().then(innerEvaluate.bind(this));
Blink Reformat4c46d092018-04-07 15:32:371570 }
1571
Paul Lewisd9907342020-01-24 13:49:471572 if (!self.UI.context.flavor(SDK.ExecutionContext)) {
1573 self.UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371574 return;
1575 }
1576 showConsoleAndEvaluate.call(this);
1577 };
1578
1579 /**
1580 * Checks that all expected scripts are present in the scripts list
1581 * in the Scripts panel.
1582 * @param {!Array.<string>} expected Regular expressions describing
1583 * expected script names.
1584 * @return {boolean} Whether all the scripts are in "scripts-files" select
1585 * box
1586 */
1587 TestSuite.prototype._scriptsAreParsed = function(expected) {
1588 const uiSourceCodes = this.nonAnonymousUISourceCodes_();
1589 // Check that at least all the expected scripts are present.
1590 const missing = expected.slice(0);
1591 for (let i = 0; i < uiSourceCodes.length; ++i) {
1592 for (let j = 0; j < missing.length; ++j) {
1593 if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
1594 missing.splice(j, 1);
1595 break;
1596 }
1597 }
1598 }
1599 return missing.length === 0;
1600 };
1601
1602 /**
1603 * Waits for script pause, checks expectations, and invokes the callback.
1604 * @param {function():void} callback
1605 */
1606 TestSuite.prototype._waitForScriptPause = function(callback) {
1607 this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback);
1608 };
1609
1610 /**
1611 * Waits until all the scripts are parsed and invokes the callback.
1612 */
1613 TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
1614 const test = this;
1615
1616 function waitForAllScripts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341617 if (test._scriptsAreParsed(expectedScripts)) {
Blink Reformat4c46d092018-04-07 15:32:371618 callback();
Tim van der Lippe1d6e57a2019-09-30 11:55:341619 } else {
Blink Reformat4c46d092018-04-07 15:32:371620 test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts);
Tim van der Lippe1d6e57a2019-09-30 11:55:341621 }
Blink Reformat4c46d092018-04-07 15:32:371622 }
1623
1624 waitForAllScripts();
1625 };
1626
1627 TestSuite.prototype._waitForTargets = function(n, callback) {
1628 checkTargets.call(this);
1629
1630 function checkTargets() {
Paul Lewis4ae5f4f2020-01-23 10:19:331631 if (self.SDK.targetManager.targets().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371632 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341633 } else {
Blink Reformat4c46d092018-04-07 15:32:371634 this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341635 }
Blink Reformat4c46d092018-04-07 15:32:371636 }
1637 };
1638
1639 TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
Paul Lewis4ae5f4f2020-01-23 10:19:331640 const runtimeModel = self.SDK.targetManager.mainTarget().model(SDK.RuntimeModel);
Blink Reformat4c46d092018-04-07 15:32:371641 checkForExecutionContexts.call(this);
1642
1643 function checkForExecutionContexts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341644 if (runtimeModel.executionContexts().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371645 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341646 } else {
Blink Reformat4c46d092018-04-07 15:32:371647 this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341648 }
Blink Reformat4c46d092018-04-07 15:32:371649 }
1650 };
1651
1652
1653 window.uiTests = new TestSuite(window.domAutomationController);
1654})(window);