Debian Codegraph @

closure-library/closure/goog/net/xpc/crosspagechannel_test.js

raw
1 // Copyright 2009 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.net.xpc.CrossPageChannelTest');
16 goog.setTestOnly('goog.net.xpc.CrossPageChannelTest');
17
18 goog.require('goog.Disposable');
19 goog.require('goog.Promise');
20 goog.require('goog.Timer');
21 goog.require('goog.Uri');
22 goog.require('goog.dom');
23 goog.require('goog.dom.TagName');
24 goog.require('goog.labs.userAgent.browser');
25 goog.require('goog.log');
26 goog.require('goog.log.Level');
27 goog.require('goog.net.xpc');
28 goog.require('goog.net.xpc.CfgFields');
29 goog.require('goog.net.xpc.CrossPageChannel');
30 goog.require('goog.net.xpc.CrossPageChannelRole');
31 goog.require('goog.net.xpc.TransportTypes');
32 goog.require('goog.object');
33 goog.require('goog.testing.PropertyReplacer');
34 goog.require('goog.testing.TestCase');
35 goog.require('goog.testing.jsunit');
36
37 // Set this to false when working on this test. It needs to be true for
38 // automated testing, as some browsers (eg IE8) choke on the large numbers of
39 // iframes this test would otherwise leave active.
40 var CLEAN_UP_IFRAMES = true;
41
42 var IFRAME_LOAD_WAIT_MS = 1000;
43 var stubs = new goog.testing.PropertyReplacer();
44 var uniqueId = 0;
45 var driver;
46 var canAccessSameDomainIframe = true;
47 var accessCheckPromise = null;
48
49 function setUpPage() {
50 // This test is insanely slow on IE8 for some reason.
51 goog.testing.TestCase.getActiveTestCase().promiseTimeout = 20 * 1000;
52
53 // Show debug log
54 var debugDiv = goog.dom.getElement('debugDiv');
55 var logger = goog.log.getLogger('goog.net.xpc');
56 logger.setLevel(goog.log.Level.ALL);
57 goog.log.addHandler(logger, function(logRecord) {
58 var msgElm = goog.dom.createDom(goog.dom.TagName.DIV);
59 msgElm.innerHTML = logRecord.getMessage();
60 goog.dom.appendChild(debugDiv, msgElm);
61 });
62
63 accessCheckPromise = new goog.Promise(function(resolve, reject) {
64 var accessCheckIframes = [];
65
66 accessCheckIframes.push(
67 create1x1Iframe('nonexistent', 'testdata/i_am_non_existent.html'));
68 window.setTimeout(function() {
69 accessCheckIframes.push(
70 create1x1Iframe('existent', 'testdata/access_checker.html'));
71 }, 10);
72
73 // Called from testdata/access_checker.html
74 window['sameDomainIframeAccessComplete'] = function(canAccess) {
75 canAccessSameDomainIframe = canAccess;
76 for (var i = 0; i < accessCheckIframes.length; i++) {
77 document.body.removeChild(accessCheckIframes[i]);
78 }
79 resolve();
80 };
81 });
82 }
83
84
85 function setUp() {
86 driver = new Driver();
87 // Ensure that the access check is complete before starting each test.
88 return accessCheckPromise;
89 }
90
91
92 function tearDown() {
93 stubs.reset();
94 driver.dispose();
95 }
96
97
98 function create1x1Iframe(iframeId, src) {
99 var iframeAccessChecker = goog.dom.createElement(goog.dom.TagName.IFRAME);
100 iframeAccessChecker.id = iframeAccessChecker.name = iframeId;
101 iframeAccessChecker.style.width = iframeAccessChecker.style.height = '1px';
102 iframeAccessChecker.src = src;
103 document.body.insertBefore(iframeAccessChecker, document.body.firstChild);
104 return iframeAccessChecker;
105 }
106
107
108 function testCreateIframeSpecifyId() {
109 driver.createPeerIframe('new_iframe');
110
111 return goog.Timer.promise(IFRAME_LOAD_WAIT_MS).then(function() {
112 driver.checkPeerIframe();
113 });
114 }
115
116
117 function testCreateIframeRandomId() {
118 driver.createPeerIframe();
119
120 return goog.Timer.promise(IFRAME_LOAD_WAIT_MS).then(function() {
121 driver.checkPeerIframe();
122 });
123 }
124
125
126 function testGetRole() {
127 var cfg = {};
128 cfg[goog.net.xpc.CfgFields.ROLE] = goog.net.xpc.CrossPageChannelRole.OUTER;
129 var channel = new goog.net.xpc.CrossPageChannel(cfg);
130 // If the configured role is ignored, this will cause the dynamicly
131 // determined role to become INNER.
132 channel.peerWindowObject_ = window.parent;
133 assertEquals(
134 'Channel should use role from the config.',
135 goog.net.xpc.CrossPageChannelRole.OUTER, channel.getRole());
136 channel.dispose();
137 }
138
139
140 // The following batch of tests:
141 // * Establishes a peer iframe
142 // * Connects an XPC channel between the frames
143 // * From the connection callback in each frame, sends an 'echo' request, and
144 // expects a 'response' response.
145 // * Reconnects the inner frame, sends an 'echo', expects a 'response'.
146 // * Optionally, reconnects the outer frame, sends an 'echo', expects a
147 // 'response'.
148 // * Optionally, reconnects the inner frame, but first reconfigures it to the
149 // alternate protocol version, simulating an inner frame navigation that
150 // picks up a new/old version.
151 //
152 // Every valid combination of protocol versions is tested, with both single and
153 // double ended handshakes. Two timing scenarios are tested per combination,
154 // which is what the 'reverse' parameter distinguishes.
155 //
156 // Where single sided handshake is in use, reconnection by the outer frame is
157 // not supported, and therefore is not tested.
158 //
159 // The only known issue migrating to V2 is that once two V2 peers have
160 // connected, replacing either peer with a V1 peer will not work. Upgrading V1
161 // peers to v2 is supported, as is replacing the only v2 peer in a connection
162 // with a v1.
163
164
165 function testLifeCycle_v1_v1() {
166 return checkLifeCycle(
167 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
168 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
169 true /* innerFrameMigrationSupported */, false /* reverse */);
170 }
171
172
173 function testLifeCycle_v1_v1_rev() {
174 return checkLifeCycle(
175 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
176 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
177 true /* innerFrameMigrationSupported */, true /* reverse */);
178 }
179
180
181 function testLifeCycle_v1_v1_onesided() {
182 return checkLifeCycle(
183 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
184 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
185 true /* innerFrameMigrationSupported */, false /* reverse */);
186 }
187
188
189 function testLifeCycle_v1_v1_onesided_rev() {
190 return checkLifeCycle(
191 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
192 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
193 true /* innerFrameMigrationSupported */, true /* reverse */);
194 }
195
196
197 function testLifeCycle_v1_v2() {
198 return checkLifeCycle(
199 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
200 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
201 true /* innerFrameMigrationSupported */, false /* reverse */);
202 }
203
204
205 function testLifeCycle_v1_v2_rev() {
206 return checkLifeCycle(
207 false /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
208 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
209 true /* innerFrameMigrationSupported */, true /* reverse */);
210 }
211
212
213 function testLifeCycle_v1_v2_onesided() {
214 return checkLifeCycle(
215 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
216 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
217 true /* innerFrameMigrationSupported */, false /* reverse */);
218 }
219
220
221 function testLifeCycle_v1_v2_onesided_rev() {
222 return checkLifeCycle(
223 true /* oneSidedHandshake */, 1 /* innerProtocolVersion */,
224 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
225 true /* innerFrameMigrationSupported */, true /* reverse */);
226 }
227
228
229 function testLifeCycle_v2_v1() {
230 return checkLifeCycle(
231 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
232 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
233 true /* innerFrameMigrationSupported */, false /* reverse */);
234 }
235
236
237 function testLifeCycle_v2_v1_rev() {
238 return checkLifeCycle(
239 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
240 1 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
241 true /* innerFrameMigrationSupported */, true /* reverse */);
242 }
243
244
245 function testLifeCycle_v2_v1_onesided() {
246 return checkLifeCycle(
247 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
248 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
249 true /* innerFrameMigrationSupported */, false /* reverse */);
250 }
251
252
253 function testLifeCycle_v2_v1_onesided_rev() {
254 return checkLifeCycle(
255 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
256 1 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
257 true /* innerFrameMigrationSupported */, true /* reverse */);
258 }
259
260
261 function testLifeCycle_v2_v2() {
262 // Test flakes on IE 10+ and Chrome: see b/22873770 and b/18595666.
263 if ((goog.labs.userAgent.browser.isIE() &&
264 goog.labs.userAgent.browser.isVersionOrHigher(10)) ||
265 goog.labs.userAgent.browser.isChrome()) {
266 return;
267 }
268
269 return checkLifeCycle(
270 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
271 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
272 false /* innerFrameMigrationSupported */, false /* reverse */);
273 }
274
275
276 function testLifeCycle_v2_v2_rev() {
277 return checkLifeCycle(
278 false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
279 2 /* outerProtocolVersion */, true /* outerFrameReconnectSupported */,
280 false /* innerFrameMigrationSupported */, true /* reverse */);
281 }
282
283
284 function testLifeCycle_v2_v2_onesided() {
285 return checkLifeCycle(
286 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
287 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
288 false /* innerFrameMigrationSupported */, false /* reverse */);
289 }
290
291
292 function testLifeCycle_v2_v2_onesided_rev() {
293 return checkLifeCycle(
294 true /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
295 2 /* outerProtocolVersion */, false /* outerFrameReconnectSupported */,
296 false /* innerFrameMigrationSupported */, true /* reverse */);
297 }
298
299
300 function checkLifeCycle(
301 oneSidedHandshake, innerProtocolVersion, outerProtocolVersion,
302 outerFrameReconnectSupported, innerFrameMigrationSupported, reverse) {
303 driver.createPeerIframe(
304 'new_iframe', oneSidedHandshake, innerProtocolVersion,
305 outerProtocolVersion);
306 return driver.connect(
307 true /* fullLifeCycleTest */, outerFrameReconnectSupported,
308 innerFrameMigrationSupported, reverse);
309 }
310
311 // testConnectMismatchedNames have been flaky on IEs.
312 // Flakiness is tracked in http://b/18595666
313 // For now, not running these tests on IE.
314
315 function testConnectMismatchedNames_v1_v1() {
316 if (goog.labs.userAgent.browser.isIE()) {
317 return;
318 }
319
320 return checkConnectMismatchedNames(
321 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,
322 false /* reverse */);
323 }
324
325
326 function testConnectMismatchedNames_v1_v1_rev() {
327 if (goog.labs.userAgent.browser.isIE()) {
328 return;
329 }
330
331 return checkConnectMismatchedNames(
332 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,
333 true /* reverse */);
334 }
335
336
337 function testConnectMismatchedNames_v1_v2() {
338 if (goog.labs.userAgent.browser.isIE()) {
339 return;
340 }
341
342 return checkConnectMismatchedNames(
343 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,
344 false /* reverse */);
345 }
346
347
348 function testConnectMismatchedNames_v1_v2_rev() {
349 if (goog.labs.userAgent.browser.isIE()) {
350 return;
351 }
352
353 return checkConnectMismatchedNames(
354 1 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,
355 true /* reverse */);
356 }
357
358
359 function testConnectMismatchedNames_v2_v1() {
360 if (goog.labs.userAgent.browser.isIE()) {
361 return;
362 }
363
364 return checkConnectMismatchedNames(
365 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,
366 false /* reverse */);
367 }
368
369
370 function testConnectMismatchedNames_v2_v1_rev() {
371 if (goog.labs.userAgent.browser.isIE()) {
372 return;
373 }
374
375 return checkConnectMismatchedNames(
376 2 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,
377 true /* reverse */);
378 }
379
380
381 function testConnectMismatchedNames_v2_v2() {
382 if (goog.labs.userAgent.browser.isIE()) {
383 return;
384 }
385
386 return checkConnectMismatchedNames(
387 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,
388 false /* reverse */);
389 }
390
391
392 function testConnectMismatchedNames_v2_v2_rev() {
393 if (goog.labs.userAgent.browser.isIE()) {
394 return;
395 }
396
397 return checkConnectMismatchedNames(
398 2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,
399 true /* reverse */);
400 }
401
402
403 function checkConnectMismatchedNames(
404 innerProtocolVersion, outerProtocolVersion, reverse) {
405 driver.createPeerIframe(
406 'new_iframe', false /* oneSidedHandshake */, innerProtocolVersion,
407 outerProtocolVersion, true /* opt_randomChannelNames */);
408 return driver.connect(
409 false /* fullLifeCycleTest */, false /* outerFrameReconnectSupported */,
410 false /* innerFrameMigrationSupported */, reverse /* reverse */);
411 }
412
413
414 function testEscapeServiceName() {
415 var escape = goog.net.xpc.CrossPageChannel.prototype.escapeServiceName_;
416 assertEquals(
417 'Shouldn\'t escape alphanumeric name', 'fooBar123', escape('fooBar123'));
418 assertEquals(
419 'Shouldn\'t escape most non-alphanumeric characters',
420 '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',
421 escape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));
422 assertEquals(
423 'Should escape %, |, and :', 'foo%3ABar%7C123%25',
424 escape('foo:Bar|123%'));
425 assertEquals('Should escape tp', '%25tp', escape('tp'));
426 assertEquals('Should escape %tp', '%25%25tp', escape('%tp'));
427 assertEquals('Should not escape stp', 'stp', escape('stp'));
428 assertEquals('Should not escape s%tp', 's%25tp', escape('s%tp'));
429 }
430
431
432 function testSameDomainCheck_noMessageOrigin() {
433 var channel = new goog.net.xpc.CrossPageChannel(
434 goog.object.create(
435 goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
436 assertTrue(channel.isMessageOriginAcceptable(undefined));
437 }
438
439
440 function testSameDomainCheck_noPeerHostname() {
441 var channel = new goog.net.xpc.CrossPageChannel({});
442 assertTrue(channel.isMessageOriginAcceptable('http://foo.com'));
443 }
444
445
446 function testSameDomainCheck_unconfigured() {
447 var channel = new goog.net.xpc.CrossPageChannel({});
448 assertTrue(channel.isMessageOriginAcceptable(undefined));
449 }
450
451
452 function testSameDomainCheck_originsMatch() {
453 var channel = new goog.net.xpc.CrossPageChannel(
454 goog.object.create(
455 goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
456 assertTrue(channel.isMessageOriginAcceptable('http://foo.com'));
457 }
458
459
460 function testSameDomainCheck_originsMismatch() {
461 var channel = new goog.net.xpc.CrossPageChannel(
462 goog.object.create(
463 goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
464 assertFalse(channel.isMessageOriginAcceptable('http://nasty.com'));
465 }
466
467
468 function testUnescapeServiceName() {
469 var unescape = goog.net.xpc.CrossPageChannel.prototype.unescapeServiceName_;
470 assertEquals(
471 'Shouldn\'t modify alphanumeric name', 'fooBar123',
472 unescape('fooBar123'));
473 assertEquals(
474 'Shouldn\'t modify most non-alphanumeric characters',
475 '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',
476 unescape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));
477 assertEquals(
478 'Should unescape URL-escapes', 'foo:Bar|123%',
479 unescape('foo%3ABar%7C123%25'));
480 assertEquals('Should unescape tp', 'tp', unescape('%25tp'));
481 assertEquals('Should unescape %tp', '%tp', unescape('%25%25tp'));
482 assertEquals('Should not escape stp', 'stp', unescape('stp'));
483 assertEquals('Should not escape s%tp', 's%tp', unescape('s%25tp'));
484 }
485
486
487 /**
488 * Tests the case where the channel is disposed before it is fully connected.
489 */
490 function testDisposeBeforeConnect() {
491 // Test flakes on IE: see b/22873770 and b/18595666.
492 if (goog.labs.userAgent.browser.isIE() &&
493 goog.labs.userAgent.browser.isVersionOrHigher(9)) {
494 return;
495 }
496
497 driver.createPeerIframe(
498 'new_iframe', false /* oneSidedHandshake */, 2 /* innerProtocolVersion */,
499 2 /* outerProtocolVersion */, true /* opt_randomChannelNames */);
500 return driver.connectOuterAndDispose();
501 }
502
503
504
505 /**
506 * Driver for the tests for CrossPageChannel.
507 *
508 * @constructor
509 * @extends {goog.Disposable}
510 */
511 Driver = function() {
512 goog.Disposable.call(this);
513
514 /**
515 * The peer iframe.
516 * @type {!Element}
517 * @private
518 */
519 this.iframe_ = null;
520
521 /**
522 * The channel to use.
523 * @type {goog.net.xpc.CrossPageChannel}
524 * @private
525 */
526 this.channel_ = null;
527
528 /**
529 * Outer frame configuration object.
530 * @type {Object}
531 * @private
532 */
533 this.outerFrameCfg_ = null;
534
535 /**
536 * The initial name of the outer channel.
537 * @type {?string}
538 * @private
539 */
540 this.initialOuterChannelName_ = null;
541
542 /**
543 * Inner frame configuration object.
544 * @type {Object}
545 * @private
546 */
547 this.innerFrameCfg_ = null;
548
549 /**
550 * The contents of the payload of the 'echo' request sent by the inner frame.
551 * @type {?string}
552 * @private
553 */
554 this.innerFrameEchoPayload_ = null;
555
556 /**
557 * The contents of the payload of the 'echo' request sent by the outer frame.
558 * @type {?string}
559 * @private
560 */
561 this.outerFrameEchoPayload_ = null;
562
563 /**
564 * A resolver which fires its promise when the inner frame receives an echo.
565 * @type {!goog.promise.Resolver}
566 * @private
567 */
568 this.innerFrameResponseReceived_ = goog.Promise.withResolver();
569
570 /**
571 * A resolver which fires its promise when the outer frame receives an echo.
572 * @type {!goog.promise.Resolver}
573 * @private
574 */
575 this.outerFrameResponseReceived_ = goog.Promise.withResolver();
576
577 };
578 goog.inherits(Driver, goog.Disposable);
579
580
581 /** @override */
582 Driver.prototype.disposeInternal = function() {
583 // Required to make this test perform acceptably (and pass) on slow browsers,
584 // esp IE8.
585 if (CLEAN_UP_IFRAMES) {
586 goog.dom.removeNode(this.iframe_);
587 delete this.iframe_;
588 }
589 goog.dispose(this.channel_);
590 this.innerFrameResponseReceived_.promise.cancel();
591 this.outerFrameResponseReceived_.promise.cancel();
592 Driver.base(this, 'disposeInternal');
593 };
594
595
596 /**
597 * Returns the child peer's window object.
598 * @return {Window} Child peer's window.
599 * @private
600 */
601 Driver.prototype.getInnerPeer_ = function() {
602 return this.iframe_.contentWindow;
603 };
604
605
606 /**
607 * Sets up the configuration objects for the inner and outer frames.
608 * @param {string=} opt_iframeId If present, the ID of the iframe to use,
609 * otherwise, tells the channel to generate an iframe ID.
610 * @param {boolean=} opt_oneSidedHandshake Whether the one sided handshake
611 * config option should be set.
612 * @param {string=} opt_channelName The name of the channel to use, or null
613 * to generate one.
614 * @param {number=} opt_innerProtocolVersion The native transport protocol
615 * version used in the inner iframe.
616 * @param {number=} opt_outerProtocolVersion The native transport protocol
617 * version used in the outer iframe.
618 * @param {boolean=} opt_randomChannelNames Whether the different ends of the
619 * channel should be allowed to pick differing, random names.
620 * @return {string} The name of the created channel.
621 * @private
622 */
623 Driver.prototype.setConfiguration_ = function(
624 opt_iframeId, opt_oneSidedHandshake, opt_channelName,
625 opt_innerProtocolVersion, opt_outerProtocolVersion,
626 opt_randomChannelNames) {
627 var cfg = {};
628 if (opt_iframeId) {
629 cfg[goog.net.xpc.CfgFields.IFRAME_ID] = opt_iframeId;
630 }
631 cfg[goog.net.xpc.CfgFields.PEER_URI] = 'testdata/inner_peer.html';
632 if (!opt_randomChannelNames) {
633 var channelName = opt_channelName || 'test_channel' + uniqueId++;
634 cfg[goog.net.xpc.CfgFields.CHANNEL_NAME] = channelName;
635 }
636 cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = 'does-not-exist.html';
637 cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = 'does-not-exist.html';
638 cfg[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE] = !!opt_oneSidedHandshake;
639 cfg[goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =
640 opt_outerProtocolVersion;
641 function resolveUri(fieldName) {
642 cfg[fieldName] =
643 goog.Uri.resolve(window.location.href, cfg[fieldName]).toString();
644 }
645 resolveUri(goog.net.xpc.CfgFields.PEER_URI);
646 resolveUri(goog.net.xpc.CfgFields.LOCAL_POLL_URI);
647 resolveUri(goog.net.xpc.CfgFields.PEER_POLL_URI);
648 this.outerFrameCfg_ = cfg;
649 this.innerFrameCfg_ = goog.object.clone(cfg);
650 this.innerFrameCfg_[goog.net.xpc.CfgFields
651 .NATIVE_TRANSPORT_PROTOCOL_VERSION] =
652 opt_innerProtocolVersion;
653 };
654
655
656 /**
657 * Creates an outer frame channel object.
658 * @private
659 */
660 Driver.prototype.createChannel_ = function() {
661 if (this.channel_) {
662 this.channel_.dispose();
663 }
664 this.channel_ = new goog.net.xpc.CrossPageChannel(this.outerFrameCfg_);
665 this.channel_.registerService('echo', goog.bind(this.echoHandler_, this));
666 this.channel_.registerService(
667 'response', goog.bind(this.responseHandler_, this));
668
669 return this.channel_.name;
670 };
671
672
673 /**
674 * Checks the names of the inner and outer frames meet expectations.
675 * @private
676 */
677 Driver.prototype.checkChannelNames_ = function() {
678 var outerName = this.channel_.name;
679 var innerName = this.getInnerPeer_().channel.name;
680 var configName =
681 this.innerFrameCfg_[goog.net.xpc.CfgFields.CHANNEL_NAME] || null;
682
683 // The outer channel never changes its name.
684 assertEquals(this.initialOuterChannelName_, outerName);
685 // The name should be as configured, if it was configured.
686 if (configName) {
687 assertEquals(configName, innerName);
688 }
689 // The names of both ends of the channel should match.
690 assertEquals(innerName, outerName);
691 G_testRunner.log('Channel name: ' + innerName);
692 };
693
694
695 /**
696 * Returns the configuration of the xpc.
697 * @return {?Object} The configuration of the xpc.
698 */
699 Driver.prototype.getInnerFrameConfiguration = function() {
700 return this.innerFrameCfg_;
701 };
702
703
704 /**
705 * Creates the peer iframe.
706 * @param {string=} opt_iframeId If present, the ID of the iframe to create,
707 * otherwise, generates an iframe ID.
708 * @param {boolean=} opt_oneSidedHandshake Whether a one sided handshake is
709 * specified.
710 * @param {number=} opt_innerProtocolVersion The native transport protocol
711 * version used in the inner iframe.
712 * @param {number=} opt_outerProtocolVersion The native transport protocol
713 * version used in the outer iframe.
714 * @param {boolean=} opt_randomChannelNames Whether the ends of the channel
715 * should be allowed to pick differing, random names.
716 * @return {!Array<string>} The id of the created iframe and the name of the
717 * created channel.
718 */
719 Driver.prototype.createPeerIframe = function(
720 opt_iframeId, opt_oneSidedHandshake, opt_innerProtocolVersion,
721 opt_outerProtocolVersion, opt_randomChannelNames) {
722 var expectedIframeId;
723
724 if (opt_iframeId) {
725 expectedIframeId = opt_iframeId = opt_iframeId + uniqueId++;
726 } else {
727 // Have createPeerIframe() generate an ID
728 stubs.set(goog.net.xpc, 'getRandomString', function(length) {
729 return '' + length;
730 });
731 expectedIframeId = 'xpcpeer4';
732 }
733 assertNull(
734 'element[id=' + expectedIframeId + '] exists',
735 goog.dom.getElement(expectedIframeId));
736
737 this.setConfiguration_(
738 opt_iframeId, opt_oneSidedHandshake, undefined /* opt_channelName */,
739 opt_innerProtocolVersion, opt_outerProtocolVersion,
740 opt_randomChannelNames);
741 var channelName = this.createChannel_();
742 this.initialOuterChannelName_ = channelName;
743 this.iframe_ = this.channel_.createPeerIframe(document.body);
744
745 assertEquals(expectedIframeId, this.iframe_.id);
746 };
747
748
749 /**
750 * Checks if the peer iframe has been created.
751 */
752 Driver.prototype.checkPeerIframe = function() {
753 assertNotNull(this.iframe_);
754 var peer = this.getInnerPeer_();
755 assertNotNull(peer);
756 assertNotNull(peer.document);
757 };
758
759
760 /**
761 * Starts the connection. The connection happens asynchronously.
762 */
763 Driver.prototype.connect = function(
764 fullLifeCycleTest, outerFrameReconnectSupported,
765 innerFrameMigrationSupported, reverse) {
766 if (!this.isTransportTestable_()) {
767 return;
768 }
769
770 // Set the criteria for the initial handshake portion of the test.
771 this.reinitializePromises_();
772
773 this.innerFrameResponseReceived_.promise.then(
774 this.checkChannelNames_, null, this);
775
776 if (fullLifeCycleTest) {
777 this.innerFrameResponseReceived_.promise.then(
778 goog.bind(
779 this.testReconnects_, this, outerFrameReconnectSupported,
780 innerFrameMigrationSupported));
781 }
782
783 this.continueConnect_(reverse);
784 return this.innerFrameResponseReceived_.promise;
785 };
786
787
788 Driver.prototype.continueConnect_ = function(reverse) {
789 // Wait until the peer is fully established. Establishment is sometimes very
790 // slow indeed, especially on virtual machines, so a fixed timeout is not
791 // suitable. This wait is required because we want to take precise control
792 // of the channel startup timing, and shouldn't be needed in production use,
793 // where the inner frame's channel is typically not started by a DOM call as
794 // it is here.
795 if (!this.getInnerPeer_() || !this.getInnerPeer_().instantiateChannel) {
796 window.setTimeout(goog.bind(this.continueConnect_, this, reverse), 100);
797 return;
798 }
799
800 var connectFromOuterFrame = goog.bind(
801 this.channel_.connect, this.channel_,
802 goog.bind(this.outerFrameConnected_, this));
803 var innerConfig = this.innerFrameCfg_;
804 var connectFromInnerFrame = goog.bind(
805 this.getInnerPeer_().instantiateChannel, this.getInnerPeer_(),
806 innerConfig);
807
808 // Take control of the timing and reverse of each frame's first SETUP call. If
809 // these happen to fire right on top of each other, that tends to mask
810 // problems that reliably occur when there is a short delay.
811 window.setTimeout(connectFromOuterFrame, reverse ? 1 : 10);
812 window.setTimeout(connectFromInnerFrame, reverse ? 10 : 1);
813 };
814
815
816 /**
817 * Called by the outer frame connection callback.
818 * @private
819 */
820 Driver.prototype.outerFrameConnected_ = function() {
821 var payload = this.outerFrameEchoPayload_ = goog.net.xpc.getRandomString(10);
822 this.channel_.send('echo', payload);
823 };
824
825
826 /**
827 * Called by the inner frame connection callback in inner_peer.html.
828 */
829 Driver.prototype.innerFrameConnected = function() {
830 var payload = this.innerFrameEchoPayload_ = goog.net.xpc.getRandomString(10);
831 this.getInnerPeer_().sendEcho(payload);
832 };
833
834
835 /**
836 * The handler function for incoming echo requests.
837 * @param {string} payload The message payload.
838 * @private
839 */
840 Driver.prototype.echoHandler_ = function(payload) {
841 assertTrue('outer frame should be connected', this.channel_.isConnected());
842 var peer = this.getInnerPeer_();
843 assertTrue('child should be connected', peer.isConnected());
844 this.channel_.send('response', payload);
845 };
846
847
848 /**
849 * The handler function for incoming echo responses.
850 * @param {string} payload The message payload.
851 * @private
852 */
853 Driver.prototype.responseHandler_ = function(payload) {
854 assertTrue('outer frame should be connected', this.channel_.isConnected());
855 var peer = this.getInnerPeer_();
856 assertTrue('child should be connected', peer.isConnected());
857 assertEquals(this.outerFrameEchoPayload_, payload);
858 this.outerFrameResponseReceived_.resolve(true);
859 };
860
861
862 /**
863 * The handler function for incoming echo replies. Called from inner_peer.html.
864 * @param {string} payload The message payload.
865 */
866 Driver.prototype.innerFrameGotResponse = function(payload) {
867 assertTrue('outer frame should be connected', this.channel_.isConnected());
868 var peer = this.getInnerPeer_();
869 assertTrue('child should be connected', peer.isConnected());
870 assertEquals(this.innerFrameEchoPayload_, payload);
871 this.innerFrameResponseReceived_.resolve(true);
872 };
873
874
875 /**
876 * The second phase of the standard test, where reconnections of both the inner
877 * and outer frames are performed.
878 * @param {boolean} outerFrameReconnectSupported Whether outer frame reconnects
879 * are supported, and should be tested.
880 * @private
881 */
882 Driver.prototype.testReconnects_ = function(
883 outerFrameReconnectSupported, innerFrameMigrationSupported) {
884 G_testRunner.log('Performing inner frame reconnect');
885 this.reinitializePromises_();
886 this.innerFrameResponseReceived_.promise.then(
887 this.checkChannelNames_, null, this);
888
889 if (outerFrameReconnectSupported) {
890 this.innerFrameResponseReceived_.promise.then(
891 goog.bind(
892 this.performOuterFrameReconnect_, this,
893 innerFrameMigrationSupported));
894 } else if (innerFrameMigrationSupported) {
895 this.innerFrameResponseReceived_.promise.then(
896 this.migrateInnerFrame_, null, this);
897 }
898
899 this.performInnerFrameReconnect_();
900 };
901
902
903 /**
904 * Initializes the promise resolvers and clears the echo payloads, ready for
905 * another sub-test.
906 * @private
907 */
908 Driver.prototype.reinitializePromises_ = function() {
909 this.innerFrameEchoPayload_ = null;
910 this.outerFrameEchoPayload_ = null;
911 this.innerFrameResponseReceived_.promise.cancel();
912 this.innerFrameResponseReceived_ = goog.Promise.withResolver();
913 this.outerFrameResponseReceived_.promise.cancel();
914 this.outerFrameResponseReceived_ = goog.Promise.withResolver();
915 };
916
917
918 /**
919 * Get the inner frame to reconnect, and repeat the echo test.
920 * @private
921 */
922 Driver.prototype.performInnerFrameReconnect_ = function() {
923 var peer = this.getInnerPeer_();
924 peer.instantiateChannel(this.innerFrameCfg_);
925 };
926
927
928 /**
929 * Get the outer frame to reconnect, and repeat the echo test.
930 * @private
931 */
932 Driver.prototype.performOuterFrameReconnect_ = function(
933 innerFrameMigrationSupported) {
934 G_testRunner.log('Closing channel');
935 this.channel_.close();
936
937 // If there is another channel still open, the native transport's global
938 // postMessage listener will still be active. This will mean that messages
939 // being sent to the now-closed channel will still be received and delivered,
940 // such as transport service traffic from its previous correspondent in the
941 // other frame. Ensure these messages don't cause exceptions.
942 try {
943 this.channel_.xpcDeliver(goog.net.xpc.TRANSPORT_SERVICE_, 'payload');
944 } catch (e) {
945 fail('Should not throw exception');
946 }
947
948 G_testRunner.log('Reconnecting outer frame');
949 this.reinitializePromises_();
950 this.innerFrameResponseReceived_.promise.then(
951 this.checkChannelNames_, null, this);
952 if (innerFrameMigrationSupported) {
953 this.outerFrameResponseReceived_.promise.then(
954 this.migrateInnerFrame_, null, this);
955 }
956 this.channel_.connect(goog.bind(this.outerFrameConnected_, this));
957 };
958
959
960 /**
961 * Migrate the inner frame to the alternate protocol version and reconnect it.
962 * @private
963 */
964 Driver.prototype.migrateInnerFrame_ = function() {
965 G_testRunner.log('Migrating inner frame');
966 this.reinitializePromises_();
967 var innerFrameProtoVersion =
968 this.innerFrameCfg_[goog.net.xpc.CfgFields
969 .NATIVE_TRANSPORT_PROTOCOL_VERSION];
970 this.innerFrameResponseReceived_.promise.then(
971 this.checkChannelNames_, null, this);
972 this.innerFrameCfg_[goog.net.xpc.CfgFields
973 .NATIVE_TRANSPORT_PROTOCOL_VERSION] =
974 innerFrameProtoVersion == 1 ? 2 : 1;
975 this.performInnerFrameReconnect_();
976 };
977
978
979 /**
980 * Determines if the transport type for the channel is testable.
981 * Some transports are misusing global state or making other
982 * assumptions that cause connections to fail.
983 * @return {boolean} Whether the transport is testable.
984 * @private
985 */
986 Driver.prototype.isTransportTestable_ = function() {
987 var testable = false;
988
989 var transportType = this.channel_.determineTransportType_();
990 switch (transportType) {
991 case goog.net.xpc.TransportTypes.IFRAME_RELAY:
992 case goog.net.xpc.TransportTypes.IFRAME_POLLING:
993 testable = canAccessSameDomainIframe;
994 break;
995 case goog.net.xpc.TransportTypes.NATIVE_MESSAGING:
996 case goog.net.xpc.TransportTypes.FLASH:
997 case goog.net.xpc.TransportTypes.DIRECT:
998 case goog.net.xpc.TransportTypes.NIX:
999 testable = true;
1000 break;
1001 }
1002
1003 return testable;
1004 };
1005
1006
1007 /**
1008 * Connect the outer channel but not the inner one. Wait a short time, then
1009 * dispose the outer channel and make sure it was torn down properly.
1010 */
1011 Driver.prototype.connectOuterAndDispose = function() {
1012 this.channel_.connect();
1013 return goog.Timer.promise(2000).then(this.disposeAndCheck_, null, this);
1014 };
1015
1016
1017 /**
1018 * Dispose the cross-page channel. Check that the transport was also
1019 * disposed, and allow to run briefly to make sure no timers which will cause
1020 * failures are still running.
1021 * @private
1022 */
1023 Driver.prototype.disposeAndCheck_ = function() {
1024 assertFalse(this.channel_.isConnected());
1025 var transport = this.channel_.transport_;
1026 this.channel_.dispose();
1027 assertNull(this.channel_.transport_);
1028 assertTrue(this.channel_.isDisposed());
1029 assertTrue(transport.isDisposed());
1030
1031 // Let any errors caused by erroneous retries happen.
1032 return goog.Timer.promise(2000);
1033 };