Blink Reformat | 4c46d09 | 2018-04-07 15:32:37 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2010 Google Inc. All rights reserved. |
| 3 | * |
| 4 | * Redistribution and use in source and binary forms, with or without |
| 5 | * modification, are permitted provided that the following conditions are |
| 6 | * met: |
| 7 | * |
| 8 | * * Redistributions of source code must retain the above copyright |
| 9 | * notice, this list of conditions and the following disclaimer. |
| 10 | * * Redistributions in binary form must reproduce the above |
| 11 | * copyright notice, this list of conditions and the following disclaimer |
| 12 | * in the documentation and/or other materials provided with the |
| 13 | * distribution. |
| 14 | * * Neither the name of Google Inc. nor the names of its |
| 15 | * contributors may be used to endorse or promote products derived from |
| 16 | * this software without specific prior written permission. |
| 17 | * |
| 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | */ |
| 30 | /* eslint-disable indent */ |
| 31 | |
| 32 | /** |
| 33 | * @fileoverview This file contains small testing framework along with the |
| 34 | * test suite for the frontend. These tests are a part of the continues build |
| 35 | * and are executed by the devtools_sanity_unittest.cc as a part of the |
| 36 | * Interactive UI Test suite. |
| 37 | * FIXME: change field naming style to use trailing underscore. |
| 38 | */ |
| 39 | |
| 40 | (function createTestSuite(window) { |
| 41 | |
| 42 | /** |
| 43 | * @unrestricted |
| 44 | */ |
| 45 | const TestSuite = class { |
| 46 | /** |
| 47 | * Test suite for interactive UI tests. |
| 48 | * @param {Object} domAutomationController DomAutomationController instance. |
| 49 | */ |
| 50 | constructor(domAutomationController) { |
| 51 | this.domAutomationController_ = domAutomationController; |
| 52 | this.controlTaken_ = false; |
| 53 | this.timerId_ = -1; |
| 54 | this._asyncInvocationId = 0; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Key event with given key identifier. |
| 59 | */ |
| 60 | static createKeyEvent(key) { |
| 61 | return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key}); |
| 62 | } |
| 63 | }; |
| 64 | |
| 65 | /** |
| 66 | * Reports test failure. |
| 67 | * @param {string} message Failure description. |
| 68 | */ |
| 69 | TestSuite.prototype.fail = function(message) { |
| 70 | if (this.controlTaken_) |
| 71 | this.reportFailure_(message); |
| 72 | else |
| 73 | throw message; |
| 74 | }; |
| 75 | |
| 76 | /** |
| 77 | * Equals assertion tests that expected === actual. |
| 78 | * @param {!Object|boolean} expected Expected object. |
| 79 | * @param {!Object|boolean} actual Actual object. |
| 80 | * @param {string} opt_message User message to print if the test fails. |
| 81 | */ |
| 82 | TestSuite.prototype.assertEquals = function(expected, actual, opt_message) { |
| 83 | if (expected !== actual) { |
| 84 | let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\''; |
| 85 | if (opt_message) |
| 86 | message = opt_message + '(' + message + ')'; |
| 87 | this.fail(message); |
| 88 | } |
| 89 | }; |
| 90 | |
| 91 | /** |
| 92 | * True assertion tests that value == true. |
| 93 | * @param {!Object} value Actual object. |
| 94 | * @param {string} opt_message User message to print if the test fails. |
| 95 | */ |
| 96 | TestSuite.prototype.assertTrue = function(value, opt_message) { |
| 97 | this.assertEquals(true, !!value, opt_message); |
| 98 | }; |
| 99 | |
| 100 | /** |
| 101 | * Takes control over execution. |
| 102 | */ |
| 103 | TestSuite.prototype.takeControl = function() { |
| 104 | this.controlTaken_ = true; |
| 105 | // Set up guard timer. |
| 106 | const self = this; |
| 107 | this.timerId_ = setTimeout(function() { |
| 108 | self.reportFailure_('Timeout exceeded: 20 sec'); |
| 109 | }, 20000); |
| 110 | }; |
| 111 | |
| 112 | /** |
| 113 | * Releases control over execution. |
| 114 | */ |
| 115 | TestSuite.prototype.releaseControl = function() { |
| 116 | if (this.timerId_ !== -1) { |
| 117 | clearTimeout(this.timerId_); |
| 118 | this.timerId_ = -1; |
| 119 | } |
| 120 | this.controlTaken_ = false; |
| 121 | this.reportOk_(); |
| 122 | }; |
| 123 | |
| 124 | /** |
| 125 | * Async tests use this one to report that they are completed. |
| 126 | */ |
| 127 | TestSuite.prototype.reportOk_ = function() { |
| 128 | this.domAutomationController_.send('[OK]'); |
| 129 | }; |
| 130 | |
| 131 | /** |
| 132 | * Async tests use this one to report failures. |
| 133 | */ |
| 134 | TestSuite.prototype.reportFailure_ = function(error) { |
| 135 | if (this.timerId_ !== -1) { |
| 136 | clearTimeout(this.timerId_); |
| 137 | this.timerId_ = -1; |
| 138 | } |
| 139 | this.domAutomationController_.send('[FAILED] ' + error); |
| 140 | }; |
| 141 | |
| 142 | /** |
| 143 | * Run specified test on a fresh instance of the test suite. |
| 144 | * @param {Array<string>} args method name followed by its parameters. |
| 145 | */ |
| 146 | TestSuite.prototype.dispatchOnTestSuite = function(args) { |
| 147 | const methodName = args.shift(); |
| 148 | try { |
| 149 | this[methodName].apply(this, args); |
| 150 | if (!this.controlTaken_) |
| 151 | this.reportOk_(); |
| 152 | } 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]; |
| 180 | if (typeof orig !== 'function') |
| 181 | this.fail('Cannot find method to override: ' + methodName); |
| 182 | const test = this; |
| 183 | receiver[methodName] = function(var_args) { |
| 184 | let result; |
| 185 | try { |
| 186 | result = orig.apply(this, arguments); |
| 187 | } finally { |
| 188 | if (!opt_sticky) |
| 189 | receiver[methodName] = orig; |
| 190 | } |
| 191 | // In case of exception the override won't be called. |
| 192 | try { |
| 193 | override.apply(this, arguments); |
| 194 | } catch (e) { |
| 195 | test.fail('Exception in overriden method \'' + methodName + '\': ' + e); |
| 196 | } |
| 197 | return result; |
| 198 | }; |
| 199 | }; |
| 200 | |
| 201 | /** |
| 202 | * Waits for current throttler invocations, if any. |
| 203 | * @param {!Common.Throttler} throttler |
| 204 | * @param {function()} callback |
| 205 | */ |
| 206 | TestSuite.prototype.waitForThrottler = function(throttler, callback) { |
| 207 | const test = this; |
| 208 | let scheduleShouldFail = true; |
| 209 | test.addSniffer(throttler, 'schedule', onSchedule); |
| 210 | |
| 211 | function hasSomethingScheduled() { |
| 212 | return throttler._isRunningProcess || throttler._process; |
| 213 | } |
| 214 | |
| 215 | function checkState() { |
| 216 | if (!hasSomethingScheduled()) { |
| 217 | scheduleShouldFail = false; |
| 218 | callback(); |
| 219 | return; |
| 220 | } |
| 221 | |
| 222 | test.addSniffer(throttler, '_processCompletedForTests', checkState); |
| 223 | } |
| 224 | |
| 225 | function onSchedule() { |
| 226 | if (scheduleShouldFail) |
| 227 | test.fail('Unexpected Throttler.schedule'); |
| 228 | } |
| 229 | |
| 230 | checkState(); |
| 231 | }; |
| 232 | |
| 233 | /** |
| 234 | * @param {string} panelName Name of the panel to show. |
| 235 | */ |
| 236 | TestSuite.prototype.showPanel = function(panelName) { |
| 237 | return UI.inspectorView.showPanel(panelName); |
| 238 | }; |
| 239 | |
| 240 | // UI Tests |
| 241 | |
| 242 | /** |
| 243 | * Tests that scripts tab can be open and populated with inspected scripts. |
| 244 | */ |
| 245 | TestSuite.prototype.testShowScriptsTab = function() { |
| 246 | const test = this; |
| 247 | this.showPanel('sources').then(function() { |
| 248 | // There should be at least main page script. |
| 249 | this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() { |
| 250 | test.releaseControl(); |
| 251 | }); |
| 252 | }.bind(this)); |
| 253 | // Wait until all scripts are added to the debugger. |
| 254 | this.takeControl(); |
| 255 | }; |
| 256 | |
| 257 | /** |
| 258 | * Tests that scripts tab is populated with inspected scripts even if it |
| 259 | * hadn't been shown by the moment inspected paged refreshed. |
| 260 | * @see http://crbug.com/26312 |
| 261 | */ |
| 262 | TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() { |
| 263 | const test = this; |
| 264 | const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); |
| 265 | debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); |
| 266 | |
| 267 | this.showPanel('elements').then(function() { |
| 268 | // Reload inspected page. It will reset the debugger agent. |
| 269 | test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); |
| 270 | }); |
| 271 | |
| 272 | function waitUntilScriptIsParsed() { |
| 273 | debuggerModel.removeEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); |
| 274 | test.showPanel('sources').then(function() { |
| 275 | test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() { |
| 276 | test.releaseControl(); |
| 277 | }); |
| 278 | }); |
| 279 | } |
| 280 | |
| 281 | // Wait until all scripts are added to the debugger. |
| 282 | this.takeControl(); |
| 283 | }; |
| 284 | |
| 285 | /** |
| 286 | * Tests that scripts list contains content scripts. |
| 287 | */ |
| 288 | TestSuite.prototype.testContentScriptIsPresent = function() { |
| 289 | const test = this; |
| 290 | this.showPanel('sources').then(function() { |
| 291 | test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() { |
| 292 | test.releaseControl(); |
| 293 | }); |
| 294 | }); |
| 295 | |
| 296 | // Wait until all scripts are added to the debugger. |
| 297 | this.takeControl(); |
| 298 | }; |
| 299 | |
| 300 | /** |
| 301 | * Tests that scripts are not duplicaed on Scripts tab switch. |
| 302 | */ |
| 303 | TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() { |
| 304 | const test = this; |
| 305 | |
| 306 | function switchToElementsTab() { |
| 307 | test.showPanel('elements').then(function() { |
| 308 | setTimeout(switchToScriptsTab, 0); |
| 309 | }); |
| 310 | } |
| 311 | |
| 312 | function switchToScriptsTab() { |
| 313 | test.showPanel('sources').then(function() { |
| 314 | setTimeout(checkScriptsPanel, 0); |
| 315 | }); |
| 316 | } |
| 317 | |
| 318 | function checkScriptsPanel() { |
| 319 | test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.'); |
| 320 | checkNoDuplicates(); |
| 321 | test.releaseControl(); |
| 322 | } |
| 323 | |
| 324 | function checkNoDuplicates() { |
| 325 | const uiSourceCodes = test.nonAnonymousUISourceCodes_(); |
| 326 | for (let i = 0; i < uiSourceCodes.length; i++) { |
| 327 | for (let j = i + 1; j < uiSourceCodes.length; j++) { |
| 328 | test.assertTrue( |
| 329 | uiSourceCodes[i].url() !== uiSourceCodes[j].url(), |
| 330 | 'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes)); |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | this.showPanel('sources').then(function() { |
| 336 | test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() { |
| 337 | checkNoDuplicates(); |
| 338 | setTimeout(switchToElementsTab, 0); |
| 339 | }); |
| 340 | }); |
| 341 | |
| 342 | // Wait until all scripts are added to the debugger. |
| 343 | this.takeControl(); |
| 344 | }; |
| 345 | |
| 346 | // Tests that debugger works correctly if pause event occurs when DevTools |
| 347 | // frontend is being loaded. |
| 348 | TestSuite.prototype.testPauseWhenLoadingDevTools = function() { |
| 349 | const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); |
| 350 | if (debuggerModel.debuggerPausedDetails) |
| 351 | return; |
| 352 | |
| 353 | this.showPanel('sources').then(function() { |
| 354 | // Script execution can already be paused. |
| 355 | |
| 356 | this._waitForScriptPause(this.releaseControl.bind(this)); |
| 357 | }.bind(this)); |
| 358 | |
| 359 | this.takeControl(); |
| 360 | }; |
| 361 | |
| 362 | // Tests that pressing "Pause" will pause script execution if the script |
| 363 | // is already running. |
| 364 | TestSuite.prototype.testPauseWhenScriptIsRunning = function() { |
| 365 | this.showPanel('sources').then(function() { |
| 366 | this.evaluateInConsole_('setTimeout("handleClick()", 0)', didEvaluateInConsole.bind(this)); |
| 367 | }.bind(this)); |
| 368 | |
| 369 | function didEvaluateInConsole(resultText) { |
| 370 | this.assertTrue(!isNaN(resultText), 'Failed to get timer id: ' + resultText); |
| 371 | // Wait for some time to make sure that inspected page is running the |
| 372 | // infinite loop. |
| 373 | setTimeout(testScriptPause.bind(this), 300); |
| 374 | } |
| 375 | |
| 376 | function testScriptPause() { |
| 377 | // The script should be in infinite loop. Click "Pause" button to |
| 378 | // pause it and wait for the result. |
| 379 | UI.panels.sources._togglePause(); |
| 380 | |
| 381 | this._waitForScriptPause(this.releaseControl.bind(this)); |
| 382 | } |
| 383 | |
| 384 | this.takeControl(); |
| 385 | }; |
| 386 | |
| 387 | /** |
| 388 | * Tests network size. |
| 389 | */ |
| 390 | TestSuite.prototype.testNetworkSize = function() { |
| 391 | const test = this; |
| 392 | |
| 393 | function finishRequest(request, finishTime) { |
| 394 | test.assertEquals(25, request.resourceSize, 'Incorrect total data length'); |
| 395 | test.releaseControl(); |
| 396 | } |
| 397 | |
| 398 | this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); |
| 399 | |
| 400 | // Reload inspected page to sniff network events |
| 401 | test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); |
| 402 | |
| 403 | this.takeControl(); |
| 404 | }; |
| 405 | |
| 406 | /** |
| 407 | * Tests network sync size. |
| 408 | */ |
| 409 | TestSuite.prototype.testNetworkSyncSize = function() { |
| 410 | const test = this; |
| 411 | |
| 412 | function finishRequest(request, finishTime) { |
| 413 | test.assertEquals(25, request.resourceSize, 'Incorrect total data length'); |
| 414 | test.releaseControl(); |
| 415 | } |
| 416 | |
| 417 | this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); |
| 418 | |
| 419 | // Send synchronous XHR to sniff network events |
| 420 | test.evaluateInConsole_( |
| 421 | 'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {}); |
| 422 | |
| 423 | this.takeControl(); |
| 424 | }; |
| 425 | |
| 426 | /** |
| 427 | * Tests network raw headers text. |
| 428 | */ |
| 429 | TestSuite.prototype.testNetworkRawHeadersText = function() { |
| 430 | const test = this; |
| 431 | |
| 432 | function finishRequest(request, finishTime) { |
| 433 | if (!request.responseHeadersText) |
| 434 | test.fail('Failure: resource does not have response headers text'); |
| 435 | const index = request.responseHeadersText.indexOf('Date:'); |
| 436 | test.assertEquals( |
| 437 | 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length'); |
| 438 | test.releaseControl(); |
| 439 | } |
| 440 | |
| 441 | this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); |
| 442 | |
| 443 | // Reload inspected page to sniff network events |
| 444 | test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); |
| 445 | |
| 446 | this.takeControl(); |
| 447 | }; |
| 448 | |
| 449 | /** |
| 450 | * Tests network timing. |
| 451 | */ |
| 452 | TestSuite.prototype.testNetworkTiming = function() { |
| 453 | const test = this; |
| 454 | |
| 455 | function finishRequest(request, finishTime) { |
| 456 | // Setting relaxed expectations to reduce flakiness. |
| 457 | // Server sends headers after 100ms, then sends data during another 100ms. |
| 458 | // We expect these times to be measured at least as 70ms. |
| 459 | test.assertTrue( |
| 460 | request.timing.receiveHeadersEnd - request.timing.connectStart >= 70, |
| 461 | 'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' + |
| 462 | 'receiveHeadersEnd=' + request.timing.receiveHeadersEnd + ', connectStart=' + |
| 463 | request.timing.connectStart + '.'); |
| 464 | test.assertTrue( |
| 465 | request.responseReceivedTime - request.startTime >= 0.07, |
| 466 | 'Time between responseReceivedTime and startTime should be >=0.07s, but was ' + |
| 467 | 'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.'); |
| 468 | test.assertTrue( |
| 469 | request.endTime - request.startTime >= 0.14, |
| 470 | 'Time between endTime and startTime should be >=0.14s, but was ' + |
| 471 | 'endtime=' + request.endTime + ', startTime=' + request.startTime + '.'); |
| 472 | |
| 473 | test.releaseControl(); |
| 474 | } |
| 475 | |
| 476 | this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); |
| 477 | |
| 478 | // Reload inspected page to sniff network events |
| 479 | test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); |
| 480 | |
| 481 | this.takeControl(); |
| 482 | }; |
| 483 | |
| 484 | TestSuite.prototype.testPushTimes = function(url) { |
| 485 | const test = this; |
| 486 | let pendingRequestCount = 2; |
| 487 | |
| 488 | function finishRequest(request, finishTime) { |
| 489 | test.assertTrue( |
| 490 | typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0, |
| 491 | `pushStart is invalid: ${request.timing.pushStart}`); |
| 492 | test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`); |
| 493 | test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime'); |
| 494 | if (request.url().endsWith('?pushUseNullEndTime')) { |
| 495 | test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`); |
| 496 | } else { |
| 497 | test.assertTrue( |
| 498 | request.timing.pushStart < request.timing.pushEnd, |
| 499 | `pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`); |
| 500 | // The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant. |
| 501 | test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime'); |
| 502 | test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime'); |
| 503 | } |
| 504 | if (!--pendingRequestCount) |
| 505 | test.releaseControl(); |
| 506 | } |
| 507 | |
| 508 | this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest, true); |
| 509 | |
| 510 | test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {}); |
| 511 | test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {}); |
| 512 | this.takeControl(); |
| 513 | }; |
| 514 | |
| 515 | TestSuite.prototype.testConsoleOnNavigateBack = function() { |
| 516 | |
| 517 | function filteredMessages() { |
| 518 | return SDK.consoleModel.messages().filter(a => a.source !== SDK.ConsoleMessage.MessageSource.Violation); |
| 519 | } |
| 520 | |
| 521 | if (filteredMessages().length === 1) |
| 522 | firstConsoleMessageReceived.call(this, null); |
| 523 | else |
| 524 | SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); |
| 525 | |
| 526 | |
| 527 | function firstConsoleMessageReceived(event) { |
| 528 | if (event && event.data.source === SDK.ConsoleMessage.MessageSource.Violation) |
| 529 | return; |
| 530 | SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); |
| 531 | this.evaluateInConsole_('clickLink();', didClickLink.bind(this)); |
| 532 | } |
| 533 | |
| 534 | function didClickLink() { |
| 535 | // Check that there are no new messages(command is not a message). |
| 536 | this.assertEquals(3, filteredMessages().length); |
| 537 | this.evaluateInConsole_('history.back();', didNavigateBack.bind(this)); |
| 538 | } |
| 539 | |
| 540 | function didNavigateBack() { |
| 541 | // Make sure navigation completed and possible console messages were pushed. |
| 542 | this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this)); |
| 543 | } |
| 544 | |
| 545 | function didCompleteNavigation() { |
| 546 | this.assertEquals(7, filteredMessages().length); |
| 547 | this.releaseControl(); |
| 548 | } |
| 549 | |
| 550 | this.takeControl(); |
| 551 | }; |
| 552 | |
| 553 | TestSuite.prototype.testSharedWorker = function() { |
| 554 | function didEvaluateInConsole(resultText) { |
| 555 | this.assertEquals('2011', resultText); |
| 556 | this.releaseControl(); |
| 557 | } |
| 558 | this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this)); |
| 559 | this.takeControl(); |
| 560 | }; |
| 561 | |
| 562 | TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() { |
| 563 | // Make sure the worker is loaded. |
| 564 | this.takeControl(); |
| 565 | this._waitForTargets(2, callback.bind(this)); |
| 566 | |
| 567 | function callback() { |
| 568 | Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this)); |
| 569 | } |
| 570 | }; |
| 571 | |
| 572 | TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() { |
| 573 | this.takeControl(); |
| 574 | this._waitForTargets(2, callback.bind(this)); |
| 575 | |
| 576 | function callback() { |
| 577 | const debuggerModel = SDK.targetManager.models(SDK.DebuggerModel)[0]; |
| 578 | if (debuggerModel.isPaused()) { |
| 579 | this.releaseControl(); |
| 580 | return; |
| 581 | } |
| 582 | this._waitForScriptPause(this.releaseControl.bind(this)); |
| 583 | } |
| 584 | }; |
| 585 | |
| 586 | TestSuite.prototype.enableTouchEmulation = function() { |
| 587 | const deviceModeModel = new Emulation.DeviceModeModel(function() {}); |
| 588 | deviceModeModel._target = SDK.targetManager.mainTarget(); |
| 589 | deviceModeModel._applyTouch(true, true); |
| 590 | }; |
| 591 | |
| 592 | TestSuite.prototype.waitForDebuggerPaused = function() { |
| 593 | const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); |
| 594 | if (debuggerModel.debuggerPausedDetails) |
| 595 | return; |
| 596 | |
| 597 | this.takeControl(); |
| 598 | this._waitForScriptPause(this.releaseControl.bind(this)); |
| 599 | }; |
| 600 | |
| 601 | TestSuite.prototype.switchToPanel = function(panelName) { |
| 602 | this.showPanel(panelName).then(this.releaseControl.bind(this)); |
| 603 | this.takeControl(); |
| 604 | }; |
| 605 | |
| 606 | // Regression test for crbug.com/370035. |
| 607 | TestSuite.prototype.testDeviceMetricsOverrides = function() { |
| 608 | function dumpPageMetrics() { |
| 609 | return JSON.stringify( |
| 610 | {width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio}); |
| 611 | } |
| 612 | |
| 613 | const test = this; |
| 614 | |
| 615 | async function testOverrides(params, metrics, callback) { |
| 616 | await SDK.targetManager.mainTarget().emulationAgent().invoke_setDeviceMetricsOverride(params); |
| 617 | test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics); |
| 618 | |
| 619 | function checkMetrics(consoleResult) { |
| 620 | test.assertEquals( |
| 621 | '"' + JSON.stringify(metrics) + '"', consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params)); |
| 622 | callback(); |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | function step1() { |
| 627 | testOverrides( |
| 628 | {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true}, |
| 629 | {width: 1200, height: 1000, deviceScaleFactor: 1}, step2); |
| 630 | } |
| 631 | |
| 632 | function step2() { |
| 633 | testOverrides( |
| 634 | {width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false}, |
| 635 | {width: 1200, height: 1000, deviceScaleFactor: 1}, step3); |
| 636 | } |
| 637 | |
| 638 | function step3() { |
| 639 | testOverrides( |
| 640 | {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true}, |
| 641 | {width: 1200, height: 1000, deviceScaleFactor: 3}, step4); |
| 642 | } |
| 643 | |
| 644 | function step4() { |
| 645 | testOverrides( |
| 646 | {width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false}, |
| 647 | {width: 1200, height: 1000, deviceScaleFactor: 3}, finish); |
| 648 | } |
| 649 | |
| 650 | function finish() { |
| 651 | test.releaseControl(); |
| 652 | } |
| 653 | |
| 654 | test.takeControl(); |
| 655 | step1(); |
| 656 | }; |
| 657 | |
| 658 | TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() { |
| 659 | const test = this; |
| 660 | let receivedReady = false; |
| 661 | |
| 662 | function signalToShowAutofill() { |
| 663 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 664 | {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); |
| 665 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 666 | {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); |
| 667 | } |
| 668 | |
| 669 | function selectTopAutoFill() { |
| 670 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 671 | {type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); |
| 672 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 673 | {type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40}); |
| 674 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 675 | {type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13}); |
| 676 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 677 | {type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13}); |
| 678 | |
| 679 | test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput); |
| 680 | } |
| 681 | |
| 682 | function onResultOfInput(value) { |
| 683 | // Console adds "" around the response. |
| 684 | test.assertEquals('"Abbf"', value); |
| 685 | test.releaseControl(); |
| 686 | } |
| 687 | |
| 688 | function onConsoleMessage(event) { |
| 689 | const message = event.data.messageText; |
| 690 | if (message === 'ready' && !receivedReady) { |
| 691 | receivedReady = true; |
| 692 | signalToShowAutofill(); |
| 693 | } |
| 694 | // This log comes from the browser unittest code. |
| 695 | if (message === 'didShowSuggestions') |
| 696 | selectTopAutoFill(); |
| 697 | } |
| 698 | |
| 699 | this.takeControl(); |
| 700 | |
| 701 | // It is possible for the ready console messagage to be already received but not handled |
| 702 | // or received later. This ensures we can catch both cases. |
| 703 | SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); |
| 704 | |
| 705 | const messages = SDK.consoleModel.messages(); |
| 706 | if (messages.length) { |
| 707 | const text = messages[0].messageText; |
| 708 | this.assertEquals('ready', text); |
| 709 | signalToShowAutofill(); |
| 710 | } |
| 711 | }; |
| 712 | |
| 713 | TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() { |
| 714 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 715 | {type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'}); |
| 716 | SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent( |
| 717 | {type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'}); |
| 718 | }; |
| 719 | |
| 720 | // Simple sanity check to make sure network throttling is wired up |
| 721 | // See crbug.com/747724 |
| 722 | TestSuite.prototype.testOfflineNetworkConditions = async function() { |
| 723 | const test = this; |
| 724 | SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions); |
| 725 | |
| 726 | function finishRequest(request) { |
| 727 | test.assertEquals( |
| 728 | 'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed'); |
| 729 | test.releaseControl(); |
| 730 | } |
| 731 | |
| 732 | this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest); |
| 733 | |
| 734 | test.takeControl(); |
| 735 | test.evaluateInConsole_('window.location.reload(true);', function(resultText) {}); |
| 736 | }; |
| 737 | |
| 738 | TestSuite.prototype.testEmulateNetworkConditions = function() { |
| 739 | const test = this; |
| 740 | |
| 741 | function testPreset(preset, messages, next) { |
| 742 | function onConsoleMessage(event) { |
| 743 | const index = messages.indexOf(event.data.messageText); |
| 744 | if (index === -1) { |
| 745 | test.fail('Unexpected message: ' + event.data.messageText); |
| 746 | return; |
| 747 | } |
| 748 | |
| 749 | messages.splice(index, 1); |
| 750 | if (!messages.length) { |
| 751 | SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); |
| 752 | next(); |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); |
| 757 | SDK.multitargetNetworkManager.setNetworkConditions(preset); |
| 758 | } |
| 759 | |
| 760 | test.takeControl(); |
| 761 | step1(); |
| 762 | |
| 763 | function step1() { |
| 764 | testPreset( |
| 765 | MobileThrottling.networkPresets[2], |
| 766 | [ |
| 767 | 'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g' |
| 768 | ], |
| 769 | step2); |
| 770 | } |
| 771 | |
| 772 | function step2() { |
| 773 | testPreset( |
| 774 | MobileThrottling.networkPresets[1], |
| 775 | [ |
| 776 | 'online event: online = true', |
| 777 | 'connection change event: type = cellular; downlinkMax = 0.390625; effectiveType = 2g' |
| 778 | ], |
| 779 | step3); |
| 780 | } |
| 781 | |
| 782 | function step3() { |
| 783 | testPreset( |
| 784 | MobileThrottling.networkPresets[0], |
| 785 | ['connection change event: type = cellular; downlinkMax = 1.4400000000000002; effectiveType = 3g'], |
| 786 | test.releaseControl.bind(test)); |
| 787 | } |
| 788 | }; |
| 789 | |
| 790 | TestSuite.prototype.testScreenshotRecording = function() { |
| 791 | const test = this; |
| 792 | |
| 793 | function performActionsInPage(callback) { |
| 794 | let count = 0; |
| 795 | const div = document.createElement('div'); |
| 796 | div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;'); |
| 797 | document.body.appendChild(div); |
| 798 | requestAnimationFrame(frame); |
| 799 | function frame() { |
| 800 | const color = [0, 0, 0]; |
| 801 | color[count % 3] = 255; |
| 802 | div.style.backgroundColor = 'rgb(' + color.join(',') + ')'; |
| 803 | if (++count > 10) |
| 804 | requestAnimationFrame(callback); |
| 805 | else |
| 806 | requestAnimationFrame(frame); |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | const captureFilmStripSetting = Common.settings.createSetting('timelineCaptureFilmStrip', false); |
| 811 | captureFilmStripSetting.set(true); |
| 812 | test.evaluateInConsole_(performActionsInPage.toString(), function() {}); |
| 813 | test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone); |
| 814 | |
| 815 | function onTimelineDone() { |
| 816 | captureFilmStripSetting.set(false); |
| 817 | const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel(); |
| 818 | const frames = filmStripModel.frames(); |
| 819 | test.assertTrue(frames.length > 4 && typeof frames.length === 'number'); |
| 820 | loadFrameImages(frames); |
| 821 | } |
| 822 | |
| 823 | function loadFrameImages(frames) { |
| 824 | const readyImages = []; |
| 825 | for (const frame of frames) |
| 826 | frame.imageDataPromise().then(onGotImageData); |
| 827 | |
| 828 | function onGotImageData(data) { |
| 829 | const image = new Image(); |
| 830 | test.assertTrue(!!data, 'No image data for frame'); |
| 831 | image.addEventListener('load', onLoad); |
| 832 | image.src = 'data:image/jpg;base64,' + data; |
| 833 | } |
| 834 | |
| 835 | function onLoad(event) { |
| 836 | readyImages.push(event.target); |
| 837 | if (readyImages.length === frames.length) |
| 838 | validateImagesAndCompleteTest(readyImages); |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | function validateImagesAndCompleteTest(images) { |
| 843 | let redCount = 0; |
| 844 | let greenCount = 0; |
| 845 | let blueCount = 0; |
| 846 | |
| 847 | const canvas = document.createElement('canvas'); |
| 848 | const ctx = canvas.getContext('2d'); |
| 849 | for (const image of images) { |
| 850 | test.assertTrue(image.naturalWidth > 10); |
| 851 | test.assertTrue(image.naturalHeight > 10); |
| 852 | canvas.width = image.naturalWidth; |
| 853 | canvas.height = image.naturalHeight; |
| 854 | ctx.drawImage(image, 0, 0); |
| 855 | const data = ctx.getImageData(0, 0, 1, 1); |
| 856 | const color = Array.prototype.join.call(data.data, ','); |
| 857 | if (data.data[0] > 200) |
| 858 | redCount++; |
| 859 | else if (data.data[1] > 200) |
| 860 | greenCount++; |
| 861 | else if (data.data[2] > 200) |
| 862 | blueCount++; |
| 863 | else |
| 864 | test.fail('Unexpected color: ' + color); |
| 865 | } |
| 866 | test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed'); |
| 867 | test.releaseControl(); |
| 868 | } |
| 869 | |
| 870 | test.takeControl(); |
| 871 | }; |
| 872 | |
| 873 | TestSuite.prototype.testSettings = function() { |
| 874 | const test = this; |
| 875 | |
| 876 | createSettings(); |
| 877 | test.takeControl(); |
| 878 | setTimeout(reset, 0); |
| 879 | |
| 880 | function createSettings() { |
| 881 | const localSetting = Common.settings.createLocalSetting('local', undefined); |
| 882 | localSetting.set({s: 'local', n: 1}); |
| 883 | const globalSetting = Common.settings.createSetting('global', undefined); |
| 884 | globalSetting.set({s: 'global', n: 2}); |
| 885 | } |
| 886 | |
| 887 | function reset() { |
| 888 | Runtime.experiments.clearForTest(); |
| 889 | InspectorFrontendHost.getPreferences(gotPreferences); |
| 890 | } |
| 891 | |
| 892 | function gotPreferences(prefs) { |
| 893 | Main.Main._instanceForTest._createSettings(prefs); |
| 894 | |
| 895 | const localSetting = Common.settings.createLocalSetting('local', undefined); |
| 896 | test.assertEquals('object', typeof localSetting.get()); |
| 897 | test.assertEquals('local', localSetting.get().s); |
| 898 | test.assertEquals(1, localSetting.get().n); |
| 899 | const globalSetting = Common.settings.createSetting('global', undefined); |
| 900 | test.assertEquals('object', typeof globalSetting.get()); |
| 901 | test.assertEquals('global', globalSetting.get().s); |
| 902 | test.assertEquals(2, globalSetting.get().n); |
| 903 | test.releaseControl(); |
| 904 | } |
| 905 | }; |
| 906 | |
| 907 | TestSuite.prototype.testWindowInitializedOnNavigateBack = function() { |
| 908 | const test = this; |
| 909 | test.takeControl(); |
| 910 | const messages = SDK.consoleModel.messages(); |
| 911 | if (messages.length === 1) |
| 912 | checkMessages(); |
| 913 | else |
| 914 | SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this); |
| 915 | |
| 916 | function checkMessages() { |
| 917 | const messages = SDK.consoleModel.messages(); |
| 918 | test.assertEquals(1, messages.length); |
| 919 | test.assertTrue(messages[0].messageText.indexOf('Uncaught') === -1); |
| 920 | test.releaseControl(); |
| 921 | } |
| 922 | }; |
| 923 | |
| 924 | TestSuite.prototype.testConsoleContextNames = function() { |
| 925 | const test = this; |
| 926 | test.takeControl(); |
| 927 | this.showPanel('console').then(() => this._waitForExecutionContexts(2, onExecutionContexts.bind(this))); |
| 928 | |
| 929 | function onExecutionContexts() { |
| 930 | const consoleView = Console.ConsoleView.instance(); |
| 931 | const selector = consoleView._consoleContextSelector; |
| 932 | const values = []; |
| 933 | for (const item of selector._items) |
| 934 | values.push(selector.titleFor(item)); |
| 935 | test.assertEquals('top', values[0]); |
| 936 | test.assertEquals('Simple content script', values[1]); |
| 937 | test.releaseControl(); |
| 938 | } |
| 939 | }; |
| 940 | |
| 941 | TestSuite.prototype.testRawHeadersWithHSTS = function(url) { |
| 942 | const test = this; |
| 943 | test.takeControl(); |
| 944 | SDK.targetManager.addModelListener( |
| 945 | SDK.NetworkManager, SDK.NetworkManager.Events.ResponseReceived, onResponseReceived); |
| 946 | |
| 947 | this.evaluateInConsole_(` |
| 948 | let img = document.createElement('img'); |
| 949 | img.src = "${url}"; |
| 950 | document.body.appendChild(img); |
| 951 | `, () => {}); |
| 952 | |
| 953 | let count = 0; |
| 954 | function onResponseReceived(event) { |
| 955 | const networkRequest = event.data; |
| 956 | if (!networkRequest.url().startsWith('http')) |
| 957 | return; |
| 958 | switch (++count) { |
| 959 | case 1: // Original redirect |
| 960 | test.assertEquals(301, networkRequest.statusCode); |
| 961 | test.assertEquals('Moved Permanently', networkRequest.statusText); |
| 962 | test.assertTrue(url.endsWith(networkRequest.responseHeaderValue('Location'))); |
| 963 | break; |
| 964 | |
| 965 | case 2: // HSTS internal redirect |
| 966 | test.assertTrue(networkRequest.url().startsWith('http://')); |
| 967 | test.assertEquals(undefined, networkRequest.requestHeadersText()); |
| 968 | test.assertEquals(307, networkRequest.statusCode); |
| 969 | test.assertEquals('Internal Redirect', networkRequest.statusText); |
| 970 | test.assertEquals('HSTS', networkRequest.responseHeaderValue('Non-Authoritative-Reason')); |
| 971 | test.assertTrue(networkRequest.responseHeaderValue('Location').startsWith('https://')); |
| 972 | break; |
| 973 | |
| 974 | case 3: // Final response |
| 975 | test.assertTrue(networkRequest.url().startsWith('https://')); |
| 976 | test.assertTrue(networkRequest.requestHeaderValue('Referer').startsWith('http://127.0.0.1')); |
| 977 | test.assertEquals(200, networkRequest.statusCode); |
| 978 | test.assertEquals('OK', networkRequest.statusText); |
| 979 | test.assertEquals('132', networkRequest.responseHeaderValue('Content-Length')); |
| 980 | test.releaseControl(); |
| 981 | } |
| 982 | } |
| 983 | }; |
| 984 | |
| 985 | TestSuite.prototype.testDOMWarnings = function() { |
| 986 | const messages = SDK.consoleModel.messages(); |
| 987 | this.assertEquals(1, messages.length); |
| 988 | const expectedPrefix = '[DOM] Found 2 elements with non-unique id #dup:'; |
| 989 | this.assertTrue(messages[0].messageText.startsWith(expectedPrefix)); |
| 990 | }; |
| 991 | |
| 992 | TestSuite.prototype.waitForTestResultsInConsole = function() { |
| 993 | const messages = SDK.consoleModel.messages(); |
| 994 | for (let i = 0; i < messages.length; ++i) { |
| 995 | const text = messages[i].messageText; |
| 996 | if (text === 'PASS') |
| 997 | return; |
| 998 | else if (/^FAIL/.test(text)) |
| 999 | this.fail(text); // This will throw. |
| 1000 | } |
| 1001 | // Neither PASS nor FAIL, so wait for more messages. |
| 1002 | function onConsoleMessage(event) { |
| 1003 | const text = event.data.messageText; |
| 1004 | if (text === 'PASS') |
| 1005 | this.releaseControl(); |
| 1006 | else if (/^FAIL/.test(text)) |
| 1007 | this.fail(text); |
| 1008 | } |
| 1009 | |
| 1010 | SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); |
| 1011 | this.takeControl(); |
| 1012 | }; |
| 1013 | |
| 1014 | TestSuite.prototype._overrideMethod = function(receiver, methodName, override) { |
| 1015 | const original = receiver[methodName]; |
| 1016 | if (typeof original !== 'function') { |
| 1017 | this.fail(`TestSuite._overrideMethod: $[methodName] is not a function`); |
| 1018 | return; |
| 1019 | } |
| 1020 | receiver[methodName] = function() { |
| 1021 | let value; |
| 1022 | try { |
| 1023 | value = original.apply(receiver, arguments); |
| 1024 | } finally { |
| 1025 | receiver[methodName] = original; |
| 1026 | } |
| 1027 | override.apply(original, arguments); |
| 1028 | return value; |
| 1029 | }; |
| 1030 | }; |
| 1031 | |
| 1032 | TestSuite.prototype.startTimeline = function(callback) { |
| 1033 | const test = this; |
| 1034 | this.showPanel('timeline').then(function() { |
| 1035 | const timeline = UI.panels.timeline; |
| 1036 | test._overrideMethod(timeline, '_recordingStarted', callback); |
| 1037 | timeline._toggleRecording(); |
| 1038 | }); |
| 1039 | }; |
| 1040 | |
| 1041 | TestSuite.prototype.stopTimeline = function(callback) { |
| 1042 | const timeline = UI.panels.timeline; |
| 1043 | this._overrideMethod(timeline, 'loadingComplete', callback); |
| 1044 | timeline._toggleRecording(); |
| 1045 | }; |
| 1046 | |
| 1047 | TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last) { |
| 1048 | const callback = arguments[arguments.length - 1]; |
| 1049 | const doneMessage = `DONE: ${functionName}.${++this._asyncInvocationId}`; |
| 1050 | const argsString = arguments.length < 3 ? |
| 1051 | '' : |
| 1052 | Array.prototype.slice.call(arguments, 1, -1).map(arg => JSON.stringify(arg)).join(',') + ','; |
| 1053 | this.evaluateInConsole_( |
| 1054 | `${functionName}(${argsString} function() { console.log('${doneMessage}'); });`, function() {}); |
| 1055 | SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage); |
| 1056 | |
| 1057 | function onConsoleMessage(event) { |
| 1058 | const text = event.data.messageText; |
| 1059 | if (text === doneMessage) { |
| 1060 | SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage); |
| 1061 | callback(); |
| 1062 | } |
| 1063 | } |
| 1064 | }; |
| 1065 | |
| 1066 | TestSuite.prototype.invokeAsyncWithTimeline_ = function(functionName, callback) { |
| 1067 | const test = this; |
| 1068 | |
| 1069 | this.startTimeline(onRecordingStarted); |
| 1070 | |
| 1071 | function onRecordingStarted() { |
| 1072 | test.invokePageFunctionAsync(functionName, pageActionsDone); |
| 1073 | } |
| 1074 | |
| 1075 | function pageActionsDone() { |
| 1076 | test.stopTimeline(callback); |
| 1077 | } |
| 1078 | }; |
| 1079 | |
| 1080 | TestSuite.prototype.enableExperiment = function(name) { |
| 1081 | Runtime.experiments.enableForTest(name); |
| 1082 | }; |
| 1083 | |
| 1084 | TestSuite.prototype.checkInputEventsPresent = function() { |
| 1085 | const expectedEvents = new Set(arguments); |
| 1086 | const model = UI.panels.timeline._performanceModel.timelineModel(); |
| 1087 | const asyncEvents = model.virtualThreads().find(thread => thread.isMainFrame).asyncEventsByGroup; |
| 1088 | const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || []; |
| 1089 | const prefix = 'InputLatency::'; |
| 1090 | for (const e of input) { |
| 1091 | if (!e.name.startsWith(prefix)) |
| 1092 | continue; |
| 1093 | if (e.steps.length < 2) |
| 1094 | continue; |
| 1095 | if (e.name.startsWith(prefix + 'Mouse') && |
| 1096 | typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') |
| 1097 | throw `Missing timeWaitingForMainThread on ${e.name}`; |
| 1098 | expectedEvents.delete(e.name.substr(prefix.length)); |
| 1099 | } |
| 1100 | if (expectedEvents.size) |
| 1101 | throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(','); |
| 1102 | }; |
| 1103 | |
| 1104 | TestSuite.prototype.testInspectedElementIs = async function(nodeName) { |
| 1105 | this.takeControl(); |
| 1106 | await self.runtime.loadModulePromise('elements'); |
| 1107 | if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) |
| 1108 | await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f)); |
| 1109 | this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest); |
| 1110 | this.releaseControl(); |
| 1111 | }; |
| 1112 | |
| 1113 | TestSuite.prototype.testInputDispatchEventsToOOPIF = async function() { |
| 1114 | this.takeControl(); |
| 1115 | |
| 1116 | await new Promise(callback => this._waitForTargets(2, callback)); |
| 1117 | |
| 1118 | async function takeLogs(target) { |
| 1119 | const code = ` |
| 1120 | (function() { |
| 1121 | var result = window.logs.join(' '); |
| 1122 | window.logs = []; |
| 1123 | return result; |
| 1124 | })() |
| 1125 | `; |
| 1126 | return (await target.runtimeAgent().invoke_evaluate({expression: code})).result.value; |
| 1127 | } |
| 1128 | |
| 1129 | let parentFrameOutput; |
| 1130 | let childFrameOutput; |
| 1131 | |
| 1132 | const inputAgent = SDK.targetManager.mainTarget().inputAgent(); |
| 1133 | const runtimeAgent = SDK.targetManager.mainTarget().runtimeAgent(); |
| 1134 | await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 10, y: 10}); |
| 1135 | await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 10, y: 20}); |
| 1136 | await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 10, y: 20}); |
| 1137 | await inputAgent.invoke_dispatchMouseEvent({type: 'mousePressed', button: 'left', clickCount: 1, x: 230, y: 140}); |
| 1138 | await inputAgent.invoke_dispatchMouseEvent({type: 'mouseMoved', button: 'left', clickCount: 1, x: 230, y: 150}); |
| 1139 | await inputAgent.invoke_dispatchMouseEvent({type: 'mouseReleased', button: 'left', clickCount: 1, x: 230, y: 150}); |
| 1140 | parentFrameOutput = 'Event type: mousedown button: 0 x: 10 y: 10 Event type: mouseup button: 0 x: 10 y: 20'; |
| 1141 | this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0])); |
| 1142 | childFrameOutput = 'Event type: mousedown button: 0 x: 30 y: 40 Event type: mouseup button: 0 x: 30 y: 50'; |
| 1143 | this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1])); |
| 1144 | |
| 1145 | |
| 1146 | await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'}); |
| 1147 | await runtimeAgent.invoke_evaluate({expression: `document.querySelector('iframe').focus()`}); |
| 1148 | await inputAgent.invoke_dispatchKeyEvent({type: 'keyDown', key: 'a'}); |
| 1149 | parentFrameOutput = 'Event type: keydown'; |
| 1150 | this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0])); |
| 1151 | childFrameOutput = 'Event type: keydown'; |
| 1152 | this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1])); |
| 1153 | |
| 1154 | await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 10, y: 10}]}); |
| 1155 | await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []}); |
| 1156 | await inputAgent.invoke_dispatchTouchEvent({type: 'touchStart', touchPoints: [{x: 230, y: 140}]}); |
| 1157 | await inputAgent.invoke_dispatchTouchEvent({type: 'touchEnd', touchPoints: []}); |
| 1158 | parentFrameOutput = 'Event type: touchstart touch x: 10 touch y: 10'; |
| 1159 | this.assertEquals(parentFrameOutput, await takeLogs(SDK.targetManager.targets()[0])); |
| 1160 | childFrameOutput = 'Event type: touchstart touch x: 30 touch y: 40'; |
| 1161 | this.assertEquals(childFrameOutput, await takeLogs(SDK.targetManager.targets()[1])); |
| 1162 | |
| 1163 | this.releaseControl(); |
| 1164 | }; |
| 1165 | |
| 1166 | TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL) { |
| 1167 | const test = this; |
| 1168 | const loggedHeaders = new Set(['cache-control', 'pragma']); |
| 1169 | function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) { |
| 1170 | return new Promise(fulfill => { |
| 1171 | Host.ResourceLoader.load(url, headers, callback); |
| 1172 | |
| 1173 | function callback(statusCode, headers, content) { |
| 1174 | test.assertEquals(expectedStatus, statusCode); |
| 1175 | |
| 1176 | const headersArray = []; |
| 1177 | for (const name in headers) { |
| 1178 | const nameLower = name.toLowerCase(); |
| 1179 | if (loggedHeaders.has(nameLower)) |
| 1180 | headersArray.push(nameLower); |
| 1181 | } |
| 1182 | headersArray.sort(); |
| 1183 | test.assertEquals(expectedHeaders.join(', '), headersArray.join(', ')); |
| 1184 | test.assertEquals(expectedContent, content); |
| 1185 | fulfill(); |
| 1186 | } |
| 1187 | }); |
| 1188 | } |
| 1189 | |
| 1190 | this.takeControl(); |
| 1191 | await testCase(baseURL + 'non-existent.html', undefined, 404, [], ''); |
| 1192 | await testCase(baseURL + 'hello.html', undefined, 200, [], '<!doctype html>\n<p>hello</p>\n'); |
| 1193 | await testCase(baseURL + 'echoheader?x-devtools-test', {'x-devtools-test': 'Foo'}, 200, ['cache-control'], 'Foo'); |
| 1194 | await testCase(baseURL + 'set-header?pragma:%20no-cache', undefined, 200, ['pragma'], 'pragma: no-cache'); |
| 1195 | |
| 1196 | await SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({ |
| 1197 | expression: `fetch("/set-cookie?devtools-test-cookie=Bar", |
| 1198 | {credentials: 'include'})`, |
| 1199 | awaitPromise: true |
| 1200 | }); |
| 1201 | await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar'); |
| 1202 | |
| 1203 | this.releaseControl(); |
| 1204 | }; |
| 1205 | |
| 1206 | /** |
| 1207 | * Serializes array of uiSourceCodes to string. |
| 1208 | * @param {!Array.<!Workspace.UISourceCode>} uiSourceCodes |
| 1209 | * @return {string} |
| 1210 | */ |
| 1211 | TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) { |
| 1212 | const names = []; |
| 1213 | for (let i = 0; i < uiSourceCodes.length; i++) |
| 1214 | names.push('"' + uiSourceCodes[i].url() + '"'); |
| 1215 | return names.join(','); |
| 1216 | }; |
| 1217 | |
| 1218 | /** |
| 1219 | * Returns all loaded non anonymous uiSourceCodes. |
| 1220 | * @return {!Array.<!Workspace.UISourceCode>} |
| 1221 | */ |
| 1222 | TestSuite.prototype.nonAnonymousUISourceCodes_ = function() { |
| 1223 | /** |
| 1224 | * @param {!Workspace.UISourceCode} uiSourceCode |
| 1225 | */ |
| 1226 | function filterOutService(uiSourceCode) { |
| 1227 | return !uiSourceCode.project().isServiceProject(); |
| 1228 | } |
| 1229 | |
| 1230 | const uiSourceCodes = Workspace.workspace.uiSourceCodes(); |
| 1231 | return uiSourceCodes.filter(filterOutService); |
| 1232 | }; |
| 1233 | |
| 1234 | /* |
| 1235 | * Evaluates the code in the console as if user typed it manually and invokes |
| 1236 | * the callback when the result message is received and added to the console. |
| 1237 | * @param {string} code |
| 1238 | * @param {function(string)} callback |
| 1239 | */ |
| 1240 | TestSuite.prototype.evaluateInConsole_ = function(code, callback) { |
| 1241 | function innerEvaluate() { |
| 1242 | UI.context.removeFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this); |
| 1243 | const consoleView = Console.ConsoleView.instance(); |
| 1244 | consoleView._prompt._appendCommand(code); |
| 1245 | |
| 1246 | this.addSniffer(Console.ConsoleView.prototype, '_consoleMessageAddedForTest', function(viewMessage) { |
| 1247 | callback(viewMessage.toMessageElement().deepTextContent()); |
| 1248 | }.bind(this)); |
| 1249 | } |
| 1250 | |
| 1251 | function showConsoleAndEvaluate() { |
| 1252 | Common.console.showPromise().then(innerEvaluate.bind(this)); |
| 1253 | } |
| 1254 | |
| 1255 | if (!UI.context.flavor(SDK.ExecutionContext)) { |
| 1256 | UI.context.addFlavorChangeListener(SDK.ExecutionContext, showConsoleAndEvaluate, this); |
| 1257 | return; |
| 1258 | } |
| 1259 | showConsoleAndEvaluate.call(this); |
| 1260 | }; |
| 1261 | |
| 1262 | /** |
| 1263 | * Checks that all expected scripts are present in the scripts list |
| 1264 | * in the Scripts panel. |
| 1265 | * @param {!Array.<string>} expected Regular expressions describing |
| 1266 | * expected script names. |
| 1267 | * @return {boolean} Whether all the scripts are in "scripts-files" select |
| 1268 | * box |
| 1269 | */ |
| 1270 | TestSuite.prototype._scriptsAreParsed = function(expected) { |
| 1271 | const uiSourceCodes = this.nonAnonymousUISourceCodes_(); |
| 1272 | // Check that at least all the expected scripts are present. |
| 1273 | const missing = expected.slice(0); |
| 1274 | for (let i = 0; i < uiSourceCodes.length; ++i) { |
| 1275 | for (let j = 0; j < missing.length; ++j) { |
| 1276 | if (uiSourceCodes[i].name().search(missing[j]) !== -1) { |
| 1277 | missing.splice(j, 1); |
| 1278 | break; |
| 1279 | } |
| 1280 | } |
| 1281 | } |
| 1282 | return missing.length === 0; |
| 1283 | }; |
| 1284 | |
| 1285 | /** |
| 1286 | * Waits for script pause, checks expectations, and invokes the callback. |
| 1287 | * @param {function():void} callback |
| 1288 | */ |
| 1289 | TestSuite.prototype._waitForScriptPause = function(callback) { |
| 1290 | this.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', callback); |
| 1291 | }; |
| 1292 | |
| 1293 | /** |
| 1294 | * Waits until all the scripts are parsed and invokes the callback. |
| 1295 | */ |
| 1296 | TestSuite.prototype._waitUntilScriptsAreParsed = function(expectedScripts, callback) { |
| 1297 | const test = this; |
| 1298 | |
| 1299 | function waitForAllScripts() { |
| 1300 | if (test._scriptsAreParsed(expectedScripts)) |
| 1301 | callback(); |
| 1302 | else |
| 1303 | test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts); |
| 1304 | } |
| 1305 | |
| 1306 | waitForAllScripts(); |
| 1307 | }; |
| 1308 | |
| 1309 | TestSuite.prototype._waitForTargets = function(n, callback) { |
| 1310 | checkTargets.call(this); |
| 1311 | |
| 1312 | function checkTargets() { |
| 1313 | if (SDK.targetManager.targets().length >= n) |
| 1314 | callback.call(null); |
| 1315 | else |
| 1316 | this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this)); |
| 1317 | } |
| 1318 | }; |
| 1319 | |
| 1320 | TestSuite.prototype._waitForExecutionContexts = function(n, callback) { |
| 1321 | const runtimeModel = SDK.targetManager.mainTarget().model(SDK.RuntimeModel); |
| 1322 | checkForExecutionContexts.call(this); |
| 1323 | |
| 1324 | function checkForExecutionContexts() { |
| 1325 | if (runtimeModel.executionContexts().length >= n) |
| 1326 | callback.call(null); |
| 1327 | else |
| 1328 | this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this)); |
| 1329 | } |
| 1330 | }; |
| 1331 | |
| 1332 | |
| 1333 | window.uiTests = new TestSuite(window.domAutomationController); |
| 1334 | })(window); |