How to use checkLifecycle method in Puppeteer

Best JavaScript code snippet using puppeteer

crosspagechannel_test.js

Source:crosspagechannel_test.js Github

copy

Full Screen

1/**2 * @license3 * Copyright The Closure Library Authors.4 * SPDX-License-Identifier: Apache-2.05 */6goog.module('goog.net.xpc.CrossPageChannelTest');7goog.setTestOnly('goog.net.xpc.CrossPageChannelTest');8const CfgFields = goog.require('goog.net.xpc.CfgFields');9const ChannelStates = goog.require('goog.net.xpc.ChannelStates');10const CrossPageChannel = goog.require('goog.net.xpc.CrossPageChannel');11const CrossPageChannelRole = goog.require('goog.net.xpc.CrossPageChannelRole');12const Disposable = goog.require('goog.Disposable');13const GoogPromise = goog.require('goog.Promise');14const Level = goog.require('goog.log.Level');15const PropertyReplacer = goog.require('goog.testing.PropertyReplacer');16const Resolver = goog.require('goog.promise.Resolver');17const TagName = goog.require('goog.dom.TagName');18const TestCase = goog.require('goog.testing.TestCase');19const Timer = goog.require('goog.Timer');20const TransportTypes = goog.require('goog.net.xpc.TransportTypes');21const Uri = goog.require('goog.Uri');22const browser = goog.require('goog.labs.userAgent.browser');23const dispose = goog.require('goog.dispose');24const dom = goog.require('goog.dom');25const log = goog.require('goog.log');26const object = goog.require('goog.object');27const testSuite = goog.require('goog.testing.testSuite');28const xpc = goog.require('goog.net.xpc');29/** @suppress {extraRequire} Needed for G_testRunner.log() */30goog.require('goog.testing.jsunit');31// Set this to false when working on this test. It needs to be true for32// automated testing, as some browsers (eg IE8) choke on the large numbers of33// iframes this test would otherwise leave active.34/** @const */35const CLEAN_UP_IFRAMES = true;36/** @const */37const IFRAME_LOAD_WAIT_MS = 1000;38const stubs = new PropertyReplacer();39let uniqueId = 0;40let driver;41let accessCheckPromise = null;42testSuite({43 setUpPage() {44 // This test is insanely slow on IE8 and Safari for some reason.45 TestCase.getActiveTestCase().promiseTimeout = 40 * 1000;46 // Show debug log47 const debugDiv = dom.getElement('debugDiv');48 const logger = log.getLogger('goog.net.xpc');49 log.setLevel(logger, Level.ALL);50 log.addHandler(logger, function(logRecord) {51 const msgElm = dom.createDom(TagName.DIV);52 msgElm.innerHTML = logRecord.getMessage();53 dom.appendChild(debugDiv, msgElm);54 });55 accessCheckPromise = new GoogPromise(function(resolve, reject) {56 const accessCheckIframes = [];57 accessCheckIframes.push(58 create1x1Iframe('nonexistent', 'testdata/i_am_non_existent.html'));59 window.setTimeout(function() {60 accessCheckIframes.push(61 create1x1Iframe('existent', 'testdata/access_checker.html'));62 }, 10);63 // Called from testdata/access_checker.html64 window['sameDomainIframeAccessComplete'] = function() {65 for (let i = 0; i < accessCheckIframes.length; i++) {66 document.body.removeChild(accessCheckIframes[i]);67 }68 resolve();69 };70 });71 },72 setUp() {73 driver = new Driver();74 // Expose driver on the window object, since inner_peer.html uses it to75 // communicate.76 window['driver'] = driver;77 // Ensure that the access check is complete before starting each test.78 return accessCheckPromise;79 },80 tearDown() {81 stubs.reset();82 driver.dispose();83 },84 testCreateIframeSpecifyId() {85 driver.createPeerIframe('new_iframe');86 return Timer.promise(IFRAME_LOAD_WAIT_MS).then(function() {87 driver.checkPeerIframe();88 });89 },90 testCreateIframeRandomId() {91 driver.createPeerIframe();92 return Timer.promise(IFRAME_LOAD_WAIT_MS).then(function() {93 driver.checkPeerIframe();94 });95 },96 testGetRole() {97 const cfg = {};98 cfg[CfgFields.ROLE] = CrossPageChannelRole.OUTER;99 const channel = new CrossPageChannel(cfg);100 // If the configured role is ignored, this will cause the dynamicly101 // determined role to become INNER.102 /** @suppress {visibility} suppression added to enable type checking */103 channel.peerWindowObject_ = window.parent;104 assertEquals(105 'Channel should use role from the config.', CrossPageChannelRole.OUTER,106 channel.getRole());107 channel.dispose();108 },109 // The following batch of tests:110 // * Establishes a peer iframe111 // * Connects an XPC channel between the frames112 // * From the connection callback in each frame, sends an 'echo' request, and113 // expects a 'response' response.114 // * Reconnects the inner frame, sends an 'echo', expects a 'response'.115 // * Optionally, reconnects the outer frame, sends an 'echo', expects a116 // 'response'.117 // * Optionally, reconnects the inner frame, but first reconfigures it to the118 // alternate protocol version, simulating an inner frame navigation that119 // picks up a new/old version.120 //121 // Every valid combination of protocol versions is tested, with both single122 // and double ended handshakes. Two timing scenarios are tested per123 // combination, which is what the 'reverse' parameter distinguishes.124 //125 // Where single sided handshake is in use, reconnection by the outer frame is126 // not supported, and therefore is not tested.127 //128 // The only known issue migrating to V2 is that once two V2 peers have129 // connected, replacing either peer with a V1 peer will not work. Upgrading130 // V1 peers to v2 is supported, as is replacing the only v2 peer in a131 // connection with a v1.132 testLifeCycle_v1_v1() {133 return checkLifeCycle(134 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,135 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,136 true /* innerFrameMigrationSupported */, false /* reverse */);137 },138 testLifeCycle_v1_v1_rev() {139 return checkLifeCycle(140 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,141 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,142 true /* innerFrameMigrationSupported */, true /* reverse */);143 },144 testLifeCycle_v1_v1_onesided() {145 return checkLifeCycle(146 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,147 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,148 true /* innerFrameMigrationSupported */, false /* reverse */);149 },150 testLifeCycle_v1_v1_onesided_rev() {151 return checkLifeCycle(152 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,153 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,154 true /* innerFrameMigrationSupported */, true /* reverse */);155 },156 testLifeCycle_v1_v2() {157 return checkLifeCycle(158 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,159 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,160 true /* innerFrameMigrationSupported */, false /* reverse */);161 },162 testLifeCycle_v1_v2_rev() {163 return checkLifeCycle(164 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,165 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,166 true /* innerFrameMigrationSupported */, true /* reverse */);167 },168 testLifeCycle_v1_v2_onesided() {169 return checkLifeCycle(170 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,171 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,172 true /* innerFrameMigrationSupported */, false /* reverse */);173 },174 testLifeCycle_v1_v2_onesided_rev() {175 return checkLifeCycle(176 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,177 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,178 true /* innerFrameMigrationSupported */, true /* reverse */);179 },180 testLifeCycle_v2_v1() {181 return checkLifeCycle(182 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,183 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,184 true /* innerFrameMigrationSupported */, false /* reverse */);185 },186 testLifeCycle_v2_v1_rev() {187 return checkLifeCycle(188 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,189 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,190 true /* innerFrameMigrationSupported */, true /* reverse */);191 },192 testLifeCycle_v2_v1_onesided() {193 return checkLifeCycle(194 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,195 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,196 true /* innerFrameMigrationSupported */, false /* reverse */);197 },198 testLifeCycle_v2_v1_onesided_rev() {199 return checkLifeCycle(200 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,201 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,202 true /* innerFrameMigrationSupported */, true /* reverse */);203 },204 testLifeCycle_v2_v2() {205 // Test flakes on IE 10+ and Chrome: see b/22873770 and b/18595666.206 if ((browser.isIE() && browser.isVersionOrHigher(10)) ||207 browser.isChrome()) {208 return;209 }210 return checkLifeCycle(211 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,212 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,213 false /* innerFrameMigrationSupported */, false /* reverse */);214 },215 testLifeCycle_v2_v2_rev() {216 return checkLifeCycle(217 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,218 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,219 false /* innerFrameMigrationSupported */, true /* reverse */);220 },221 testLifeCycle_v2_v2_onesided() {222 return checkLifeCycle(223 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,224 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,225 false /* innerFrameMigrationSupported */, false /* reverse */);226 },227 testLifeCycle_v2_v2_onesided_rev() {228 return checkLifeCycle(229 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,230 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,231 false /* innerFrameMigrationSupported */, true /* reverse */);232 },233 // testConnectMismatchedNames have been flaky on IEs.234 // Flakiness is tracked in http://b/18595666235 // For now, not running these tests on IE.236 testConnectMismatchedNames_v1_v1() {237 if (browser.isIE()) {238 return;239 }240 return checkConnectMismatchedNames(241 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,242 false /* reverse */);243 },244 testConnectMismatchedNames_v1_v1_rev() {245 if (browser.isIE()) {246 return;247 }248 return checkConnectMismatchedNames(249 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,250 true /* reverse */);251 },252 testConnectMismatchedNames_v1_v2() {253 if (browser.isIE()) {254 return;255 }256 return checkConnectMismatchedNames(257 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,258 false /* reverse */);259 },260 testConnectMismatchedNames_v1_v2_rev() {261 if (browser.isIE()) {262 return;263 }264 return checkConnectMismatchedNames(265 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,266 true /* reverse */);267 },268 testConnectMismatchedNames_v2_v1() {269 if (browser.isIE()) {270 return;271 }272 return checkConnectMismatchedNames(273 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,274 false /* reverse */);275 },276 testConnectMismatchedNames_v2_v1_rev() {277 if (browser.isIE()) {278 return;279 }280 return checkConnectMismatchedNames(281 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,282 true /* reverse */);283 },284 testConnectMismatchedNames_v2_v2() {285 if (browser.isIE()) {286 return;287 }288 return checkConnectMismatchedNames(289 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,290 false /* reverse */);291 },292 testConnectMismatchedNames_v2_v2_rev() {293 if (browser.isIE()) {294 return;295 }296 return checkConnectMismatchedNames(297 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,298 true /* reverse */);299 },300 /** @suppress {checkTypes} suppression added to enable type checking */301 testEscapeServiceName() {302 /** @suppress {visibility} suppression added to enable type checking */303 const escape = CrossPageChannel.prototype.escapeServiceName_;304 assertEquals(305 'Shouldn\'t escape alphanumeric name', 'fooBar123',306 escape('fooBar123'));307 assertEquals(308 'Shouldn\'t escape most non-alphanumeric characters',309 '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',310 escape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));311 assertEquals(312 'Should escape %, |, and :', 'foo%3ABar%7C123%25',313 escape('foo:Bar|123%'));314 assertEquals('Should escape tp', '%25tp', escape('tp'));315 assertEquals('Should escape %tp', '%25%25tp', escape('%tp'));316 assertEquals('Should not escape stp', 'stp', escape('stp'));317 assertEquals('Should not escape s%tp', 's%25tp', escape('s%tp'));318 },319 testSameDomainCheck_noMessageOrigin() {320 const channel = new CrossPageChannel(321 object.create(CfgFields.PEER_HOSTNAME, 'http://foo.com'));322 assertTrue(channel.isMessageOriginAcceptable(undefined));323 },324 testSameDomainCheck_noPeerHostname() {325 const channel = new CrossPageChannel({});326 assertTrue(channel.isMessageOriginAcceptable('http://foo.com'));327 },328 testSameDomainCheck_unconfigured() {329 const channel = new CrossPageChannel({});330 assertTrue(channel.isMessageOriginAcceptable(undefined));331 },332 testSameDomainCheck_originsMatch() {333 const channel = new CrossPageChannel(334 object.create(CfgFields.PEER_HOSTNAME, 'http://foo.com'));335 assertTrue(channel.isMessageOriginAcceptable('http://foo.com'));336 },337 testSameDomainCheck_originsMismatch() {338 const channel = new CrossPageChannel(339 object.create(CfgFields.PEER_HOSTNAME, 'http://foo.com'));340 assertFalse(channel.isMessageOriginAcceptable('http://nasty.com'));341 },342 /** @suppress {checkTypes} suppression added to enable type checking */343 testUnescapeServiceName() {344 /** @suppress {visibility} suppression added to enable type checking */345 const unescape = CrossPageChannel.prototype.unescapeServiceName_;346 assertEquals(347 'Shouldn\'t modify alphanumeric name', 'fooBar123',348 unescape('fooBar123'));349 assertEquals(350 'Shouldn\'t modify most non-alphanumeric characters',351 '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',352 unescape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));353 assertEquals(354 'Should unescape URL-escapes', 'foo:Bar|123%',355 unescape('foo%3ABar%7C123%25'));356 assertEquals('Should unescape tp', 'tp', unescape('%25tp'));357 assertEquals('Should unescape %tp', '%tp', unescape('%25%25tp'));358 assertEquals('Should not escape stp', 'stp', unescape('stp'));359 assertEquals('Should not escape s%tp', 's%tp', unescape('s%25tp'));360 },361 async testDisposeImmediate() {362 // Given363 driver.createPeerIframe(364 'new_iframe',365 /* oneSidedHandshake= */ false,366 /* innerProtocolVersion= */ 2,367 /* outerProtocolVersion= */ 2,368 /* opt_randomChannelNames= */ true);369 assertEquals(driver.getChannel().state_, ChannelStates.NOT_CONNECTED);370 assertNull(driver.getChannel().transport_);371 // When372 driver.getChannel().dispose();373 // Then374 assertTrue(driver.getChannel().isDisposed());375 // Let any errors caused by erroneous retries happen.376 await Timer.promise(2000);377 },378 async testDisposeBeforePeerNotification() {379 // Given380 driver.createPeerIframe(381 'new_iframe',382 /* oneSidedHandshake= */ false,383 /* innerProtocolVersion= */ 2,384 /* outerProtocolVersion= */ 2,385 /* opt_randomChannelNames= */ true);386 await driver.connectAndWaitForPeer();387 assertEquals(driver.getChannel().state_, ChannelStates.NOT_CONNECTED);388 const transport = driver.getChannel().transport_;389 // When390 driver.getChannel().dispose();391 // Then392 assertNull(driver.getChannel().transport_);393 assertTrue(driver.getChannel().isDisposed());394 assertTrue(transport.isDisposed());395 // Let any errors caused by erroneous retries happen.396 await Timer.promise(2000);397 },398});399/**400 * @param {string} iframeId401 * @param {string} src402 * @return {!HTMLIFrameElement}403 */404function create1x1Iframe(iframeId, src) {405 const iframeAccessChecker = dom.createElement(TagName.IFRAME);406 iframeAccessChecker.id = iframeAccessChecker.name = iframeId;407 iframeAccessChecker.style.width = iframeAccessChecker.style.height = '1px';408 iframeAccessChecker.src = src;409 document.body.insertBefore(iframeAccessChecker, document.body.firstChild);410 return iframeAccessChecker;411}412/**413 * @param {boolean} oneSidedHandshake,414 * @param {number} innerProtocolVersion415 * @param {number} outerProtocolVersion416 * @param {boolean} outerFrameReconnectSupported417 * @param {boolean} innerFrameMigrationSupported418 * @param {boolean} reverse419 * @return {!GoogPromise<undefined>}420 */421function checkLifeCycle(422 oneSidedHandshake, innerProtocolVersion, outerProtocolVersion,423 outerFrameReconnectSupported, innerFrameMigrationSupported, reverse) {424 driver.createPeerIframe(425 'new_iframe', oneSidedHandshake, innerProtocolVersion,426 outerProtocolVersion);427 return driver.connect(428 true /* fullLifeCycleTest */, outerFrameReconnectSupported,429 innerFrameMigrationSupported, reverse);430}431/**432 * @param {number} innerProtocolVersion433 * @param {number} outerProtocolVersion434 * @param {boolean} reverse435 * @return {!GoogPromise<undefined>}436 */437function checkConnectMismatchedNames(438 innerProtocolVersion, outerProtocolVersion, reverse) {439 driver.createPeerIframe(440 'new_iframe', false /* oneSidedHandshake */, innerProtocolVersion,441 outerProtocolVersion, true /* opt_randomChannelNames */);442 return driver.connect(443 false /* fullLifeCycleTest */, false /* outerFrameReconnectSupported */,444 false /* innerFrameMigrationSupported */, reverse /* reverse */);445}446/**447 * Driver for the tests for CrossPageChannel.448 * @unrestricted449 */450const Driver = class extends Disposable {451 constructor() {452 super();453 /**454 * The peer iframe.455 * @type {!Element}456 * @private457 * @suppress {checkTypes} suppression added to enable type checking458 */459 this.iframe_ = null;460 /**461 * The channel to use.462 * @type {?CrossPageChannel}463 * @private464 */465 this.channel_ = null;466 /**467 * Outer frame configuration object.468 * @type {?Object}469 * @private470 */471 this.outerFrameCfg_ = null;472 /**473 * The initial name of the outer channel.474 * @type {?string}475 * @private476 */477 this.initialOuterChannelName_ = null;478 /**479 * Inner frame configuration object.480 * @type {?Object}481 * @private482 */483 this.innerFrameCfg_ = null;484 /**485 * The contents of the payload of the 'echo' request sent by the inner486 * frame.487 * @type {?string}488 * @private489 */490 this.innerFrameEchoPayload_ = null;491 /**492 * The contents of the payload of the 'echo' request sent by the outer493 * frame.494 * @type {?string}495 * @private496 */497 this.outerFrameEchoPayload_ = null;498 /**499 * A resolver which fires its promise when the inner frame receives an echo.500 * @type {!Resolver}501 * @private502 */503 this.innerFrameResponseReceived_ = GoogPromise.withResolver();504 /**505 * A resolver which fires its promise when the outer frame receives an echo.506 * @type {!Resolver}507 * @private508 */509 this.outerFrameResponseReceived_ = GoogPromise.withResolver();510 }511 /** @override */512 disposeInternal() {513 // Required to make this test perform acceptably (and pass) on slow514 // browsers, esp IE8.515 if (CLEAN_UP_IFRAMES) {516 dom.removeNode(this.iframe_);517 delete this.iframe_;518 }519 dispose(this.channel_);520 this.innerFrameResponseReceived_.promise.cancel();521 this.outerFrameResponseReceived_.promise.cancel();522 super.disposeInternal();523 }524 /**525 * Returns the child peer's window object.526 * @return {!Window} Child peer's window.527 * @private528 * @suppress {strictMissingProperties} suppression added to enable type529 * checking530 */531 getInnerPeer_() {532 return this.iframe_.contentWindow;533 }534 /**535 * Sets up the configuration objects for the inner and outer frames.536 * @param {string=} opt_iframeId If present, the ID of the iframe to use,537 * otherwise, tells the channel to generate an iframe ID.538 * @param {boolean=} opt_oneSidedHandshake Whether the one sided handshake539 * config option should be set.540 * @param {string=} opt_channelName The name of the channel to use, or null541 * to generate one.542 * @param {number=} opt_innerProtocolVersion The native transport protocol543 * version used in the inner iframe.544 * @param {number=} opt_outerProtocolVersion The native transport protocol545 * version used in the outer iframe.546 * @param {boolean=} opt_randomChannelNames Whether the different ends of the547 * channel should be allowed to pick differing, random names.548 * @return {string} The name of the created channel.549 * @private550 * @suppress {missingReturn} suppression added to enable type checking551 */552 setConfiguration_(553 opt_iframeId, opt_oneSidedHandshake, opt_channelName,554 opt_innerProtocolVersion, opt_outerProtocolVersion,555 opt_randomChannelNames) {556 const cfg = {};557 if (opt_iframeId) {558 cfg[CfgFields.IFRAME_ID] = opt_iframeId;559 }560 cfg[CfgFields.PEER_URI] = 'testdata/inner_peer.html';561 if (!opt_randomChannelNames) {562 const channelName = opt_channelName || 'test_channel' + uniqueId++;563 cfg[CfgFields.CHANNEL_NAME] = channelName;564 }565 cfg[CfgFields.LOCAL_POLL_URI] = 'does-not-exist.html';566 cfg[CfgFields.PEER_POLL_URI] = 'does-not-exist.html';567 cfg[CfgFields.ONE_SIDED_HANDSHAKE] = !!opt_oneSidedHandshake;568 cfg[CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] = opt_outerProtocolVersion;569 function resolveUri(fieldName) {570 cfg[fieldName] =571 Uri.resolve(window.location.href, cfg[fieldName]).toString();572 }573 resolveUri(CfgFields.PEER_URI);574 resolveUri(CfgFields.LOCAL_POLL_URI);575 resolveUri(CfgFields.PEER_POLL_URI);576 this.outerFrameCfg_ = cfg;577 this.innerFrameCfg_ = object.clone(cfg);578 this.innerFrameCfg_[CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =579 opt_innerProtocolVersion;580 }581 /**582 * Creates an outer frame channel object.583 * @return {string}584 * @private585 * @suppress {checkTypes} suppression added to enable type checking586 */587 createChannel_() {588 if (this.channel_) {589 this.channel_.dispose();590 }591 this.channel_ = new CrossPageChannel(this.outerFrameCfg_);592 this.channel_.registerService('echo', goog.bind(this.echoHandler_, this));593 this.channel_.registerService(594 'response', goog.bind(this.responseHandler_, this));595 return this.channel_.name;596 }597 /**598 * Checks the names of the inner and outer frames meet expectations.599 * @private600 * @suppress {undefinedVars} suppression added to enable type checking601 */602 checkChannelNames_() {603 const outerName = this.channel_.name;604 /**605 * @suppress {missingProperties} suppression added to enable type checking606 */607 const innerName = this.getInnerPeer_().channel.name;608 const configName = this.innerFrameCfg_[CfgFields.CHANNEL_NAME] || null;609 // The outer channel never changes its name.610 assertEquals(this.initialOuterChannelName_, outerName);611 // The name should be as configured, if it was configured.612 if (configName) {613 assertEquals(configName, innerName);614 }615 // The names of both ends of the channel should match.616 assertEquals(innerName, outerName);617 G_testRunner.log('Channel name: ' + innerName);618 }619 /**620 * Returns the configuration of the xpc.621 * @return {?Object} The configuration of the xpc.622 */623 getInnerFrameConfiguration() {624 return this.innerFrameCfg_;625 }626 /**627 * Creates the peer iframe.628 * @param {string=} opt_iframeId If present, the ID of the iframe to create,629 * otherwise, generates an iframe ID.630 * @param {boolean=} opt_oneSidedHandshake Whether a one sided handshake is631 * specified.632 * @param {number=} opt_innerProtocolVersion The native transport protocol633 * version used in the inner iframe.634 * @param {number=} opt_outerProtocolVersion The native transport protocol635 * version used in the outer iframe.636 * @param {boolean=} opt_randomChannelNames Whether the ends of the channel637 * should be allowed to pick differing, random names.638 * @return {!Array<string>} The id of the created iframe and the name of the639 * created channel.640 * @suppress {missingReturn} suppression added to enable type checking641 */642 createPeerIframe(643 opt_iframeId, opt_oneSidedHandshake, opt_innerProtocolVersion,644 opt_outerProtocolVersion, opt_randomChannelNames) {645 let expectedIframeId;646 if (opt_iframeId) {647 expectedIframeId = opt_iframeId = opt_iframeId + uniqueId++;648 } else {649 // Have createPeerIframe() generate an ID650 stubs.set(xpc, 'getRandomString', function(length) {651 return '' + length;652 });653 expectedIframeId = 'xpcpeer4';654 }655 assertNull(656 'element[id=' + expectedIframeId + '] exists',657 dom.getElement(expectedIframeId));658 this.setConfiguration_(659 opt_iframeId, opt_oneSidedHandshake, undefined /* opt_channelName */,660 opt_innerProtocolVersion, opt_outerProtocolVersion,661 opt_randomChannelNames);662 const channelName = this.createChannel_();663 this.initialOuterChannelName_ = channelName;664 this.iframe_ = this.channel_.createPeerIframe(document.body);665 assertEquals(expectedIframeId, this.iframe_.id);666 }667 /**668 * Checks if the peer iframe has been created.669 */670 checkPeerIframe() {671 assertNotNull(this.iframe_);672 const peer = this.getInnerPeer_();673 assertNotNull(peer);674 assertNotNull(peer.document);675 }676 /**677 * Starts the connection. The connection happens asynchronously.678 * @param {boolean} fullLifeCycleTest679 * @param {boolean} outerFrameReconnectSupported680 * @param {boolean} innerFrameMigrationSupported681 * @param {boolean} reverse682 * @return {!GoogPromise<undefined>}683 * @suppress {checkTypes} suppression added to enable type checking684 */685 connect(686 fullLifeCycleTest, outerFrameReconnectSupported,687 innerFrameMigrationSupported, reverse) {688 if (!this.isTransportTestable_()) {689 return;690 }691 // Set the criteria for the initial handshake portion of the test.692 this.reinitializePromises_();693 this.innerFrameResponseReceived_.promise.then(694 this.checkChannelNames_, null, this);695 if (fullLifeCycleTest) {696 this.innerFrameResponseReceived_.promise.then(goog.bind(697 this.testReconnects_, this, outerFrameReconnectSupported,698 innerFrameMigrationSupported));699 }700 this.continueConnect_(reverse);701 return this.innerFrameResponseReceived_.promise;702 }703 /**704 * @param {boolean} reverse705 * @private706 * @suppress {missingProperties} suppression added to enable type checking707 */708 continueConnect_(reverse) {709 // Wait until the peer is fully established. Establishment is sometimes710 // very slow indeed, especially on virtual machines, so a fixed timeout is711 // not suitable. This wait is required because we want to take precise712 // control of the channel startup timing, and shouldn't be needed in713 // production use, where the inner frame's channel is typically not started714 // by a DOM call as it is here.715 if (!this.getInnerPeer_() || !this.getInnerPeer_().instantiateChannel) {716 window.setTimeout(goog.bind(this.continueConnect_, this, reverse), 100);717 return;718 }719 const connectFromOuterFrame = goog.bind(720 this.channel_.connect, this.channel_,721 goog.bind(this.outerFrameConnected_, this));722 const innerConfig = this.innerFrameCfg_;723 /**724 * @suppress {missingProperties} suppression added to enable type checking725 */726 const connectFromInnerFrame = goog.bind(727 this.getInnerPeer_().instantiateChannel, this.getInnerPeer_(),728 innerConfig);729 // Take control of the timing and reverse of each frame's first SETUP call.730 // If these happen to fire right on top of each other, that tends to mask731 // problems that reliably occur when there is a short delay.732 window.setTimeout(connectFromOuterFrame, reverse ? 1 : 10);733 window.setTimeout(connectFromInnerFrame, reverse ? 10 : 1);734 }735 /**736 * Called by the outer frame connection callback.737 * @private738 */739 outerFrameConnected_() {740 const payload = this.outerFrameEchoPayload_ = xpc.getRandomString(10);741 this.channel_.send('echo', payload);742 }743 /**744 * Called by the inner frame connection callback in inner_peer.html.745 * @suppress {missingProperties} suppression added to enable type checking746 */747 innerFrameConnected() {748 const payload = this.innerFrameEchoPayload_ = xpc.getRandomString(10);749 this.getInnerPeer_().sendEcho(payload);750 }751 /**752 * The handler function for incoming echo requests.753 * @param {string} payload The message payload.754 * @private755 * @suppress {strictMissingProperties} suppression added to enable type756 * checking757 */758 echoHandler_(payload) {759 assertTrue('outer frame should be connected', this.channel_.isConnected());760 const peer = this.getInnerPeer_();761 assertTrue('child should be connected', peer.isConnected());762 this.channel_.send('response', payload);763 }764 /**765 * The handler function for incoming echo responses.766 * @param {string} payload The message payload.767 * @private768 * @suppress {strictMissingProperties} suppression added to enable type769 * checking770 */771 responseHandler_(payload) {772 assertTrue('outer frame should be connected', this.channel_.isConnected());773 const peer = this.getInnerPeer_();774 assertTrue('child should be connected', peer.isConnected());775 assertEquals(this.outerFrameEchoPayload_, payload);776 this.outerFrameResponseReceived_.resolve(true);777 }778 /**779 * The handler function for incoming echo replies. Called from780 * inner_peer.html.781 * @param {string} payload The message payload.782 * @suppress {strictMissingProperties} suppression added to enable type783 * checking784 */785 innerFrameGotResponse(payload) {786 assertTrue('outer frame should be connected', this.channel_.isConnected());787 const peer = this.getInnerPeer_();788 assertTrue('child should be connected', peer.isConnected());789 assertEquals(this.innerFrameEchoPayload_, payload);790 this.innerFrameResponseReceived_.resolve(true);791 }792 /**793 * The second phase of the standard test, where reconnections of both the794 * inner and outer frames are performed.795 * @param {boolean} outerFrameReconnectSupported Whether outer frame796 * reconnects are supported, and should be tested.797 * @param {boolean} innerFrameMigrationSupported798 * @private799 */800 testReconnects_(outerFrameReconnectSupported, innerFrameMigrationSupported) {801 G_testRunner.log('Performing inner frame reconnect');802 this.reinitializePromises_();803 this.innerFrameResponseReceived_.promise.then(804 this.checkChannelNames_, null, this);805 if (outerFrameReconnectSupported) {806 this.innerFrameResponseReceived_.promise.then(goog.bind(807 this.performOuterFrameReconnect_, this,808 innerFrameMigrationSupported));809 } else if (innerFrameMigrationSupported) {810 this.innerFrameResponseReceived_.promise.then(811 this.migrateInnerFrame_, null, this);812 }813 this.performInnerFrameReconnect_();814 }815 /**816 * Initializes the promise resolvers and clears the echo payloads, ready for817 * another sub-test.818 * @private819 */820 reinitializePromises_() {821 this.innerFrameEchoPayload_ = null;822 this.outerFrameEchoPayload_ = null;823 this.innerFrameResponseReceived_.promise.cancel();824 this.innerFrameResponseReceived_ = GoogPromise.withResolver();825 this.outerFrameResponseReceived_.promise.cancel();826 this.outerFrameResponseReceived_ = GoogPromise.withResolver();827 }828 /**829 * Get the inner frame to reconnect, and repeat the echo test.830 * @private831 * @suppress {missingProperties} suppression added to enable type checking832 */833 performInnerFrameReconnect_() {834 const peer = this.getInnerPeer_();835 peer.instantiateChannel(this.innerFrameCfg_);836 }837 /**838 * Get the outer frame to reconnect, and repeat the echo test.839 * @private840 */841 performOuterFrameReconnect_(innerFrameMigrationSupported) {842 G_testRunner.log('Closing channel');843 this.channel_.close();844 // If there is another channel still open, the native transport's global845 // postMessage listener will still be active. This will mean that messages846 // being sent to the now-closed channel will still be received and847 // delivered, such as transport service traffic from its previous848 // correspondent in the other frame. Ensure these messages don't cause849 // exceptions.850 try {851 this.channel_.xpcDeliver(xpc.TRANSPORT_SERVICE, 'payload');852 } catch (e) {853 fail('Should not throw exception');854 }855 G_testRunner.log('Reconnecting outer frame');856 this.reinitializePromises_();857 this.innerFrameResponseReceived_.promise.then(858 this.checkChannelNames_, null, this);859 if (innerFrameMigrationSupported) {860 this.outerFrameResponseReceived_.promise.then(861 this.migrateInnerFrame_, null, this);862 }863 this.channel_.connect(goog.bind(this.outerFrameConnected_, this));864 }865 /**866 * Migrate the inner frame to the alternate protocol version and reconnect it.867 * @private868 */869 migrateInnerFrame_() {870 G_testRunner.log('Migrating inner frame');871 this.reinitializePromises_();872 const innerFrameProtoVersion =873 this.innerFrameCfg_[CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION];874 this.innerFrameResponseReceived_.promise.then(875 this.checkChannelNames_, null, this);876 this.innerFrameCfg_[CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =877 innerFrameProtoVersion == 1 ? 2 : 1;878 this.performInnerFrameReconnect_();879 }880 /**881 * Determines if the transport type for the channel is testable.882 * Some transports are misusing global state or making other883 * assumptions that cause connections to fail.884 * @return {boolean} Whether the transport is testable.885 * @private886 */887 isTransportTestable_() {888 let testable = false;889 /** @suppress {visibility} suppression added to enable type checking */890 const transportType = this.channel_.determineTransportType_();891 switch (transportType) {892 case TransportTypes.NATIVE_MESSAGING:893 case TransportTypes.DIRECT:894 testable = true;895 break;896 }897 return testable;898 }899 /** @return {?CrossPageChannel} */900 getChannel() {901 return this.channel_;902 }903 /**904 * Begin, but don't finish, connection to a peer.905 *906 * @return {!Promise<undefined>} A timing hook for the unstable period between907 * the creation of the peer and the connection notification from that908 * peer.909 */910 connectAndWaitForPeer() {911 this.channel_.connect();912 // Set a listener for when the peer exists.913 return new Promise(914 /** @suppress {visibility} suppression added to enable type checking */915 (res) => this.channel_.peerWindowDeferred_.addCallback(res));916 }...

Full Screen

Full Screen

NavigatorWatcher.js

Source:NavigatorWatcher.js Github

copy

Full Screen

...85 _checkLifecycleComplete() {86 // We expect navigation to commit.87 if (this._frame._loaderId === this._initialLoaderId && !this._hasSameDocumentNavigation)88 return;89 if (!checkLifecycle(this._frame, this._expectedLifecycle))90 return;91 this._lifecycleCompleteCallback();92 /**93 * @param {!Puppeteer.Frame} frame94 * @param {!Array<string>} expectedLifecycle95 * @return {boolean}96 */97 function checkLifecycle(frame, expectedLifecycle) {98 for (const event of expectedLifecycle) {99 if (!frame._lifecycleEvents.has(event))100 return false;101 }102 for (const child of frame.childFrames()) {103 if (!checkLifecycle(child, expectedLifecycle))104 return false;105 }106 return true;107 }108 }109 cancel() {110 this._cleanup();111 }112 _cleanup() {113 helper.removeEventListeners(this._eventListeners);114 this._lifecycleCompleteCallback(new Error('Navigation failed'));115 clearTimeout(this._maximumTimer);116 }117}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const { checkLifecycle } = require('puppeteer-lifecycle');3(async () => {4 const browser = await puppeteer.launch({ headless: false });5 const page = await browser.newPage();6 await checkLifecycle(page, 'networkidle0', 10000);7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();10### checkLifecycle(page, lifecycle, timeout)

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const browser = await puppeteer.launch({headless: false});3const page = await browser.newPage();4await page.screenshot({path: 'example.png'});5await browser.close();6To get more help on the Puppeteer API, check out the [Puppeteer API documentation](

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const browser = await puppeteer.launch();3const page = await browser.newPage();4await page.checkLifecycle();5await browser.close();6### page.checkLifecycle()7### page.checkLifecycle(options)8MIT © [Nathan Sobo](

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful