blob: 8154822d24dba48f3e8f2f66d91ec3a790dad61b [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(
Benedikt Meurer62b49da2021-02-18 09:15:55650 JSON.stringify(JSON.stringify(metrics)), consoleResult,
651 'Wrong metrics for params: ' + JSON.stringify(params));
Blink Reformat4c46d092018-04-07 15:32:37652 callback();
653 }
654 }
655
656 function step1() {
657 testOverrides(
658 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
659 {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
660 }
661
662 function step2() {
663 testOverrides(
664 {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
665 {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
666 }
667
668 function step3() {
669 testOverrides(
670 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
671 {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
672 }
673
674 function step4() {
675 testOverrides(
676 {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
677 {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
678 }
679
680 function finish() {
681 test.releaseControl();
682 }
683
684 test.takeControl();
685 step1();
686 };
687
688 TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
689 const test = this;
690 let receivedReady = false;
691
692 function signalToShowAutofill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33693 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37694 {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
Paul Lewis4ae5f4f2020-01-23 10:19:33695 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37696 {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
697 }
698
699 function selectTopAutoFill() {
Paul Lewis4ae5f4f2020-01-23 10:19:33700 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37701 {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
Paul Lewis4ae5f4f2020-01-23 10:19:33702 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37703 {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
704
705 test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
706 }
707
708 function onResultOfInput(value) {
709 // Console adds "" around the response.
710 test.assertEquals('"Abbf"', value);
711 test.releaseControl();
712 }
713
714 function onConsoleMessage(event) {
715 const message = event.data.messageText;
716 if (message === 'ready' && !receivedReady) {
717 receivedReady = true;
718 signalToShowAutofill();
719 }
720 // This log comes from the browser unittest code.
Tim van der Lippe1d6e57a2019-09-30 11:55:34721 if (message === 'didShowSuggestions') {
Blink Reformat4c46d092018-04-07 15:32:37722 selectTopAutoFill();
Tim van der Lippe1d6e57a2019-09-30 11:55:34723 }
Blink Reformat4c46d092018-04-07 15:32:37724 }
725
726 this.takeControl();
727
728 // It is possible for the ready console messagage to be already received but not handled
729 // or received later. This ensures we can catch both cases.
Paul Lewise504fd62020-01-23 16:52:33730 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37731
Paul Lewise504fd62020-01-23 16:52:33732 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:37733 if (messages.length) {
734 const text = messages[0].messageText;
735 this.assertEquals('ready', text);
736 signalToShowAutofill();
737 }
738 };
739
Pâris MEULEMANd4709cb2019-04-17 08:32:48740 TestSuite.prototype.testKeyEventUnhandled = function() {
741 function onKeyEventUnhandledKeyDown(event) {
742 this.assertEquals('keydown', event.data.type);
743 this.assertEquals('F8', event.data.key);
744 this.assertEquals(119, event.data.keyCode);
745 this.assertEquals(0, event.data.modifiers);
746 this.assertEquals('', event.data.code);
Tim van der Lippe50cfa9b2019-10-01 10:40:58747 Host.InspectorFrontendHost.events.removeEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44748 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Tim van der Lippe50cfa9b2019-10-01 10:40:58749 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44750 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33751 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48752 {type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
753 }
754 function onKeyEventUnhandledKeyUp(event) {
755 this.assertEquals('keyup', event.data.type);
756 this.assertEquals('F8', event.data.key);
757 this.assertEquals(119, event.data.keyCode);
758 this.assertEquals(0, event.data.modifiers);
759 this.assertEquals('F8', event.data.code);
760 this.releaseControl();
761 }
762 this.takeControl();
Tim van der Lippe50cfa9b2019-10-01 10:40:58763 Host.InspectorFrontendHost.events.addEventListener(
Tim van der Lippe7b190162019-09-27 15:10:44764 Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Paul Lewis4ae5f4f2020-01-23 10:19:33765 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Pâris MEULEMANd4709cb2019-04-17 08:32:48766 {type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
767 };
768
Jack Lynchb514f9f2020-06-19 21:16:45769 // Tests that the keys that are forwarded from the browser update
770 // when their shortcuts change
771 TestSuite.prototype.testForwardedKeysChanged = function() {
Jack Lynch080a0fd2020-06-15 19:55:19772 this.takeControl();
773
774 this.addSniffer(self.UI.shortcutRegistry, '_registerBindings', () => {
775 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
776 {type: 'rawKeyDown', key: 'F1', windowsVirtualKeyCode: 112, nativeVirtualKeyCode: 112});
777 });
778 this.addSniffer(self.UI.shortcutRegistry, 'handleKey', key => {
779 this.assertEquals(112, key);
780 this.releaseControl();
781 });
782
783 self.Common.settings.moduleSetting('activeKeybindSet').set('vsCode');
784 };
785
Blink Reformat4c46d092018-04-07 15:32:37786 TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
Paul Lewis4ae5f4f2020-01-23 10:19:33787 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37788 {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
Paul Lewis4ae5f4f2020-01-23 10:19:33789 self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
Blink Reformat4c46d092018-04-07 15:32:37790 {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
791 };
792
Pâris MEULEMANd81f35f2019-05-07 09:04:34793 // Check that showing the certificate viewer does not crash, crbug.com/954874
794 TestSuite.prototype.testShowCertificate = function() {
Tim van der Lippe50cfa9b2019-10-01 10:40:58795 Host.InspectorFrontendHost.showCertificateViewer([
Pâris MEULEMANd81f35f2019-05-07 09:04:34796 'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
797 'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
798 'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
799 'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
800 'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
801 'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
802 'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
803 'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
804 'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
805 'X7qUz7Hvr3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TZsXjAzlAcmg' +
871 'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
872 '/H5COEBkEveegeGTLg=='
873 ]);
874 };
875
Paul Lewise407fce2021-02-26 09:59:31876 // Simple check to make sure network throttling is wired up
Blink Reformat4c46d092018-04-07 15:32:37877 // See crbug.com/747724
878 TestSuite.prototype.testOfflineNetworkConditions = async function() {
879 const test = this;
Paul Lewis5a922e72020-01-24 11:58:08880 self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
Blink Reformat4c46d092018-04-07 15:32:37881
882 function finishRequest(request) {
883 test.assertEquals(
884 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
885 test.releaseControl();
886 }
887
888 this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest);
889
890 test.takeControl();
891 test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
892 };
893
894 TestSuite.prototype.testEmulateNetworkConditions = function() {
895 const test = this;
896
897 function testPreset(preset, messages, next) {
898 function onConsoleMessage(event) {
899 const index = messages.indexOf(event.data.messageText);
900 if (index === -1) {
901 test.fail('Unexpected message: ' + event.data.messageText);
902 return;
903 }
904
905 messages.splice(index, 1);
906 if (!messages.length) {
Paul Lewise504fd62020-01-23 16:52:33907 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:37908 next();
909 }
910 }
911
Paul Lewise504fd62020-01-23 16:52:33912 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Paul Lewis5a922e72020-01-24 11:58:08913 self.SDK.multitargetNetworkManager.setNetworkConditions(preset);
Blink Reformat4c46d092018-04-07 15:32:37914 }
915
916 test.takeControl();
917 step1();
918
919 function step1() {
920 testPreset(
921 MobileThrottling.networkPresets[2],
922 [
923 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
924 ],
925 step2);
926 }
927
928 function step2() {
929 testPreset(
930 MobileThrottling.networkPresets[1],
931 [
932 'online event: online = true',
Wolfgang Beyerd451ecd2020-10-23 08:35:54933 'connection change event: type = cellular; downlinkMax = 0.3814697265625; effectiveType = 2g'
Blink Reformat4c46d092018-04-07 15:32:37934 ],
935 step3);
936 }
937
938 function step3() {
939 testPreset(
940 MobileThrottling.networkPresets[0],
Wolfgang Beyerd451ecd2020-10-23 08:35:54941 ['connection change event: type = cellular; downlinkMax = 1.373291015625; effectiveType = 3g'],
Blink Reformat4c46d092018-04-07 15:32:37942 test.releaseControl.bind(test));
943 }
944 };
945
946 TestSuite.prototype.testScreenshotRecording = function() {
947 const test = this;
948
949 function performActionsInPage(callback) {
950 let count = 0;
951 const div = document.createElement('div');
952 div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
953 document.body.appendChild(div);
954 requestAnimationFrame(frame);
955 function frame() {
956 const color = [0, 0, 0];
957 color[count % 3] = 255;
958 div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
Tim van der Lippe1d6e57a2019-09-30 11:55:34959 if (++count > 10) {
Blink Reformat4c46d092018-04-07 15:32:37960 requestAnimationFrame(callback);
Tim van der Lippe1d6e57a2019-09-30 11:55:34961 } else {
Blink Reformat4c46d092018-04-07 15:32:37962 requestAnimationFrame(frame);
Tim van der Lippe1d6e57a2019-09-30 11:55:34963 }
Blink Reformat4c46d092018-04-07 15:32:37964 }
965 }
966
Paul Lewis6bcdb182020-01-23 11:08:05967 const captureFilmStripSetting = self.Common.settings.createSetting('timelineCaptureFilmStrip', false);
Blink Reformat4c46d092018-04-07 15:32:37968 captureFilmStripSetting.set(true);
969 test.evaluateInConsole_(performActionsInPage.toString(), function() {});
970 test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
971
972 function onTimelineDone() {
973 captureFilmStripSetting.set(false);
974 const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
975 const frames = filmStripModel.frames();
976 test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
977 loadFrameImages(frames);
978 }
979
980 function loadFrameImages(frames) {
981 const readyImages = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:34982 for (const frame of frames) {
Blink Reformat4c46d092018-04-07 15:32:37983 frame.imageDataPromise().then(onGotImageData);
Tim van der Lippe1d6e57a2019-09-30 11:55:34984 }
Blink Reformat4c46d092018-04-07 15:32:37985
986 function onGotImageData(data) {
987 const image = new Image();
Tim van der Lipped7cfd142021-01-07 12:17:24988 test.assertTrue(Boolean(data), 'No image data for frame');
Blink Reformat4c46d092018-04-07 15:32:37989 image.addEventListener('load', onLoad);
990 image.src = 'data:image/jpg;base64,' + data;
991 }
992
993 function onLoad(event) {
994 readyImages.push(event.target);
Tim van der Lippe1d6e57a2019-09-30 11:55:34995 if (readyImages.length === frames.length) {
Blink Reformat4c46d092018-04-07 15:32:37996 validateImagesAndCompleteTest(readyImages);
Tim van der Lippe1d6e57a2019-09-30 11:55:34997 }
Blink Reformat4c46d092018-04-07 15:32:37998 }
999 }
1000
1001 function validateImagesAndCompleteTest(images) {
1002 let redCount = 0;
1003 let greenCount = 0;
1004 let blueCount = 0;
1005
1006 const canvas = document.createElement('canvas');
1007 const ctx = canvas.getContext('2d');
1008 for (const image of images) {
1009 test.assertTrue(image.naturalWidth > 10);
1010 test.assertTrue(image.naturalHeight > 10);
1011 canvas.width = image.naturalWidth;
1012 canvas.height = image.naturalHeight;
1013 ctx.drawImage(image, 0, 0);
1014 const data = ctx.getImageData(0, 0, 1, 1);
1015 const color = Array.prototype.join.call(data.data, ',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341016 if (data.data[0] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371017 redCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341018 } else if (data.data[1] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371019 greenCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341020 } else if (data.data[2] > 200) {
Blink Reformat4c46d092018-04-07 15:32:371021 blueCount++;
Tim van der Lippe1d6e57a2019-09-30 11:55:341022 } else {
Blink Reformat4c46d092018-04-07 15:32:371023 test.fail('Unexpected color: ' + color);
Tim van der Lippe1d6e57a2019-09-30 11:55:341024 }
Blink Reformat4c46d092018-04-07 15:32:371025 }
Paul Lewise407fce2021-02-26 09:59:311026 test.assertTrue(redCount && greenCount && blueCount, 'Color check failed');
Blink Reformat4c46d092018-04-07 15:32:371027 test.releaseControl();
1028 }
1029
1030 test.takeControl();
1031 };
1032
1033 TestSuite.prototype.testSettings = function() {
1034 const test = this;
1035
1036 createSettings();
1037 test.takeControl();
1038 setTimeout(reset, 0);
1039
1040 function createSettings() {
Paul Lewis6bcdb182020-01-23 11:08:051041 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371042 localSetting.set({s: 'local', n: 1});
Paul Lewis6bcdb182020-01-23 11:08:051043 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371044 globalSetting.set({s: 'global', n: 2});
1045 }
1046
1047 function reset() {
Tim van der Lippe99e59b82019-09-30 20:00:591048 Root.Runtime.experiments.clearForTest();
Tim van der Lippe50cfa9b2019-10-01 10:40:581049 Host.InspectorFrontendHost.getPreferences(gotPreferences);
Blink Reformat4c46d092018-04-07 15:32:371050 }
1051
1052 function gotPreferences(prefs) {
1053 Main.Main._instanceForTest._createSettings(prefs);
1054
Paul Lewis6bcdb182020-01-23 11:08:051055 const localSetting = self.Common.settings.createLocalSetting('local', undefined);
Blink Reformat4c46d092018-04-07 15:32:371056 test.assertEquals('object', typeof localSetting.get());
1057 test.assertEquals('local', localSetting.get().s);
1058 test.assertEquals(1, localSetting.get().n);
Paul Lewis6bcdb182020-01-23 11:08:051059 const globalSetting = self.Common.settings.createSetting('global', undefined);
Blink Reformat4c46d092018-04-07 15:32:371060 test.assertEquals('object', typeof globalSetting.get());
1061 test.assertEquals('global', globalSetting.get().s);
1062 test.assertEquals(2, globalSetting.get().n);
1063 test.releaseControl();
1064 }
1065 };
1066
1067 TestSuite.prototype.testWindowInitializedOnNavigateBack = function() {
1068 const test = this;
1069 test.takeControl();
Paul Lewise504fd62020-01-23 16:52:331070 const messages = self.SDK.consoleModel.messages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341071 if (messages.length === 1) {
Blink Reformat4c46d092018-04-07 15:32:371072 checkMessages();
Tim van der Lippe1d6e57a2019-09-30 11:55:341073 } else {
Paul Lewise504fd62020-01-23 16:52:331074 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this);
Tim van der Lippe1d6e57a2019-09-30 11:55:341075 }
Blink Reformat4c46d092018-04-07 15:32:371076
1077 function checkMessages() {
Paul Lewise504fd62020-01-23 16:52:331078 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371079 test.assertEquals(1, messages.length);
1080 test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1);
1081 test.releaseControl();
1082 }
1083 };
1084
1085 TestSuite.prototype.testConsoleContextNames = function() {
1086 const test = this;
1087 test.takeControl();
1088 this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this)));
1089
1090 function onExecutionContexts() {
1091 const consoleView = Console.ConsoleView.instance();
1092 const selector = consoleView._consoleContextSelector;
1093 const values = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341094 for (const item of selector._items) {
Blink Reformat4c46d092018-04-07 15:32:371095 values.push(selector.titleFor(item));
Tim van der Lippe1d6e57a2019-09-30 11:55:341096 }
Blink Reformat4c46d092018-04-07 15:32:371097 test.assertEquals('top', values[0]);
1098 test.assertEquals('Simple content script', values[1]);
1099 test.releaseControl();
1100 }
1101 };
1102
1103 TestSuite.prototype.testRawHeadersWithHSTS = function(url) {
1104 const test = this;
1105 test.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331106 self.SDK.targetManager.addModelListener(
Blink Reformat4c46d092018-04-07 15:32:371107 SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived);
1108
1109 this.evaluateInConsole_(`
1110 let img = document.createElement('img');
1111 img.src = "${url}";
1112 document.body.appendChild(img);
1113 `, () => {});
1114
1115 let count = 0;
1116 function onResponseReceived(event) {
Songtao Xia1e692682020-06-19 13:56:391117 const networkRequest = event.data.request;
Tim van der Lippe1d6e57a2019-09-30 11:55:341118 if (!networkRequest.url().startsWith('http')) {
Blink Reformat4c46d092018-04-07 15:32:371119 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341120 }
Blink Reformat4c46d092018-04-07 15:32:371121 switch (++count) {
1122 case 1: // Original redirect
1123 test.assertEquals(301, networkRequest.statusCode);
1124 test.assertEquals('Moved Permanently', networkRequest.statusText);
1125 test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location')));
1126 break;
1127
1128 case 2: // HSTS internal redirect
1129 test.assertTrue(networkRequest.url().startsWith('http://'));
Blink Reformat4c46d092018-04-07 15:32:371130 test.assertEquals(307, networkRequest.statusCode);
1131 test.assertEquals('Internal Redirect', networkRequest.statusText);
1132 test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason'));
1133 test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://'));
1134 break;
1135
1136 case 3: // Final response
1137 test.assertTrue(networkRequest.url().startsWith('https://'));
1138 test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1'));
1139 test.assertEquals(200, networkRequest.statusCode);
1140 test.assertEquals('OK', networkRequest.statusText);
1141 test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length'));
1142 test.releaseControl();
1143 }
1144 }
1145 };
1146
1147 TestSuite.prototype.testDOMWarnings = function() {
Paul Lewise504fd62020-01-23 16:52:331148 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371149 this.assertEquals(1, messages.length);
1150 const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:';
1151 this.assertTrue(messages[0].messageText.startsWith(expectedPrefix));
1152 };
1153
1154 TestSuite.prototype.waitForTestResultsInConsole = function() {
Paul Lewise504fd62020-01-23 16:52:331155 const messages = self.SDK.consoleModel.messages();
Blink Reformat4c46d092018-04-07 15:32:371156 for (let i = 0; i < messages.length; ++i) {
1157 const text = messages[i].messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341158 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371159 return;
Mathias Bynensf06e8c02020-02-28 13:58:281160 }
1161 if (/^FAIL/.test(text)) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341162 this.fail(text);
1163 } // This will throw.
Blink Reformat4c46d092018-04-07 15:32:371164 }
1165 // Neither PASS nor FAIL, so wait for more messages.
1166 function onConsoleMessage(event) {
1167 const text = event.data.messageText;
Tim van der Lippe1d6e57a2019-09-30 11:55:341168 if (text === 'PASS') {
Blink Reformat4c46d092018-04-07 15:32:371169 this.releaseControl();
Tim van der Lippe1d6e57a2019-09-30 11:55:341170 } else if (/^FAIL/.test(text)) {
Blink Reformat4c46d092018-04-07 15:32:371171 this.fail(text);
Tim van der Lippe1d6e57a2019-09-30 11:55:341172 }
Blink Reformat4c46d092018-04-07 15:32:371173 }
1174
Paul Lewise504fd62020-01-23 16:52:331175 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
Blink Reformat4c46d092018-04-07 15:32:371176 this.takeControl();
1177 };
1178
Andrey Kosyakova08cb9b2020-04-01 21:49:521179 TestSuite.prototype.waitForTestResultsAsMessage = function() {
1180 const onMessage = event => {
1181 if (!event.data.testOutput) {
1182 return;
1183 }
1184 top.removeEventListener('message', onMessage);
1185 const text = event.data.testOutput;
1186 if (text === 'PASS') {
1187 this.releaseControl();
1188 } else {
1189 this.fail(text);
1190 }
1191 };
1192 top.addEventListener('message', onMessage);
1193 this.takeControl();
1194 };
1195
Blink Reformat4c46d092018-04-07 15:32:371196 TestSuite.prototype._overrideMethod = function(receiver, methodName, override) {
1197 const original = receiver[methodName];
1198 if (typeof original !== 'function') {
Mathias Bynens23ee1aa2020-03-02 12:06:381199 this.fail(`TestSuite._overrideMethod: ${methodName} is not a function`);
Blink Reformat4c46d092018-04-07 15:32:371200 return;
1201 }
1202 receiver[methodName] = function() {
1203 let value;
1204 try {
1205 value = original.apply(receiver, arguments);
1206 } finally {
1207 receiver[methodName] = original;
1208 }
1209 override.apply(original, arguments);
1210 return value;
1211 };
1212 };
1213
1214 TestSuite.prototype.startTimeline = function(callback) {
1215 const test = this;
1216 this.showPanel('timeline').then(function() {
1217 const timeline = UI.panels.timeline;
1218 test._overrideMethod(timeline, '_recordingStarted', callback);
1219 timeline._toggleRecording();
1220 });
1221 };
1222
1223 TestSuite.prototype.stopTimeline = function(callback) {
1224 const timeline = UI.panels.timeline;
1225 this._overrideMethod(timeline, 'loadingComplete', callback);
1226 timeline._toggleRecording();
1227 };
1228
1229 TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) {
1230 const callback = arguments[arguments.length - 1];
1231 const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`;
1232 const argsString = arguments.length < 3 ?
1233 '' :
1234 Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ',';
1235 this.evaluateInConsole_(
1236 `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {});
Paul Lewise504fd62020-01-23 16:52:331237 self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371238
1239 function onConsoleMessage(event) {
1240 const text = event.data.messageText;
1241 if (text === doneMessage) {
Paul Lewise504fd62020-01-23 16:52:331242 self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage);
Blink Reformat4c46d092018-04-07 15:32:371243 callback();
1244 }
1245 }
1246 };
1247
1248 TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) {
1249 const test = this;
1250
1251 this.startTimeline(onRecordingStarted);
1252
1253 function onRecordingStarted() {
1254 test.invokePageFunctionAsync(functionName, pageActionsDone);
1255 }
1256
1257 function pageActionsDone() {
1258 test.stopTimeline(callback);
1259 }
1260 };
1261
1262 TestSuite.prototype.enableExperiment = function(name) {
Tim van der Lippe99e59b82019-09-30 20:00:591263 Root.Runtime.experiments.enableForTest(name);
Blink Reformat4c46d092018-04-07 15:32:371264 };
1265
1266 TestSuite.prototype.checkInputEventsPresent = function() {
1267 const expectedEvents = new Set(arguments);
1268 const model = UI.panels.timeline._performanceModel.timelineModel();
1269 const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup;
1270 const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || [];
1271 const prefix = 'InputLatency::';
1272 for (const e of input) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341273 if (!e.name.startsWith(prefix)) {
Blink Reformat4c46d092018-04-07 15:32:371274 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341275 }
1276 if (e.steps.length < 2) {
Blink Reformat4c46d092018-04-07 15:32:371277 continue;
Tim van der Lippe1d6e57a2019-09-30 11:55:341278 }
Blink Reformat4c46d092018-04-07 15:32:371279 if (e.name.startsWith(prefix + 'Mouse') &&
Tim van der Lippe1d6e57a2019-09-30 11:55:341280 typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') {
Blink Reformat4c46d092018-04-07 15:32:371281 throw `Missing timeWaitingForMainThread on ${e.name}`;
Tim van der Lippe1d6e57a2019-09-30 11:55:341282 }
Blink Reformat4c46d092018-04-07 15:32:371283 expectedEvents.delete(e.name.substr(prefix.length));
1284 }
Tim van der Lippe1d6e57a2019-09-30 11:55:341285 if (expectedEvents.size) {
Blink Reformat4c46d092018-04-07 15:32:371286 throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(',');
Tim van der Lippe1d6e57a2019-09-30 11:55:341287 }
Blink Reformat4c46d092018-04-07 15:32:371288 };
1289
1290 TestSuite.prototype.testInspectedElementIs = async function(nodeName) {
1291 this.takeControl();
1292 await self.runtime.loadModulePromise('elements');
Tim van der Lippe1d6e57a2019-09-30 11:55:341293 if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) {
Blink Reformat4c46d092018-04-07 15:32:371294 await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f));
Tim van der Lippe1d6e57a2019-09-30 11:55:341295 }
Blink Reformat4c46d092018-04-07 15:32:371296 this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest);
1297 this.releaseControl();
1298 };
1299
Andrey Lushnikovd92662b2018-05-09 03:57:001300 TestSuite.prototype.testDisposeEmptyBrowserContext = async function(url) {
1301 this.takeControl();
Paul Lewis4ae5f4f2020-01-23 10:19:331302 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikovd92662b2018-05-09 03:57:001303 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1304 const response1 = await targetAgent.invoke_getBrowserContexts();
1305 this.assertEquals(response1.browserContextIds.length, 1);
1306 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1307 const response2 = await targetAgent.invoke_getBrowserContexts();
1308 this.assertEquals(response2.browserContextIds.length, 0);
1309 this.releaseControl();
1310 };
1311
Peter Marshalld2f58c32020-04-21 13:23:131312 TestSuite.prototype.testNewWindowFromBrowserContext = async function(url) {
1313 this.takeControl();
1314 // Create a BrowserContext.
1315 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
1316 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1317
1318 // Cause a Browser to be created with the temp profile.
1319 const {targetId} =
1320 await targetAgent.invoke_createTarget({url: 'data:text/html,', browserContextId, newWindow: true});
1321 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
1322
1323 // Destroy the temp profile.
1324 await targetAgent.invoke_disposeBrowserContext({browserContextId});
1325
1326 this.releaseControl();
1327 };
1328
Andrey Lushnikov0eea25e2018-04-24 22:29:511329 TestSuite.prototype.testCreateBrowserContext = async function(url) {
1330 this.takeControl();
1331 const browserContextIds = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331332 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov0eea25e2018-04-24 22:29:511333
1334 const target1 = await createIsolatedTarget(url);
1335 const target2 = await createIsolatedTarget(url);
1336
Andrey Lushnikov07477b42018-05-08 22:00:521337 const response = await targetAgent.invoke_getBrowserContexts();
1338 this.assertEquals(response.browserContextIds.length, 2);
1339 this.assertTrue(response.browserContextIds.includes(browserContextIds[0]));
1340 this.assertTrue(response.browserContextIds.includes(browserContextIds[1]));
1341
Andrey Lushnikov0eea25e2018-04-24 22:29:511342 await evalCode(target1, 'localStorage.setItem("page1", "page1")');
1343 await evalCode(target2, 'localStorage.setItem("page2", "page2")');
1344
1345 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page1")'), 'page1');
1346 this.assertEquals(await evalCode(target1, 'localStorage.getItem("page2")'), null);
1347 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page1")'), null);
1348 this.assertEquals(await evalCode(target2, 'localStorage.getItem("page2")'), 'page2');
1349
Andrey Lushnikov69499702018-05-08 18:20:471350 const removedTargets = [];
Paul Lewis4ae5f4f2020-01-23 10:19:331351 self.SDK.targetManager.observeTargets(
1352 {targetAdded: () => {}, targetRemoved: target => removedTargets.push(target)});
Andrey Lushnikov69499702018-05-08 18:20:471353 await Promise.all([disposeBrowserContext(browserContextIds[0]), disposeBrowserContext(browserContextIds[1])]);
1354 this.assertEquals(removedTargets.length, 2);
1355 this.assertEquals(removedTargets.indexOf(target1) !== -1, true);
1356 this.assertEquals(removedTargets.indexOf(target2) !== -1, true);
Andrey Lushnikov0eea25e2018-04-24 22:29:511357
1358 this.releaseControl();
1359
1360 /**
1361 * @param {string} url
1362 * @return {!Promise<!SDK.Target>}
1363 */
1364 async function createIsolatedTarget(url) {
Andrey Lushnikov0eea25e2018-04-24 22:29:511365 const {browserContextId} = await targetAgent.invoke_createBrowserContext();
1366 browserContextIds.push(browserContextId);
1367
1368 const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
Dmitry Gozman99d7a6c2018-11-12 17:55:111369 await targetAgent.invoke_attachToTarget({targetId, flatten: true});
Andrey Lushnikov0eea25e2018-04-24 22:29:511370
Paul Lewis4ae5f4f2020-01-23 10:19:331371 const target = self.SDK.targetManager.targets().find(target => target.id() === targetId);
Andrey Lushnikov0eea25e2018-04-24 22:29:511372 const pageAgent = target.pageAgent();
1373 await pageAgent.invoke_enable();
1374 await pageAgent.invoke_navigate({url});
1375 return target;
1376 }
1377
Andrey Lushnikov0eea25e2018-04-24 22:29:511378 async function disposeBrowserContext(browserContextId) {
Paul Lewis4ae5f4f2020-01-23 10:19:331379 const targetAgent = self.SDK.targetManager.mainTarget().targetAgent();
Andrey Lushnikov69499702018-05-08 18:20:471380 await targetAgent.invoke_disposeBrowserContext({browserContextId});
Andrey Lushnikov0eea25e2018-04-24 22:29:511381 }
1382
1383 async function evalCode(target, code) {
1384 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1385 }
1386 };
1387
Blink Reformat4c46d092018-04-07 15:32:371388 TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() {
1389 this.takeControl();
1390
1391 await new Promise(callback => this._waitForTargets(2, callback));
1392
1393 async function takeLogs(target) {
1394 const code = `
1395 (function() {
1396 var result = window.logs.join(' ');
1397 window.logs = [];
1398 return result;
1399 })()
1400 `;
1401 return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value;
1402 }
1403
1404 let parentFrameOutput;
1405 let childFrameOutput;
1406
Paul Lewis4ae5f4f2020-01-23 10:19:331407 const inputAgent = self.SDK.targetManager.mainTarget().inputAgent();
1408 const runtimeAgent = self.SDK.targetManager.mainTarget().runtimeAgent();
Blink Reformat4c46d092018-04-07 15:32:371409 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10});
1410 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20});
1411 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20});
1412 await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140});
1413 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150});
1414 await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150});
1415 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:331416 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371417 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:331418 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371419
1420
1421 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
Mathias Bynens23ee1aa2020-03-02 12:06:381422 await runtimeAgent.invoke_evaluate({expression: "document.querySelector('iframe').focus()"});
Blink Reformat4c46d092018-04-07 15:32:371423 await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'});
1424 parentFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331425 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371426 childFrameOutput = 'Event type: keydown';
Paul Lewis4ae5f4f2020-01-23 10:19:331427 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371428
1429 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]});
1430 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1431 await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]});
1432 await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []});
1433 parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10';
Paul Lewis4ae5f4f2020-01-23 10:19:331434 this.assertEquals(parentFrameOutput, await takeLogs(self.SDK.targetManager.targets()[0]));
Blink Reformat4c46d092018-04-07 15:32:371435 childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40';
Paul Lewis4ae5f4f2020-01-23 10:19:331436 this.assertEquals(childFrameOutput, await takeLogs(self.SDK.targetManager.targets()[1]));
Blink Reformat4c46d092018-04-07 15:32:371437
1438 this.releaseControl();
1439 };
1440
Andrey Kosyakov4f7fb052019-03-19 15:53:431441 TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) {
Blink Reformat4c46d092018-04-07 15:32:371442 const test = this;
1443 const loggedHeaders = new Set(['cache-control', 'pragma']);
1444 function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) {
1445 return new Promise(fulfill => {
1446 Host.ResourceLoader.load(url, headers, callback);
1447
Sigurd Schneidera327cde2020-01-21 15:48:121448 function callback(success, headers, content, errorDescription) {
1449 test.assertEquals(expectedStatus, errorDescription.statusCode);
Blink Reformat4c46d092018-04-07 15:32:371450
1451 const headersArray = [];
1452 for (const name in headers) {
1453 const nameLower = name.toLowerCase();
Tim van der Lippe1d6e57a2019-09-30 11:55:341454 if (loggedHeaders.has(nameLower)) {
Blink Reformat4c46d092018-04-07 15:32:371455 headersArray.push(nameLower);
Tim van der Lippe1d6e57a2019-09-30 11:55:341456 }
Blink Reformat4c46d092018-04-07 15:32:371457 }
1458 headersArray.sort();
1459 test.assertEquals(expectedHeaders.join(', '), headersArray.join(', '));
1460 test.assertEquals(expectedContent, content);
1461 fulfill();
1462 }
1463 });
1464 }
1465
1466 this.takeControl();
1467 await testCase(baseURL + 'non-existent.html', undefined, 404, [], '');
1468 await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n');
1469 await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo');
1470 await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache');
1471
Paul Lewis4ae5f4f2020-01-23 10:19:331472 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Blink Reformat4c46d092018-04-07 15:32:371473 expression: `fetch("/set-cookie?devtools-test-cookie=Bar",
1474 {credentials: 'include'})`,
1475 awaitPromise: true
1476 });
1477 await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
1478
Paul Lewis4ae5f4f2020-01-23 10:19:331479 await self.SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
Andrey Kosyakov73081cc2019-01-08 03:50:591480 expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
1481 {credentials: 'include'})`,
1482 awaitPromise: true
1483 });
1484 await testCase(
1485 baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
Andrey Kosyakov4f7fb052019-03-19 15:53:431486 await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>');
1487 await testCase(fileURL, undefined, 200, [], '<html>\n<body>\nDummy page.\n</body>\n</html>\n');
Rob Paveza30df0482019-10-09 23:15:491488 await testCase(fileURL + 'thisfileshouldnotbefound', undefined, 404, [], '');
Andrey Kosyakov73081cc2019-01-08 03:50:591489
Blink Reformat4c46d092018-04-07 15:32:371490 this.releaseControl();
1491 };
1492
Joey Arhar723d5b52019-04-19 01:31:391493 TestSuite.prototype.testExtensionWebSocketUserAgentOverride = async function(websocketPort) {
1494 this.takeControl();
1495
1496 const testUserAgent = 'test user agent';
Paul Lewis5a922e72020-01-24 11:58:081497 self.SDK.multitargetNetworkManager.setUserAgentOverride(testUserAgent);
Joey Arhar723d5b52019-04-19 01:31:391498
1499 function onRequestUpdated(event) {
1500 const request = event.data;
Tim van der Lippe1d6e57a2019-09-30 11:55:341501 if (request.resourceType() !== Common.resourceTypes.WebSocket) {
Joey Arhar723d5b52019-04-19 01:31:391502 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341503 }
1504 if (!request.requestHeadersText()) {
Joey Arhar723d5b52019-04-19 01:31:391505 return;
Tim van der Lippe1d6e57a2019-09-30 11:55:341506 }
Joey Arhar723d5b52019-04-19 01:31:391507
1508 let actualUserAgent = 'no user-agent header';
1509 for (const {name, value} of request.requestHeaders()) {
Tim van der Lippe1d6e57a2019-09-30 11:55:341510 if (name.toLowerCase() === 'user-agent') {
Joey Arhar723d5b52019-04-19 01:31:391511 actualUserAgent = value;
Tim van der Lippe1d6e57a2019-09-30 11:55:341512 }
Joey Arhar723d5b52019-04-19 01:31:391513 }
1514 this.assertEquals(testUserAgent, actualUserAgent);
1515 this.releaseControl();
1516 }
Paul Lewis4ae5f4f2020-01-23 10:19:331517 self.SDK.targetManager.addModelListener(
Joey Arhar723d5b52019-04-19 01:31:391518 SDK.NetworkManager, SDK.NetworkManager.Events.RequestUpdated, onRequestUpdated.bind(this));
1519
1520 this.evaluateInConsole_(`new WebSocket('ws://127.0.0.1:${websocketPort}')`, () => {});
1521 };
1522
Blink Reformat4c46d092018-04-07 15:32:371523 /**
1524 * Serializes array of uiSourceCodes to string.
1525 * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes
1526 * @return {string}
1527 */
1528 TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) {
1529 const names = [];
Tim van der Lippe1d6e57a2019-09-30 11:55:341530 for (let i = 0; i < uiSourceCodes.length; i++) {
Blink Reformat4c46d092018-04-07 15:32:371531 names.push('"' + uiSourceCodes[i].url() + '"');
Tim van der Lippe1d6e57a2019-09-30 11:55:341532 }
Blink Reformat4c46d092018-04-07 15:32:371533 return names.join(',');
1534 };
1535
1536 /**
1537 * Returns all loaded non anonymous uiSourceCodes.
1538 * @return {!Array.<!Workspace.UISourceCode>}
1539 */
1540 TestSuite.prototype.nonAnonymousUISourceCodes_ = function() {
1541 /**
1542 * @param {!Workspace.UISourceCode} uiSourceCode
1543 */
1544 function filterOutService(uiSourceCode) {
1545 return !uiSourceCode.project().isServiceProject();
1546 }
1547
Paul Lewis10e83a92020-01-23 14:07:581548 const uiSourceCodes = self.Workspace.workspace.uiSourceCodes();
Blink Reformat4c46d092018-04-07 15:32:371549 return uiSourceCodes.filter(filterOutService);
1550 };
1551
1552 /*
1553 * Evaluates the code in the console as if user typed it manually and invokes
1554 * the callback when the result message is received and added to the console.
1555 * @param {string} code
1556 * @param {function(string)} callback
1557 */
1558 TestSuite.prototype.evaluateInConsole_ = function(code, callback) {
1559 function innerEvaluate() {
Paul Lewisd9907342020-01-24 13:49:471560 self.UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371561 const consoleView = Console.ConsoleView.instance();
1562 consoleView._prompt._appendCommand(code);
1563
1564 this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) {
1565 callback(viewMessage.toMessageElement().deepTextContent());
1566 }.bind(this));
1567 }
1568
1569 function showConsoleAndEvaluate() {
Paul Lewis04ccecc2020-01-22 17:15:141570 self.Common.console.showPromise().then(innerEvaluate.bind(this));
Blink Reformat4c46d092018-04-07 15:32:371571 }
1572
Paul Lewisd9907342020-01-24 13:49:471573 if (!self.UI.context.flavor(SDK.ExecutionContext)) {
1574 self.UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this);
Blink Reformat4c46d092018-04-07 15:32:371575 return;
1576 }
1577 showConsoleAndEvaluate.call(this);
1578 };
1579
1580 /**
1581 * Checks that all expected scripts are present in the scripts list
1582 * in the Scripts panel.
1583 * @param {!Array.<string>} expected Regular expressions describing
1584 * expected script names.
1585 * @return {boolean} Whether all the scripts are in "scripts-files" select
1586 * box
1587 */
1588 TestSuite.prototype._scriptsAreParsed = function(expected) {
1589 const uiSourceCodes = this.nonAnonymousUISourceCodes_();
1590 // Check that at least all the expected scripts are present.
1591 const missing = expected.slice(0);
1592 for (let i = 0; i < uiSourceCodes.length; ++i) {
1593 for (let j = 0; j < missing.length; ++j) {
1594 if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
1595 missing.splice(j, 1);
1596 break;
1597 }
1598 }
1599 }
1600 return missing.length === 0;
1601 };
1602
1603 /**
1604 * Waits for script pause, checks expectations, and invokes the callback.
1605 * @param {function():void} callback
1606 */
1607 TestSuite.prototype._waitForScriptPause = function(callback) {
1608 this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback);
1609 };
1610
1611 /**
1612 * Waits until all the scripts are parsed and invokes the callback.
1613 */
1614 TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) {
1615 const test = this;
1616
1617 function waitForAllScripts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341618 if (test._scriptsAreParsed(expectedScripts)) {
Blink Reformat4c46d092018-04-07 15:32:371619 callback();
Tim van der Lippe1d6e57a2019-09-30 11:55:341620 } else {
Blink Reformat4c46d092018-04-07 15:32:371621 test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts);
Tim van der Lippe1d6e57a2019-09-30 11:55:341622 }
Blink Reformat4c46d092018-04-07 15:32:371623 }
1624
1625 waitForAllScripts();
1626 };
1627
1628 TestSuite.prototype._waitForTargets = function(n, callback) {
1629 checkTargets.call(this);
1630
1631 function checkTargets() {
Paul Lewis4ae5f4f2020-01-23 10:19:331632 if (self.SDK.targetManager.targets().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371633 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341634 } else {
Blink Reformat4c46d092018-04-07 15:32:371635 this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341636 }
Blink Reformat4c46d092018-04-07 15:32:371637 }
1638 };
1639
1640 TestSuite.prototype._waitForExecutionContexts = function(n, callback) {
Paul Lewis4ae5f4f2020-01-23 10:19:331641 const runtimeModel = self.SDK.targetManager.mainTarget().model(SDK.RuntimeModel);
Blink Reformat4c46d092018-04-07 15:32:371642 checkForExecutionContexts.call(this);
1643
1644 function checkForExecutionContexts() {
Tim van der Lippe1d6e57a2019-09-30 11:55:341645 if (runtimeModel.executionContexts().length >= n) {
Blink Reformat4c46d092018-04-07 15:32:371646 callback.call(null);
Tim van der Lippe1d6e57a2019-09-30 11:55:341647 } else {
Blink Reformat4c46d092018-04-07 15:32:371648 this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this));
Tim van der Lippe1d6e57a2019-09-30 11:55:341649 }
Blink Reformat4c46d092018-04-07 15:32:371650 }
1651 };
1652
1653
1654 window.uiTests = new TestSuite(window.domAutomationController);
1655})(window);