aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/net/xpc/crosspagechannel_test.html
blob: 0c77626c6a73595977b4149029a69e06bcc15e2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
<!DOCTYPE html>
<!--
-->
<html>
<!--
Copyright 2009 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>CrossPageChannel: End-to-End Test</title>
<script type="text/javascript" src="../../base.js"></script>
<script type="text/javascript">
  goog.require('goog.Disposable');
  goog.require('goog.Uri');
  goog.require('goog.async.Deferred');
  goog.require('goog.debug.Logger');
  goog.require('goog.dom');
  goog.require('goog.net.xpc.CrossPageChannel');
  goog.require('goog.object');
  goog.require('goog.testing.AsyncTestCase');
  goog.require('goog.testing.PropertyReplacer');
  goog.require('goog.testing.jsunit');
</script>
</head>
<body>
<script type="text/javascript">

// Set this to false when working on this test.  It needs to be true for
// automated testing, as some browsers (eg IE8) choke on the large numbers of
// iframes this test would otherwise leave active.
var CLEAN_UP_IFRAMES = true;

var IFRAME_LOAD_WAIT_MS = 1000;
var stubs = new goog.testing.PropertyReplacer();
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(
    document.title);
var uniqueId = 0;
var driver;
var canAccessSameDomainIframe = true;
var accessCheckIframes = [];

function setUpPage() {
  // This test is insanely slow on IE8 for some reason.
  asyncTestCase.stepTimeout = 20 * 1000;

  // Show debug log
  var debugDiv = goog.dom.getElement('debugDiv');
  var logger = goog.debug.Logger.getLogger('goog.net.xpc');
  logger.setLevel(goog.debug.Logger.Level.ALL);
  logger.addHandler(function(logRecord) {
    var msgElm = goog.dom.createDom('div');
    msgElm.innerHTML = logRecord.getMessage();
    goog.dom.appendChild(debugDiv, msgElm);
  });
  asyncTestCase.waitForAsync('Checking if we can access same domain iframes');
  checkSameDomainIframeAccess();
}


function setUp() {
  driver = new Driver();
}


function tearDown() {
  stubs.reset();
  driver.dispose();
}


function checkSameDomainIframeAccess() {
  accessCheckIframes.push(
      create1x1Iframe('nonexistant', 'testdata/i_am_non_existant.html'));
  window.setTimeout(function () {
    accessCheckIframes.push(
        create1x1Iframe('existant', 'testdata/access_checker.html'));
  }, 10);
}


function create1x1Iframe(iframeId, src) {
  var iframeAccessChecker = goog.dom.createElement('IFRAME');
  iframeAccessChecker.id = iframeAccessChecker.name = iframeId;
  iframeAccessChecker.style.width = iframeAccessChecker.style.height = '1px';
  iframeAccessChecker.src = src;
  document.body.insertBefore(iframeAccessChecker, document.body.firstChild);
  return iframeAccessChecker;
}


function sameDomainIframeAccessComplete(canAccess) {
  canAccessSameDomainIframe  = canAccess;
  for (var i = 0; i < accessCheckIframes.length; i++) {
    document.body.removeChild(accessCheckIframes[i]);
  }
  asyncTestCase.continueTesting();
}


function testCreateIframeSpecifyId() {
  driver.createPeerIframe('new_iframe');

  asyncTestCase.waitForAsync('iframe load');
  window.setTimeout(function() {
    driver.checkPeerIframe();
    asyncTestCase.continueTesting();
  }, IFRAME_LOAD_WAIT_MS);
}


function testCreateIframeRandomId() {
  driver.createPeerIframe();

  asyncTestCase.waitForAsync('iframe load');
  window.setTimeout(function() {
    driver.checkPeerIframe();
    asyncTestCase.continueTesting();
  }, IFRAME_LOAD_WAIT_MS);
}


// The following batch of tests:
// * Establishes a peer iframe
// * Connects an XPC channel between the frames
// * From the connection callback in each frame, sends an 'echo' request, and
//   expects a 'response' response.
// * Reconnects the inner frame, sends an 'echo', expects a 'response'.
// * Optionally, reconnects the outer frame, sends an 'echo', expects a
//   'response'.
// * Optionally, reconnects the inner frame, but first reconfigures it to the
//   alternate protocol version, simulating an inner frame navigation that
//   picks up a new/old version.
//
// Every valid combination of protocol versions is tested, with both single and
// double ended handshakes.  Two timing scenarios are tested per combination,
// which is what the 'reverse' parameter distinguishes.
//
// Where single sided handshake is in use, reconnection by the outer frame is
// not supported, and therefore is not tested.
//
// The only known issue migrating to V2 is that once two V2 peers have
// connected, replacing either peer with a V1 peer will not work.  Upgrading V1
// peers to v2 is supported, as is replacing the only v2 peer in a connection
// with a v1.


function testLifeCycle_v1_v1() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v1_v1_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function testLifeCycle_v1_v1_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v1_v1_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function testLifeCycle_v1_v2() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v1_v2_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function testLifeCycle_v1_v2_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v1_v2_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function testLifeCycle_v2_v1() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v2_v1_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function testLifeCycle_v2_v1_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v2_v1_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function testLifeCycle_v2_v2() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v2_v2_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function testLifeCycle_v2_v2_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testLifeCycle_v2_v2_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      true /* reverse */);
}


function checkLifeCycle(oneSidedHandshake, innerProtocolVersion,
    outerProtocolVersion, outerFrameReconnectSupported,
    innerFrameMigrationSupported, reverse) {
  driver.createPeerIframe('new_iframe', oneSidedHandshake,
      innerProtocolVersion, outerProtocolVersion);
  driver.connect(true /* fullLifeCycleTest */, outerFrameReconnectSupported,
      innerFrameMigrationSupported, reverse);
}


function testConnectMismatchedNames_v1_v1() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* reverse */);
}


function testConnectMismatchedNames_v1_v1_rev() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* reverse */);
}


function testConnectMismatchedNames_v1_v2() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* reverse */);
}


function testConnectMismatchedNames_v1_v2_rev() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* reverse */);
}


function testConnectMismatchedNames_v2_v1() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* reverse */);
}


function testConnectMismatchedNames_v2_v1_rev() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* reverse */);
}


function testConnectMismatchedNames_v2_v2() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* reverse */);
}


function testConnectMismatchedNames_v2_v2_rev() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* reverse */);
}


function checkConnectMismatchedNames(innerProtocolVersion,
    outerProtocolVersion, reverse) {
  driver.createPeerIframe('new_iframe', false /* oneSidedHandshake */, innerProtocolVersion,
      outerProtocolVersion, true /* opt_randomChannelNames */);
  driver.connect(false /* fullLifeCycleTest */,
      false /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      false /* reverse */);
}


function testEscapeServiceName() {
  var escape = goog.net.xpc.CrossPageChannel.prototype.escapeServiceName_;
  assertEquals('Shouldn\'t escape alphanumeric name',
               'fooBar123', escape('fooBar123'));
  assertEquals('Shouldn\'t escape most non-alphanumeric characters',
               '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',
               escape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));
  assertEquals('Should escape %, |, and :',
               'foo%3ABar%7C123%25', escape('foo:Bar|123%'));
  assertEquals('Should escape tp', '%25tp', escape('tp'));
  assertEquals('Should escape %tp', '%25%25tp', escape('%tp'));
  assertEquals('Should not escape stp', 'stp', escape('stp'));
  assertEquals('Should not escape s%tp', 's%25tp', escape('s%tp'));
}


function testSameDomainCheck_noMessageOrigin() {
  var channel = new goog.net.xpc.CrossPageChannel(goog.object.create(
      goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
  assertTrue(channel.isMessageOriginAcceptable_(undefined));
}


function testSameDomainCheck_noPeerHostname() {
  var channel = new goog.net.xpc.CrossPageChannel({});
  assertTrue(channel.isMessageOriginAcceptable_('http://foo.com'));
}


function testSameDomainCheck_unconfigured() {
  var channel = new goog.net.xpc.CrossPageChannel({});
  assertTrue(channel.isMessageOriginAcceptable_(undefined));
}


function testSameDomainCheck_originsMatch() {
  var channel = new goog.net.xpc.CrossPageChannel(goog.object.create(
      goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
  assertTrue(channel.isMessageOriginAcceptable_('http://foo.com'));
}


function testSameDomainCheck_originsMismatch() {
  var channel = new goog.net.xpc.CrossPageChannel(goog.object.create(
      goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
  assertFalse(channel.isMessageOriginAcceptable_('http://nasty.com'));
}


function testUnescapeServiceName() {
  var unescape = goog.net.xpc.CrossPageChannel.prototype.unescapeServiceName_;
  assertEquals('Shouldn\'t modify alphanumeric name',
               'fooBar123', unescape('fooBar123'));
  assertEquals('Shouldn\'t modify most non-alphanumeric characters',
               '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',
               unescape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));
  assertEquals('Should unescape URL-escapes',
               'foo:Bar|123%', unescape('foo%3ABar%7C123%25'));
  assertEquals('Should unescape tp', 'tp', unescape('%25tp'));
  assertEquals('Should unescape %tp', '%tp', unescape('%25%25tp'));
  assertEquals('Should not escape stp', 'stp', unescape('stp'));
  assertEquals('Should not escape s%tp', 's%tp', unescape('s%25tp'));
}


/**
 * Tests the case where the channel is disposed before it is fully connected.
 */
function testDisposeBeforeConnect() {
  asyncTestCase.waitForAsync('Checking disposal before connection.')
  driver.createPeerIframe('new_iframe', false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,
      true /* opt_randomChannelNames */);
  driver.connectOuterAndDispose();
}


/**
 * Driver for the tests for CrossPageChannel.
 *
 * @constructor
 * @extends {goog.Disposable}
 */
Driver = function() {
  goog.Disposable.call(this);

  /**
   * The peer iframe.
   * @type {!Element}
   * @private
   */
  this.iframe_ = null;

  /**
   * The channel to use.
   * @type {goog.net.xpc.CrossPageChannel}
   * @private
   */
  this.channel_ = null;

  /**
   * Outer frame configuration object.
   * @type {Object}
   * @private
   */
  this.outerFrameCfg_ = null;

  /**
   * The initial name of the outer channel.
   * @type {?string}
   * @private
   */
  this.initialOuterChannelName_ = null;

  /**
   * Inner frame configuration object.
   * @type {Object}
   * @private
   */
  this.innerFrameCfg_ = null;

  /**
   * The contents of the payload of the 'echo' request sent by the inner frame.
   * @type {?string}
   * @private
   */
  this.innerFrameEchoPayload_ = null;

  /**
   * The contents of the payload of the 'echo' request sent by the outer frame.
   * @type {?string}
   * @private
   */
  this.outerFrameEchoPayload_ = null;

  /**
   * A deferred which fires when the inner frame receives its echo response.
   * @type {goog.async.Deferred}
   * @private
   */
  this.innerFrameResponseReceived_ = new goog.async.Deferred();

  /**
   * A deferred which fires when the outer frame receives its echo response.
   * @type {goog.async.Deferred}
   * @private
   */
  this.outerFrameResponseReceived_ = new goog.async.Deferred();

};
goog.inherits(Driver, goog.Disposable);


/** @override */
Driver.prototype.disposeInternal = function() {
  // Required to make this test perform acceptably (and pass) on slow browsers,
  // esp IE8.
  if (CLEAN_UP_IFRAMES) {
    goog.dom.removeNode(this.iframe_);
    delete this.iframe_;
  }
  goog.dispose(this.channel_);
  this.innerFrameResponseReceived_.cancel();
  this.innerFrameResponseReceived_ = null;
  this.outerFrameResponseReceived_.cancel();
  this.outerFrameResponseReceived_ = null;
  goog.base(this, 'disposeInternal');
};


/**
 * Returns the child peer's window object.
 * @return {Window} Child peer's window.
 * @private
 */
Driver.prototype.getInnerPeer_ = function() {
  return this.iframe_.contentWindow;
};


/**
 * Sets up the configuration objects for the inner and outer frames.
 * @param {string=} opt_iframeId If present, the ID of the iframe to use,
 *     otherwise, tells the channel to generate an iframe ID.
 * @param {boolean=} opt_oneSidedHandshake Whether the one sided handshake
 *     config option should be set.
 * @param {string=} opt_channelName The name of the channel to use, or null
 *     to generate one.
 * @param {number=} opt_innerProtocolVersion The native transport protocol
 *     version used in the inner iframe.
 * @param {number=} opt_outerProtocolVersion The native transport protocol
 *     version used in the outer iframe.
 * @param {boolean=} randomChannelNames Whether the different ends of the
 *     channel should be allowed to pick differing, random names.
 * @return {string} The name of the created channel.
 * @private
 */
Driver.prototype.setConfiguration_ = function(opt_iframeId,
    opt_oneSidedHandshake, opt_channelName, opt_innerProtocolVersion,
    opt_outerProtocolVersion, opt_randomChannelNames) {
  var cfg = {};
  if (opt_iframeId) {
    cfg[goog.net.xpc.CfgFields.IFRAME_ID] = opt_iframeId;
  }
  cfg[goog.net.xpc.CfgFields.PEER_URI] = 'testdata/inner_peer.html';
  if (!opt_randomChannelNames) {
    var channelName = opt_channelName || 'test_channel' + uniqueId++;
    cfg[goog.net.xpc.CfgFields.CHANNEL_NAME] = channelName;
  }
  cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = 'does-not-exist.html';
  cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = 'does-not-exist.html';
  cfg[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE] = !!opt_oneSidedHandshake;
  cfg[goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =
      opt_outerProtocolVersion;
  function resolveUri(fieldName) {
    cfg[fieldName] =
        goog.Uri.resolve(window.location.href, cfg[fieldName]).toString();
  }
  resolveUri(goog.net.xpc.CfgFields.PEER_URI);
  resolveUri(goog.net.xpc.CfgFields.LOCAL_POLL_URI);
  resolveUri(goog.net.xpc.CfgFields.PEER_POLL_URI);
  this.outerFrameCfg_ = cfg;
  this.innerFrameCfg_ = goog.object.clone(cfg);
  this.innerFrameCfg_[
      goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =
      opt_innerProtocolVersion;
};


/**
 * Creates an outer frame channel object.
 * @private
 */
Driver.prototype.createChannel_ = function() {
  if (this.channel_) {
    this.channel_.dispose();
  }
  this.channel_ = new goog.net.xpc.CrossPageChannel(this.outerFrameCfg_);
  this.channel_.registerService('echo',
      goog.bind(this.echoHandler_, this));
  this.channel_.registerService('response',
      goog.bind(this.responseHandler_, this));

  return this.channel_.name;
};


/**
 * Checks the names of the inner and outer frames meet expectations.
 * @private
 */
Driver.prototype.checkChannelNames_ = function() {
  var outerName = this.channel_.name;
  var innerName = this.getInnerPeer_().channel.name;
  var configName = this.innerFrameCfg_[goog.net.xpc.CfgFields.CHANNEL_NAME]
      || null;

  // The outer channel never changes its name.
  assertEquals(this.initialOuterChannelName_, outerName);
  // The name should be as configured, if it was configured.
  if (configName) {
    assertEquals(configName, innerName);
  }
  // The names of both ends of the channel should match.
  assertEquals(innerName, outerName);
  G_testRunner.log('Channel name: ' + innerName);
};


/**
 * Returns the configuration of the xpc.
 * @return {?Object} The configuration of the xpc.
 */
Driver.prototype.getInnerFrameConfiguration = function() {
  return this.innerFrameCfg_;
};


/**
 * Creates the peer iframe.
 * @param {string=} opt_iframeId If present, the ID of the iframe to create,
 *     otherwise, generates an iframe ID.
 * @param {boolean=} opt_oneSidedHandshake Whether a one sided handshake is
 *     specified.
 * @param {number=} opt_innerProtocolVersion The native transport protocol
 *     version used in the inner iframe.
 * @param {number=} opt_outerProtocolVersion The native transport protocol
 *     version used in the outer iframe.
 * @param {boolean=} opt_randomChannelNames Whether the ends of the channel
 *     should be allowed to pick differing, random names.
 * @return {!Array.<string>} The id of the created iframe and the name of the
 *     created channel.
 */
Driver.prototype.createPeerIframe = function(opt_iframeId,
    opt_oneSidedHandshake, opt_innerProtocolVersion, opt_outerProtocolVersion,
    opt_randomChannelNames) {
  var expectedIframeId;

  if (opt_iframeId) {
    expectedIframeId = opt_iframeId = opt_iframeId + uniqueId++;
  } else {
    // Have createPeerIframe() generate an ID
    stubs.set(goog.net.xpc, 'getRandomString', function(length) {
      return '' + length;
    });
    expectedIframeId = 'xpcpeer4';
  }
  assertNull('element[id=' + expectedIframeId + '] exists',
      goog.dom.getElement(expectedIframeId));

  this.setConfiguration_(opt_iframeId, opt_oneSidedHandshake,
      undefined /* opt_channelName */, opt_innerProtocolVersion,
      opt_outerProtocolVersion, opt_randomChannelNames);
  var channelName = this.createChannel_();
  this.initialOuterChannelName_ = channelName;
  this.iframe_ = this.channel_.createPeerIframe(document.body);

  assertEquals(expectedIframeId, this.iframe_.id);
};


/**
 * Checks if the peer iframe has been created.
 */
Driver.prototype.checkPeerIframe = function() {
  assertNotNull(this.iframe_);
  var peer = this.getInnerPeer_();
  assertNotNull(peer);
  assertNotNull(peer.document);
};


/**
 * Starts the connection. The connection happens asynchronously.
 */
Driver.prototype.connect = function(fullLifeCycleTest,
    outerFrameReconnectSupported, innerFrameMigrationSupported, reverse) {
  if (!this.isTransportTestable_()) {
    asyncTestCase.continueTesting();
    return;
  }

  asyncTestCase.waitForAsync('parent and child connect');

  // Set the criteria for the initial handshake portion of the test.
  this.reinitializeDeferreds_();
  this.innerFrameResponseReceived_.awaitDeferred(
      this.outerFrameResponseReceived_);
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));

  if (fullLifeCycleTest) {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(this.testReconnects_, this,
            outerFrameReconnectSupported, innerFrameMigrationSupported));
  } else {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  }

  this.continueConnect_(reverse);
};


Driver.prototype.continueConnect_ = function(reverse) {
  // Wait until the peer is fully established.  Establishment is sometimes very
  // slow indeed, especially on virtual machines, so a fixed timeout is not
  // suitable.  This wait is required because we want to take precise control
  // of the channel startup timing, and shouldn't be needed in production use,
  // where the inner frame's channel is typically not started by a DOM call as
  // it is here.
  if (!this.getInnerPeer_() || !this.getInnerPeer_().instantiateChannel) {
    window.setTimeout(goog.bind(this.continueConnect_, this, reverse), 100);
    return;
  }

  var connectFromOuterFrame = goog.bind(this.channel_.connect, this.channel_,
      goog.bind(this.outerFrameConnected_, this));
  var innerConfig = this.innerFrameCfg_;
  var connectFromInnerFrame = goog.bind(this.getInnerPeer_().instantiateChannel,
    this.getInnerPeer_(), innerConfig);

  // Take control of the timing and reverse of each frame's first SETUP call.  If
  // these happen to fire right on top of each other, that tends to mask
  // problems that reliably occur when there is a short delay.
  window.setTimeout(connectFromOuterFrame, reverse ? 1 : 10);
  window.setTimeout(connectFromInnerFrame, reverse ? 10 : 1);
};


/**
 * Called by the outer frame connection callback.
 * @private
 */
Driver.prototype.outerFrameConnected_ = function() {
  var payload = this.outerFrameEchoPayload_ =
      goog.net.xpc.getRandomString(10);
  this.channel_.send('echo', payload);
};


/**
 * Called by the inner frame connection callback.
 */
Driver.prototype.innerFrameConnected = function() {
  var payload = this.innerFrameEchoPayload_ =
      goog.net.xpc.getRandomString(10);
  this.getInnerPeer_().sendEcho(payload);
};


/**
 * The handler function for incoming echo requests.
 * @param {string} payload The message payload.
 * @private
 */
Driver.prototype.echoHandler_ = function(payload) {
  assertTrue('outer frame should be connected', this.channel_.isConnected());
  var peer = this.getInnerPeer_();
  assertTrue('child should be connected', peer.isConnected());
  this.channel_.send('response', payload);
};


/**
 * The handler function for incoming echo responses.
 * @param {string} payload The message payload.
 * @private
 */
Driver.prototype.responseHandler_ = function(payload) {
  assertTrue('outer frame should be connected', this.channel_.isConnected());
  var peer = this.getInnerPeer_();
  assertTrue('child should be connected', peer.isConnected());
  assertEquals(this.outerFrameEchoPayload_, payload);
  this.outerFrameResponseReceived_.callback(true);
};


/**
 * The handler function for incoming echo replies.
 * @param {string} payload The message payload.
 * @private
 */
Driver.prototype.innerFrameGotResponse = function(payload) {
  assertTrue('outer frame should be connected', this.channel_.isConnected());
  var peer = this.getInnerPeer_();
  assertTrue('child should be connected', peer.isConnected());
  assertEquals(this.innerFrameEchoPayload_, payload);
  this.innerFrameResponseReceived_.callback(true);
};


/**
 * The second phase of the standard test, where reconnections of both the inner
 * and outer frames are performed.
 * @param {boolean} outerFrameReconnectSupported Whether outer frame reconnects
 *     are supported, and should be tested.
 * @private
 */
Driver.prototype.testReconnects_ = function(outerFrameReconnectSupported,
    innerFrameMigrationSupported) {
  G_testRunner.log('Performing inner frame reconnect');
  this.reinitializeDeferreds_();
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));

  if (outerFrameReconnectSupported) {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(this.performOuterFrameReconnect_, this,
            innerFrameMigrationSupported));
  } else if (innerFrameMigrationSupported) {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(this.migrateInnerFrame_, this));
  } else {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  }

  this.performInnerFrameReconnect_();
};


/**
 * Initializes the deferreds and clears the echo payloads, ready for another
 * sub-test.
 * @private
 */
Driver.prototype.reinitializeDeferreds_ = function() {
  this.innerFrameEchoPayload_ = null;
  this.outerFrameEchoPayload_ = null;
  this.innerFrameResponseReceived_.cancel();
  this.innerFrameResponseReceived_ = new goog.async.Deferred();
  this.outerFrameResponseReceived_.cancel();
  this.outerFrameResponseReceived_ = new goog.async.Deferred();
};


/**
 * Get the inner frame to reconnect, and repeat the echo test.
 * @private
 */
Driver.prototype.performInnerFrameReconnect_ = function() {
  var peer = this.getInnerPeer_();
  peer.instantiateChannel(this.innerFrameCfg_);
};


/**
 * Get the outer frame to reconnect, and repeat the echo test.
 * @private
 */
Driver.prototype.performOuterFrameReconnect_ = function(
    innerFrameMigrationSupported) {
  G_testRunner.log('Reconnecting outer frame');
  this.reinitializeDeferreds_();
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));
  if (innerFrameMigrationSupported) {
    this.outerFrameResponseReceived_.addCallback(
        goog.bind(this.migrateInnerFrame_, this));
  } else {
    this.outerFrameResponseReceived_.addCallback(
        goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  }
  this.createChannel_();
  this.channel_.connect(goog.bind(this.outerFrameConnected_, this));
};


/**
 * Migrate the inner frame to the alternate protocol version and reconnect it.
 * @private
 */
Driver.prototype.migrateInnerFrame_ = function() {
  G_testRunner.log('Migrating inner frame');
  this.reinitializeDeferreds_();
  var innerFrameProtoVersion = this.innerFrameCfg_[
      goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION];
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  this.innerFrameCfg_[
      goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =
          innerFrameProtoVersion == 1 ? 2 : 1;
  this.performInnerFrameReconnect_();
};


/**
 * Determines if the transport type for the channel is testable.
 * Some transports are misusing global state or making other
 * assumptions that cause connections to fail.
 * @return {boolean} Whether the transport is testable.
 * @private
 */
Driver.prototype.isTransportTestable_ = function() {
  var testable = false;

  var transportType = this.channel_.determineTransportType_();
  switch (transportType) {
    case goog.net.xpc.TransportTypes.IFRAME_RELAY:
    case goog.net.xpc.TransportTypes.IFRAME_POLLING:
      testable = canAccessSameDomainIframe;
      break;
    case goog.net.xpc.TransportTypes.NATIVE_MESSAGING:
    case goog.net.xpc.TransportTypes.FLASH:
    case goog.net.xpc.TransportTypes.NIX:
      testable = true;
      break;
  }

  return testable;
};


/**
 * Connect the outer channel but not the inner one.  Wait a short time, then
 * dispose the outer channel and make sure it was torn down properly.
 */
Driver.prototype.connectOuterAndDispose = function() {
  this.channel_.connect();
  window.setTimeout(goog.bind(this.disposeAndCheck_, this), 2000);
};


/**
 * Dispose the cross-page channel. Check that the transport was also
 * disposed, and allow to run briefly to make sure no timers which will cause
 * failures are still running.
 */
Driver.prototype.disposeAndCheck_ = function() {
  assertFalse(this.channel_.isConnected());
  var transport = this.channel_.transport_;
  this.channel_.dispose();
  assertNull(this.channel_.transport_);
  assertTrue(this.channel_.isDisposed());
  assertTrue(transport.isDisposed());

  // Let any errors caused by erroneous retries happen.
  window.setTimeout(goog.bind(asyncTestCase.continueTesting, asyncTestCase),
      2000);
};

</script>

<!-- Debug box. -->
<div style="position:absolute; float: right; top: 10px; right: 10px; width: 500px">
Debug [<a href="#" onclick="document.getElementById('debugDiv').innerHTML = '';">clear</a>]: <br/>
<div id="debugDiv" style="border: 1px #000000 solid; font-size:xx-small; background: #fff;"></div>
</div>

</body>
</html>