Debian Codegraph @

closure-library/closure/goog/labs/net/webchannel/webchannelbase_test.js

raw
1 // Copyright 2013 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 /**
16 * @fileoverview Unit tests for goog.labs.net.webChannel.WebChannelBase.
17 * @suppress {accessControls} Private methods are accessed for test purposes.
18 *
19 */
20
21
22 goog.provide('goog.labs.net.webChannel.webChannelBaseTest');
23
24 goog.require('goog.Timer');
25 goog.require('goog.array');
26 goog.require('goog.dom');
27 goog.require('goog.functions');
28 goog.require('goog.json');
29 goog.require('goog.labs.net.webChannel.ChannelRequest');
30 goog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');
31 goog.require('goog.labs.net.webChannel.WebChannelBase');
32 goog.require('goog.labs.net.webChannel.WebChannelBaseTransport');
33 goog.require('goog.labs.net.webChannel.WebChannelDebug');
34 goog.require('goog.labs.net.webChannel.Wire');
35 goog.require('goog.labs.net.webChannel.netUtils');
36 goog.require('goog.labs.net.webChannel.requestStats');
37 goog.require('goog.labs.net.webChannel.requestStats.Stat');
38 goog.require('goog.structs.Map');
39 goog.require('goog.testing.MockClock');
40 goog.require('goog.testing.PropertyReplacer');
41 goog.require('goog.testing.asserts');
42 goog.require('goog.testing.jsunit');
43
44 goog.setTestOnly('goog.labs.net.webChannel.webChannelBaseTest');
45
46
47 /**
48 * Delay between a network failure and the next network request.
49 */
50 var RETRY_TIME = 1000;
51
52
53 /**
54 * A really long time - used to make sure no more timeouts will fire.
55 */
56 var ALL_DAY_MS = 1000 * 60 * 60 * 24;
57
58 var stubs = new goog.testing.PropertyReplacer();
59
60 var channel;
61 var deliveredMaps;
62 var handler;
63 var mockClock;
64 var gotError;
65 var numStatEvents;
66 var lastStatEvent;
67 var numTimingEvents;
68 var lastPostSize;
69 var lastPostRtt;
70 var lastPostRetryCount;
71
72 // Set to true to see the channel debug output in the browser window.
73 var debug = false;
74 // Debug message to print out when debug is true.
75 var debugMessage = '';
76
77 function debugToWindow(message) {
78 if (debug) {
79 debugMessage += message + '<br>';
80 goog.dom.getElement('debug').innerHTML = debugMessage;
81 }
82 }
83
84
85 /**
86 * Stubs goog.labs.net.webChannel.netUtils to always time out. It maintains the
87 * contract given by goog.labs.net.webChannel.netUtils.testNetwork, but always
88 * times out (calling callback(false)).
89 *
90 * stubNetUtils should be called in tests that require it before
91 * a call to testNetwork happens. It is reset at tearDown.
92 */
93 function stubNetUtils() {
94 stubs.set(
95 goog.labs.net.webChannel.netUtils, 'testLoadImage',
96 function(url, timeout, callback) {
97 goog.Timer.callOnce(goog.partial(callback, false), timeout);
98 });
99 }
100
101
102 /**
103 * Stubs goog.labs.net.webChannel.ForwardChannelRequestPool.isSpdyEnabled_
104 * to manage the max pool size for the forward channel.
105 *
106 * @param {boolean} spdyEnabled Whether SPDY is enabled for the test.
107 */
108 function stubSpdyCheck(spdyEnabled) {
109 stubs.set(
110 goog.labs.net.webChannel.ForwardChannelRequestPool, 'isSpdyEnabled_',
111 function() { return spdyEnabled; });
112 }
113
114
115
116 /**
117 * Mock ChannelRequest.
118 * @constructor
119 * @struct
120 * @final
121 */
122 var MockChannelRequest = function(
123 channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {
124 this.channel_ = channel;
125 this.channelDebug_ = channelDebug;
126 this.sessionId_ = opt_sessionId;
127 this.requestId_ = opt_requestId;
128 this.successful_ = true;
129 this.lastError_ = null;
130 this.lastStatusCode_ = 200;
131
132 // For debugging, keep track of whether this is a back or forward channel.
133 this.isBack = !!(opt_requestId == 'rpc');
134 this.isForward = !this.isBack;
135
136 this.pendingMessages_ = [];
137 };
138
139 MockChannelRequest.prototype.postData_ = null;
140
141 MockChannelRequest.prototype.requestStartTime_ = null;
142
143 /**
144 * @param {Object} extraHeaders The HTTP headers.
145 */
146 MockChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {};
147
148 /**
149 * @param {number} timeout The timeout in MS for when we fail the request.
150 */
151 MockChannelRequest.prototype.setTimeout = function(timeout) {};
152
153 /**
154 * @param {number} throttle The throttle in ms. A value of zero indicates
155 * no throttle.
156 */
157 MockChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {
158 };
159
160 /**
161 * @param {goog.Uri} uri The uri of the request.
162 * @param {?string} postData The data for the post body.
163 * @param {boolean} decodeChunks Whether to the result is expected to be
164 * encoded for chunking and thus requires decoding.
165 */
166 MockChannelRequest.prototype.xmlHttpPost = function(
167 uri, postData, decodeChunks) {
168 this.channelDebug_.debug(
169 '---> POST: ' + uri + ', ' + postData + ', ' + decodeChunks);
170 this.postData_ = postData;
171 this.requestStartTime_ = goog.now();
172 };
173
174 /**
175 * @param {goog.Uri} uri The uri of the request.
176 * @param {boolean} decodeChunks Whether to the result is expected to be
177 * encoded for chunking and thus requires decoding.
178 * @param {?string} hostPrefix The host prefix, if we might be using a
179 * secondary domain. Note that it should also be in the URL, adding this
180 * won't cause it to be added to the URL.
181 */
182 MockChannelRequest.prototype.xmlHttpGet = function(
183 uri, decodeChunks, hostPrefix) {
184 this.channelDebug_.debug(
185 '<--- GET: ' + uri + ', ' + decodeChunks + ', ' + hostPrefix);
186 this.requestStartTime_ = goog.now();
187 };
188
189 /**
190 * @param {goog.Uri} uri The uri to send a request to.
191 */
192 MockChannelRequest.prototype.sendCloseRequest = function(uri) {
193 this.requestStartTime_ = goog.now();
194 };
195
196 /**
197 * Cancel.
198 */
199 MockChannelRequest.prototype.cancel = function() {
200 this.successful_ = false;
201 };
202
203 /**
204 * @returns {boolean}
205 */
206 MockChannelRequest.prototype.getSuccess = function() {
207 return this.successful_;
208 };
209
210 /**
211 * @return {?ChannelRequest.Error} The last error.
212 */
213 MockChannelRequest.prototype.getLastError = function() {
214 return this.lastError_;
215 };
216
217 /**
218 * @return {number} The status code of the last request.
219 */
220 MockChannelRequest.prototype.getLastStatusCode = function() {
221 return this.lastStatusCode_;
222 };
223
224 /**
225 * @return {string|undefined} The session ID.
226 */
227 MockChannelRequest.prototype.getSessionId = function() {
228 return this.sessionId_;
229 };
230
231 /**
232 * @return {string|number|undefined} The request ID.
233 */
234 MockChannelRequest.prototype.getRequestId = function() {
235 return this.requestId_;
236 };
237
238 /**
239 * @return {?string} The POST data provided by the request initiator.
240 */
241 MockChannelRequest.prototype.getPostData = function() {
242 return this.postData_;
243 };
244
245 /**
246 * @return {?number} The time the request started, as returned by goog.now().
247 */
248 MockChannelRequest.prototype.getRequestStartTime = function() {
249 return this.requestStartTime_;
250 };
251
252 /**
253 * @return {?goog.net.XhrIo} Any XhrIo request created for this object.
254 */
255 MockChannelRequest.prototype.getXhr = function() {
256 return null;
257 };
258
259 /**
260 * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} messages
261 * The pending messages for this request.
262 */
263 MockChannelRequest.prototype.setPendingMessages = function(messages) {
264 this.pendingMessages_ = messages;
265 };
266
267 /**
268 * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending
269 * messages for this request.
270 */
271 MockChannelRequest.prototype.getPendingMessages = function() {
272 return this.pendingMessages_;
273 };
274
275
276 function shouldRunTests() {
277 return goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming();
278 }
279
280
281 /**
282 * @suppress {invalidCasts} The cast from MockChannelRequest to
283 * ChannelRequest is invalid and will not compile.
284 */
285 function setUpPage() {
286 // Use our MockChannelRequests instead of the real ones.
287 goog.labs.net.webChannel.ChannelRequest.createChannelRequest = function(
288 channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {
289 return /** @type {!goog.labs.net.webChannel.ChannelRequest} */ (
290 new MockChannelRequest(
291 channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId));
292 };
293
294 // Mock out the stat notification code.
295 goog.labs.net.webChannel.requestStats.notifyStatEvent = function(stat) {
296 numStatEvents++;
297 lastStatEvent = stat;
298 };
299
300 goog.labs.net.webChannel.requestStats.notifyTimingEvent = function(
301 size, rtt, retries) {
302 numTimingEvents++;
303 lastPostSize = size;
304 lastPostRtt = rtt;
305 lastPostRetryCount = retries;
306 };
307 }
308
309 function setUp() {
310 numTimingEvents = 0;
311 lastPostSize = null;
312 lastPostRtt = null;
313 lastPostRetryCount = null;
314
315 mockClock = new goog.testing.MockClock(true);
316 channel = new goog.labs.net.webChannel.WebChannelBase('1');
317 // restore channel-test for tests that rely on the channel-test state
318 channel.backgroundChannelTest_ = false;
319
320 gotError = false;
321
322 handler = new goog.labs.net.webChannel.WebChannelBase.Handler();
323 handler.channelOpened = function() {};
324 handler.channelError = function(channel, error) { gotError = true; };
325 handler.channelSuccess = function(channel, request) {
326 deliveredMaps = goog.array.clone(request.getPendingMessages());
327 };
328
329 /**
330 * @suppress {checkTypes} The callback function type declaration is skipped.
331 */
332 handler.channelClosed = function(
333 channel, opt_pendingMaps, opt_undeliveredMaps) {
334 // Mock out the handler, and let it set a formatted user readable string
335 // of the undelivered maps which we can use when verifying our assertions.
336 if (opt_pendingMaps) {
337 handler.pendingMapsString = formatArrayOfMaps(opt_pendingMaps);
338 }
339 if (opt_undeliveredMaps) {
340 handler.undeliveredMapsString = formatArrayOfMaps(opt_undeliveredMaps);
341 }
342 };
343 handler.channelHandleMultipleArrays = function() {};
344 handler.channelHandleArray = function() {};
345
346 channel.setHandler(handler);
347
348 // Provide a predictable retry time for testing.
349 channel.getRetryTime_ = function(retryCount) { return RETRY_TIME; };
350
351 var channelDebug = new goog.labs.net.webChannel.WebChannelDebug();
352 channelDebug.debug = function(message) { debugToWindow(message); };
353 channel.setChannelDebug(channelDebug);
354
355 numStatEvents = 0;
356 lastStatEvent = null;
357 }
358
359
360 function tearDown() {
361 mockClock.dispose();
362 stubs.reset();
363 debugToWindow('<hr>');
364 }
365
366
367 function getSingleForwardRequest() {
368 var pool = channel.forwardChannelRequestPool_;
369 if (!pool.hasPendingRequest()) {
370 return null;
371 }
372 return pool.request_ || pool.requestPool_.getValues()[0];
373 }
374
375
376 /**
377 * Helper function to return a formatted string representing an array of maps.
378 */
379 function formatArrayOfMaps(arrayOfMaps) {
380 var result = [];
381 for (var i = 0; i < arrayOfMaps.length; i++) {
382 var map = arrayOfMaps[i];
383 var keys = map.map.getKeys();
384 for (var j = 0; j < keys.length; j++) {
385 var tmp = keys[j] + ':' + map.map.get(keys[j]) +
386 (map.context ? ':' + map.context : '');
387 result.push(tmp);
388 }
389 }
390 return result.join(', ');
391 }
392
393
394 function testFormatArrayOfMaps() {
395 // This function is used in a non-trivial test, so let's verify that it works.
396 var map1 = new goog.structs.Map();
397 map1.set('k1', 'v1');
398 map1.set('k2', 'v2');
399 var map2 = new goog.structs.Map();
400 map2.set('k3', 'v3');
401 var map3 = new goog.structs.Map();
402 map3.set('k4', 'v4');
403 map3.set('k5', 'v5');
404 map3.set('k6', 'v6');
405
406 // One map.
407 var a = [];
408 a.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map1));
409 assertEquals('k1:v1, k2:v2', formatArrayOfMaps(a));
410
411 // Many maps.
412 var b = [];
413 b.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map1));
414 b.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map2));
415 b.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map3));
416 assertEquals(
417 'k1:v1, k2:v2, k3:v3, k4:v4, k5:v5, k6:v6', formatArrayOfMaps(b));
418
419 // One map with a context.
420 var c = [];
421 c.push(
422 new goog.labs.net.webChannel.Wire.QueuedMap(0, map1, new String('c1')));
423 assertEquals('k1:v1:c1, k2:v2:c1', formatArrayOfMaps(c));
424 }
425
426
427 /**
428 * @param {number=} opt_serverVersion
429 * @param {string=} opt_hostPrefix
430 * @param {string=} opt_uriPrefix
431 * @param {boolean=} opt_spdyEnabled
432 */
433 function connectForwardChannel(
434 opt_serverVersion, opt_hostPrefix, opt_uriPrefix, opt_spdyEnabled) {
435 stubSpdyCheck(!!opt_spdyEnabled);
436 var uriPrefix = opt_uriPrefix || '';
437 channel.connect(uriPrefix + '/test', uriPrefix + '/bind', null);
438 mockClock.tick(0);
439 completeTestConnection();
440 completeForwardChannel(opt_serverVersion, opt_hostPrefix);
441 }
442
443
444 /**
445 * @param {number=} opt_serverVersion
446 * @param {string=} opt_hostPrefix
447 * @param {string=} opt_uriPrefix
448 * @param {boolean=} opt_spdyEnabled
449 */
450 function connect(
451 opt_serverVersion, opt_hostPrefix, opt_uriPrefix, opt_spdyEnabled) {
452 connectForwardChannel(
453 opt_serverVersion, opt_hostPrefix, opt_uriPrefix, opt_spdyEnabled);
454 completeBackChannel();
455 }
456
457
458 function disconnect() {
459 channel.disconnect();
460 mockClock.tick(0);
461 }
462
463
464 function completeTestConnection() {
465 completeForwardTestConnection();
466 completeBackTestConnection();
467 assertEquals(
468 goog.labs.net.webChannel.WebChannelBase.State.OPENING,
469 channel.getState());
470 }
471
472
473 function completeForwardTestConnection() {
474 channel.connectionTest_.onRequestData(
475 channel.connectionTest_.request_, '["b"]');
476 channel.connectionTest_.onRequestComplete(channel.connectionTest_.request_);
477 mockClock.tick(0);
478 }
479
480
481 function completeBackTestConnection() {
482 channel.connectionTest_.onRequestData(
483 channel.connectionTest_.request_, '11111');
484 mockClock.tick(0);
485 }
486
487
488 /**
489 * @param {number=} opt_serverVersion
490 * @param {string=} opt_hostPrefix
491 */
492 function completeForwardChannel(opt_serverVersion, opt_hostPrefix) {
493 var responseData = '[[0,["c","1234567890ABCDEF",' +
494 (opt_hostPrefix ? '"' + opt_hostPrefix + '"' : 'null') +
495 (opt_serverVersion ? ',' + opt_serverVersion : '') + ']]]';
496 channel.onRequestData(getSingleForwardRequest(), responseData);
497 channel.onRequestComplete(getSingleForwardRequest());
498 mockClock.tick(0);
499 }
500
501
502 function completeBackChannel() {
503 channel.onRequestData(channel.backChannelRequest_, '[[1,["foo"]]]');
504 channel.onRequestComplete(channel.backChannelRequest_);
505 mockClock.tick(0);
506 }
507
508
509 function responseDone() {
510 channel.onRequestData(getSingleForwardRequest(), '[1,0,0]'); // mock data
511 channel.onRequestComplete(getSingleForwardRequest());
512 mockClock.tick(0);
513 }
514
515
516 /**
517 *
518 * @param {number=} opt_lastArrayIdSentFromServer
519 * @param {number=} opt_outstandingDataSize
520 */
521 function responseNoBackchannel(
522 opt_lastArrayIdSentFromServer, opt_outstandingDataSize) {
523 var responseData = goog.json.serialize(
524 [0, opt_lastArrayIdSentFromServer, opt_outstandingDataSize]);
525 channel.onRequestData(getSingleForwardRequest(), responseData);
526 channel.onRequestComplete(getSingleForwardRequest());
527 mockClock.tick(0);
528 }
529
530 function response(lastArrayIdSentFromServer, outstandingDataSize) {
531 var responseData =
532 goog.json.serialize([1, lastArrayIdSentFromServer, outstandingDataSize]);
533 channel.onRequestData(getSingleForwardRequest(), responseData);
534 channel.onRequestComplete(getSingleForwardRequest());
535 mockClock.tick(0);
536 }
537
538
539 function receive(data) {
540 channel.onRequestData(channel.backChannelRequest_, '[[1,' + data + ']]');
541 channel.onRequestComplete(channel.backChannelRequest_);
542 mockClock.tick(0);
543 }
544
545
546 function responseTimeout() {
547 getSingleForwardRequest().lastError_ =
548 goog.labs.net.webChannel.ChannelRequest.Error.TIMEOUT;
549 getSingleForwardRequest().successful_ = false;
550 channel.onRequestComplete(getSingleForwardRequest());
551 mockClock.tick(0);
552 }
553
554
555 /**
556 * @param {number=} opt_statusCode
557 */
558 function responseRequestFailed(opt_statusCode) {
559 getSingleForwardRequest().lastError_ =
560 goog.labs.net.webChannel.ChannelRequest.Error.STATUS;
561 getSingleForwardRequest().lastStatusCode_ = opt_statusCode || 503;
562 getSingleForwardRequest().successful_ = false;
563 channel.onRequestComplete(getSingleForwardRequest());
564 mockClock.tick(0);
565 }
566
567
568 function responseUnknownSessionId() {
569 getSingleForwardRequest().lastError_ =
570 goog.labs.net.webChannel.ChannelRequest.Error.UNKNOWN_SESSION_ID;
571 getSingleForwardRequest().successful_ = false;
572 channel.onRequestComplete(getSingleForwardRequest());
573 mockClock.tick(0);
574 }
575
576
577 /**
578 * @param {string} key
579 * @param {string} value
580 * @param {string=} opt_context
581 */
582 function sendMap(key, value, opt_context) {
583 var map = new goog.structs.Map();
584 map.set(key, value);
585 channel.sendMap(map, opt_context);
586 mockClock.tick(0);
587 }
588
589
590 function hasForwardChannel() {
591 return !!getSingleForwardRequest();
592 }
593
594
595 function hasBackChannel() {
596 return !!channel.backChannelRequest_;
597 }
598
599
600 function hasDeadBackChannelTimer() {
601 return goog.isDefAndNotNull(channel.deadBackChannelTimerId_);
602 }
603
604
605 function assertHasForwardChannel() {
606 assertTrue('Forward channel missing.', hasForwardChannel());
607 }
608
609
610 function assertHasBackChannel() {
611 assertTrue('Back channel missing.', hasBackChannel());
612 }
613
614
615 function testConnect() {
616 connect();
617 assertEquals(
618 goog.labs.net.webChannel.WebChannelBase.State.OPENED, channel.getState());
619 // If the server specifies no version, the client assumes the latest version
620 assertEquals(
621 goog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION,
622 channel.channelVersion_);
623 assertFalse(channel.isBuffered());
624 }
625
626 function testConnect_backChannelEstablished() {
627 connect();
628 assertHasBackChannel();
629 }
630
631 function testConnect_withServerHostPrefix() {
632 connect(undefined, 'serverHostPrefix');
633 assertEquals('serverHostPrefix', channel.hostPrefix_);
634 }
635
636 function testConnect_withClientHostPrefix() {
637 handler.correctHostPrefix = function(hostPrefix) {
638 return 'clientHostPrefix';
639 };
640 connect();
641 assertEquals('clientHostPrefix', channel.hostPrefix_);
642 }
643
644 function testConnect_overrideServerHostPrefix() {
645 handler.correctHostPrefix = function(hostPrefix) {
646 return 'clientHostPrefix';
647 };
648 connect(undefined, 'serverHostPrefix');
649 assertEquals('clientHostPrefix', channel.hostPrefix_);
650 }
651
652 function testConnect_withServerVersion() {
653 connect(8);
654 assertEquals(8, channel.channelVersion_);
655 }
656
657 function testConnect_notOkToMakeRequestForTest() {
658 handler.okToMakeRequest = goog.functions.constant(
659 goog.labs.net.webChannel.WebChannelBase.Error.NETWORK);
660 channel.connect('/test', '/bind', null);
661 mockClock.tick(0);
662 assertEquals(
663 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
664 }
665
666 function testConnect_notOkToMakeRequestForBind() {
667 channel.connect('/test', '/bind', null);
668 mockClock.tick(0);
669 completeTestConnection();
670 handler.okToMakeRequest = goog.functions.constant(
671 goog.labs.net.webChannel.WebChannelBase.Error.NETWORK);
672 completeForwardChannel();
673 assertEquals(
674 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
675 }
676
677
678 function testSendMap() {
679 connect();
680 sendMapOnce();
681 }
682
683
684 function testSendMapWithSpdyEnabled() {
685 connect(undefined, undefined, undefined, true);
686 sendMapOnce();
687 }
688
689
690 function sendMapOnce() {
691 assertEquals(1, numTimingEvents);
692 sendMap('foo', 'bar');
693 responseDone();
694 assertEquals(2, numTimingEvents);
695 assertEquals('foo:bar', formatArrayOfMaps(deliveredMaps));
696 }
697
698
699 function testSendMap_twice() {
700 connect();
701 sendMapTwice();
702 }
703
704
705 function testSendMap_twiceWithSpdyEnabled() {
706 connect(undefined, undefined, undefined, true);
707 sendMapTwice();
708 }
709
710
711 function sendMapTwice() {
712 sendMap('foo1', 'bar1');
713 responseDone();
714 assertEquals('foo1:bar1', formatArrayOfMaps(deliveredMaps));
715 sendMap('foo2', 'bar2');
716 responseDone();
717 assertEquals('foo2:bar2', formatArrayOfMaps(deliveredMaps));
718 }
719
720
721 function testSendMap_andReceive() {
722 connect();
723 sendMap('foo', 'bar');
724 responseDone();
725 receive('["the server reply"]');
726 }
727
728
729 function testReceive() {
730 connect();
731 receive('["message from server"]');
732 assertHasBackChannel();
733 }
734
735
736 function testReceive_twice() {
737 connect();
738 receive('["message one from server"]');
739 receive('["message two from server"]');
740 assertHasBackChannel();
741 }
742
743
744 function testReceive_andSendMap() {
745 connect();
746 receive('["the server reply"]');
747 sendMap('foo', 'bar');
748 responseDone();
749 assertHasBackChannel();
750 }
751
752
753 function testBackChannelRemainsEstablished_afterSingleSendMap() {
754 connect();
755
756 sendMap('foo', 'bar');
757 responseDone();
758 receive('["ack"]');
759
760 assertHasBackChannel();
761 }
762
763
764 function testBackChannelRemainsEstablished_afterDoubleSendMap() {
765 connect();
766
767 sendMap('foo1', 'bar1');
768 sendMap('foo2', 'bar2');
769 responseDone();
770 receive('["ack"]');
771
772 // This assertion would fail prior to CL 13302660.
773 assertHasBackChannel();
774 }
775
776
777 function testTimingEvent() {
778 connect();
779 assertEquals(1, numTimingEvents);
780 sendMap('', '');
781 assertEquals(1, numTimingEvents);
782 mockClock.tick(20);
783 var expSize = getSingleForwardRequest().getPostData().length;
784 responseDone();
785
786 assertEquals(2, numTimingEvents);
787 assertEquals(expSize, lastPostSize);
788 assertEquals(20, lastPostRtt);
789 assertEquals(0, lastPostRetryCount);
790
791 sendMap('abcdefg', '123456');
792 expSize = getSingleForwardRequest().getPostData().length;
793 responseTimeout();
794 assertEquals(2, numTimingEvents);
795 mockClock.tick(RETRY_TIME + 1);
796 responseDone();
797 assertEquals(3, numTimingEvents);
798 assertEquals(expSize, lastPostSize);
799 assertEquals(1, lastPostRetryCount);
800 assertEquals(1, lastPostRtt);
801 }
802
803
804 /**
805 * Make sure that dropping the forward channel retry limit below the retry count
806 * reports an error, and prevents another request from firing.
807 */
808 function testSetFailFastWhileWaitingForRetry() {
809 stubNetUtils();
810
811 connect();
812 setFailFastWhileWaitingForRetry();
813 }
814
815
816 function testSetFailFastWhileWaitingForRetryWithSpdyEnabled() {
817 stubNetUtils();
818
819 connect(undefined, undefined, undefined, true);
820 setFailFastWhileWaitingForRetry();
821 }
822
823
824 function setFailFastWhileWaitingForRetry() {
825 assertEquals(1, numTimingEvents);
826
827 sendMap('foo', 'bar');
828 assertNull(channel.forwardChannelTimerId_);
829 assertNotNull(getSingleForwardRequest());
830 assertEquals(0, channel.forwardChannelRetryCount_);
831
832 // Watchdog timeout.
833 responseTimeout();
834 assertNotNull(channel.forwardChannelTimerId_);
835 assertNull(getSingleForwardRequest());
836 assertEquals(1, channel.forwardChannelRetryCount_);
837
838 // Almost finish the between-retry timeout.
839 mockClock.tick(RETRY_TIME - 1);
840 assertNotNull(channel.forwardChannelTimerId_);
841 assertNull(getSingleForwardRequest());
842 assertEquals(1, channel.forwardChannelRetryCount_);
843
844 // Setting max retries to 0 should cancel the timer and raise an error.
845 channel.setFailFast(true);
846 assertNull(channel.forwardChannelTimerId_);
847 assertNull(getSingleForwardRequest());
848 assertEquals(1, channel.forwardChannelRetryCount_);
849
850 // We get the error immediately before starting to ping google.com.
851 assertTrue(gotError);
852 assertEquals(0, deliveredMaps.length);
853
854 // Simulate that timing out. We should not get another error.
855 gotError = false;
856 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
857 assertFalse('Extra error after network ping timed out.', gotError);
858
859 // Make sure no more retry timers are firing.
860 mockClock.tick(ALL_DAY_MS);
861 assertNull(channel.forwardChannelTimerId_);
862 assertNull(getSingleForwardRequest());
863 assertEquals(1, channel.forwardChannelRetryCount_);
864 assertEquals(1, numTimingEvents);
865 }
866
867
868 /**
869 * Make sure that dropping the forward channel retry limit below the retry count
870 * reports an error, and prevents another request from firing.
871 */
872 function testSetFailFastWhileRetryXhrIsInFlight() {
873 stubNetUtils();
874
875 connect();
876 setFailFastWhileRetryXhrIsInFlight();
877 }
878
879
880 function testSetFailFastWhileRetryXhrIsInFlightWithSpdyEnabled() {
881 stubNetUtils();
882
883 connect(undefined, undefined, undefined, true);
884 setFailFastWhileRetryXhrIsInFlight();
885 }
886
887
888 function setFailFastWhileRetryXhrIsInFlight() {
889 assertEquals(1, numTimingEvents);
890
891 sendMap('foo', 'bar');
892 assertNull(channel.forwardChannelTimerId_);
893 assertNotNull(getSingleForwardRequest());
894 assertEquals(0, channel.forwardChannelRetryCount_);
895
896 // Watchdog timeout.
897 responseTimeout();
898 assertNotNull(channel.forwardChannelTimerId_);
899 assertNull(getSingleForwardRequest());
900 assertEquals(1, channel.forwardChannelRetryCount_);
901
902 // Wait for the between-retry timeout.
903 mockClock.tick(RETRY_TIME);
904 assertNull(channel.forwardChannelTimerId_);
905 assertNotNull(getSingleForwardRequest());
906 assertEquals(1, channel.forwardChannelRetryCount_);
907
908 // Simulate a second watchdog timeout.
909 responseTimeout();
910 assertNotNull(channel.forwardChannelTimerId_);
911 assertNull(getSingleForwardRequest());
912 assertEquals(2, channel.forwardChannelRetryCount_);
913
914 // Wait for another between-retry timeout.
915 mockClock.tick(RETRY_TIME);
916 // Now the third req is in flight.
917 assertNull(channel.forwardChannelTimerId_);
918 assertNotNull(getSingleForwardRequest());
919 assertEquals(2, channel.forwardChannelRetryCount_);
920
921 // Set fail fast, killing the request
922 channel.setFailFast(true);
923 assertNull(channel.forwardChannelTimerId_);
924 assertNull(getSingleForwardRequest());
925 assertEquals(2, channel.forwardChannelRetryCount_);
926
927 // We get the error immediately before starting to ping google.com.
928 assertTrue(gotError);
929
930 // Simulate that timing out. We should not get another error.
931 gotError = false;
932 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
933 assertFalse('Extra error after network ping timed out.', gotError);
934
935 // Make sure no more retry timers are firing.
936 mockClock.tick(ALL_DAY_MS);
937 assertNull(channel.forwardChannelTimerId_);
938 assertNull(getSingleForwardRequest());
939 assertEquals(2, channel.forwardChannelRetryCount_);
940 assertEquals(1, numTimingEvents);
941 }
942
943
944 /**
945 * Makes sure that setting fail fast while not retrying doesn't cause a failure.
946 */
947 function testSetFailFastAtRetryCount() {
948 stubNetUtils();
949
950 connect();
951 assertEquals(1, numTimingEvents);
952
953 sendMap('foo', 'bar');
954 assertNull(channel.forwardChannelTimerId_);
955 assertNotNull(getSingleForwardRequest());
956 assertEquals(0, channel.forwardChannelRetryCount_);
957
958 // Set fail fast.
959 channel.setFailFast(true);
960 // Request should still be alive.
961 assertNull(channel.forwardChannelTimerId_);
962 assertNotNull(getSingleForwardRequest());
963 assertEquals(0, channel.forwardChannelRetryCount_);
964
965 // Watchdog timeout. Now we should get an error.
966 responseTimeout();
967 assertNull(channel.forwardChannelTimerId_);
968 assertNull(getSingleForwardRequest());
969 assertEquals(0, channel.forwardChannelRetryCount_);
970
971 // We get the error immediately before starting to ping google.com.
972 assertTrue(gotError);
973 // We get the error immediately before starting to ping google.com.
974 // Simulate that timing out. We should not get another error in addition
975 // to the initial failure.
976 gotError = false;
977 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
978 assertFalse('Extra error after network ping timed out.', gotError);
979
980 // Make sure no more retry timers are firing.
981 mockClock.tick(ALL_DAY_MS);
982 assertNull(channel.forwardChannelTimerId_);
983 assertNull(getSingleForwardRequest());
984 assertEquals(0, channel.forwardChannelRetryCount_);
985 assertEquals(1, numTimingEvents);
986 }
987
988
989 function testRequestFailedClosesChannel() {
990 stubNetUtils();
991
992 connect();
993 requestFailedClosesChannel();
994 }
995
996
997 function testRequestFailedClosesChannelWithSpdyEnabled() {
998 stubNetUtils();
999
1000 connect(undefined, undefined, undefined, true);
1001 requestFailedClosesChannel();
1002 }
1003
1004
1005 function requestFailedClosesChannel() {
1006 assertEquals(1, numTimingEvents);
1007
1008 sendMap('foo', 'bar');
1009 responseRequestFailed();
1010
1011 assertEquals(
1012 'Should be closed immediately after request failed.',
1013 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
1014
1015 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
1016
1017 assertEquals(
1018 'Should remain closed after the ping timeout.',
1019 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
1020 assertEquals(1, numTimingEvents);
1021 }
1022
1023
1024 function testStatEventReportedOnlyOnce() {
1025 stubNetUtils();
1026
1027 connect();
1028 sendMap('foo', 'bar');
1029 numStatEvents = 0;
1030 lastStatEvent = null;
1031 responseUnknownSessionId();
1032
1033 assertEquals(1, numStatEvents);
1034 assertEquals(
1035 goog.labs.net.webChannel.requestStats.Stat.ERROR_OTHER, lastStatEvent);
1036
1037 numStatEvents = 0;
1038 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
1039 assertEquals('No new stat events should be reported.', 0, numStatEvents);
1040 }
1041
1042
1043 function testStatEventReportedOnlyOnce_onNetworkUp() {
1044 stubNetUtils();
1045
1046 connect();
1047 sendMap('foo', 'bar');
1048 numStatEvents = 0;
1049 lastStatEvent = null;
1050 responseRequestFailed();
1051
1052 assertEquals(
1053 'No stat event should be reported before we know the reason.', 0,
1054 numStatEvents);
1055
1056 // Let the ping time out.
1057 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
1058
1059 // Assert we report the correct stat event.
1060 assertEquals(1, numStatEvents);
1061 assertEquals(
1062 goog.labs.net.webChannel.requestStats.Stat.ERROR_NETWORK, lastStatEvent);
1063 }
1064
1065
1066 function testStatEventReportedOnlyOnce_onNetworkDown() {
1067 stubNetUtils();
1068
1069 connect();
1070 sendMap('foo', 'bar');
1071 numStatEvents = 0;
1072 lastStatEvent = null;
1073 responseRequestFailed();
1074
1075 assertEquals(
1076 'No stat event should be reported before we know the reason.', 0,
1077 numStatEvents);
1078
1079 // Wait half the ping timeout period, and then fake the network being up.
1080 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT / 2);
1081 channel.testNetworkCallback_(true);
1082
1083 // Assert we report the correct stat event.
1084 assertEquals(1, numStatEvents);
1085 assertEquals(
1086 goog.labs.net.webChannel.requestStats.Stat.ERROR_OTHER, lastStatEvent);
1087 }
1088
1089
1090 function testOutgoingMapsAwaitsResponse() {
1091 connect();
1092 outgoingMapsAwaitsResponse();
1093 }
1094
1095
1096 function testOutgoingMapsAwaitsResponseWithSpdyEnabled() {
1097 connect(undefined, undefined, undefined, true);
1098 outgoingMapsAwaitsResponse();
1099 }
1100
1101
1102 function outgoingMapsAwaitsResponse() {
1103 assertEquals(0, channel.outgoingMaps_.length);
1104
1105 sendMap('foo1', 'bar');
1106 assertEquals(0, channel.outgoingMaps_.length);
1107 sendMap('foo2', 'bar');
1108 assertEquals(1, channel.outgoingMaps_.length);
1109 sendMap('foo3', 'bar');
1110 assertEquals(2, channel.outgoingMaps_.length);
1111 sendMap('foo4', 'bar');
1112 assertEquals(3, channel.outgoingMaps_.length);
1113
1114 responseDone();
1115 // Now the forward channel request is completed and a new started, so all maps
1116 // are dequeued from the array of outgoing maps into this new forward request.
1117 assertEquals(0, channel.outgoingMaps_.length);
1118 }
1119
1120
1121 function testUndeliveredMaps_doesNotNotifyWhenSuccessful() {
1122 /**
1123 * @suppress {checkTypes} The callback function type declaration is skipped.
1124 */
1125 handler.channelClosed = function(
1126 channel, opt_pendingMaps, opt_undeliveredMaps) {
1127 if (opt_pendingMaps || opt_undeliveredMaps) {
1128 fail('No pending or undelivered maps should be reported.');
1129 }
1130 };
1131
1132 connect();
1133 sendMap('foo1', 'bar1');
1134 responseDone();
1135 sendMap('foo2', 'bar2');
1136 responseDone();
1137 disconnect();
1138 }
1139
1140
1141 function testUndeliveredMaps_doesNotNotifyIfNothingWasSent() {
1142 /**
1143 * @suppress {checkTypes} The callback function type declaration is skipped.
1144 */
1145 handler.channelClosed = function(
1146 channel, opt_pendingMaps, opt_undeliveredMaps) {
1147 if (opt_pendingMaps || opt_undeliveredMaps) {
1148 fail('No pending or undelivered maps should be reported.');
1149 }
1150 };
1151
1152 connect();
1153 mockClock.tick(ALL_DAY_MS);
1154 disconnect();
1155 }
1156
1157
1158 function testUndeliveredMaps_clearsPendingMapsAfterNotifying() {
1159 connect();
1160 sendMap('foo1', 'bar1');
1161 sendMap('foo2', 'bar2');
1162 sendMap('foo3', 'bar3');
1163
1164 assertEquals(
1165 1, channel.forwardChannelRequestPool_.getPendingMessages().length);
1166 assertEquals(2, channel.outgoingMaps_.length);
1167
1168 disconnect();
1169
1170 assertEquals(
1171 0, channel.forwardChannelRequestPool_.getPendingMessages().length);
1172 assertEquals(0, channel.outgoingMaps_.length);
1173 }
1174
1175
1176 function testUndeliveredMaps_notifiesWithContext() {
1177 connect();
1178
1179 // First send two messages that succeed.
1180 sendMap('foo1', 'bar1', 'context1');
1181 responseDone();
1182 sendMap('foo2', 'bar2', 'context2');
1183 responseDone();
1184
1185 // Pretend the server hangs and no longer responds.
1186 sendMap('foo3', 'bar3', 'context3');
1187 sendMap('foo4', 'bar4', 'context4');
1188 sendMap('foo5', 'bar5', 'context5');
1189
1190 // Give up.
1191 disconnect();
1192
1193 // Assert that we are informed of any undelivered messages; both about
1194 // #3 that was sent but which we don't know if the server received, and
1195 // #4 and #5 which remain in the outgoing maps and have not yet been sent.
1196 assertEquals('foo3:bar3:context3', handler.pendingMapsString);
1197 assertEquals(
1198 'foo4:bar4:context4, foo5:bar5:context5', handler.undeliveredMapsString);
1199 }
1200
1201
1202 function testUndeliveredMaps_serviceUnavailable() {
1203 // Send a few maps, and let one fail.
1204 connect();
1205 sendMap('foo1', 'bar1');
1206 responseDone();
1207 sendMap('foo2', 'bar2');
1208 responseRequestFailed();
1209
1210 // After a failure, the channel should be closed.
1211 disconnect();
1212
1213 assertEquals('foo2:bar2', handler.pendingMapsString);
1214 assertEquals('', handler.undeliveredMapsString);
1215 }
1216
1217
1218 function testUndeliveredMaps_onPingTimeout() {
1219 stubNetUtils();
1220
1221 connect();
1222
1223 // Send a message.
1224 sendMap('foo1', 'bar1');
1225
1226 // Fake REQUEST_FAILED, triggering a ping to check the network.
1227 responseRequestFailed();
1228
1229 // Let the ping time out, unsuccessfully.
1230 mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
1231
1232 // Assert channel is closed.
1233 assertEquals(
1234 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
1235
1236 // Assert that the handler is notified about the undelivered messages.
1237 assertEquals('foo1:bar1', handler.pendingMapsString);
1238 assertEquals('', handler.undeliveredMapsString);
1239 }
1240
1241
1242 function testResponseNoBackchannelPostNotBeforeBackchannel() {
1243 connect(8);
1244 sendMap('foo1', 'bar1');
1245
1246 mockClock.tick(10);
1247 assertFalse(
1248 channel.backChannelRequest_.getRequestStartTime() <
1249 getSingleForwardRequest().getRequestStartTime());
1250 responseNoBackchannel();
1251 assertNotEquals(
1252 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
1253 lastStatEvent);
1254 }
1255
1256
1257 function testResponseNoBackchannel() {
1258 connect(8);
1259 sendMap('foo1', 'bar1');
1260 response(-1, 0);
1261 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE + 1);
1262 sendMap('foo2', 'bar2');
1263 assertTrue(
1264 channel.backChannelRequest_.getRequestStartTime() +
1265 goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE <
1266 getSingleForwardRequest().getRequestStartTime());
1267 responseNoBackchannel();
1268 assertEquals(
1269 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
1270 lastStatEvent);
1271 }
1272
1273
1274 function testResponseNoBackchannelWithNoBackchannel() {
1275 connect(8);
1276 sendMap('foo1', 'bar1');
1277 assertNull(channel.backChannelTimerId_);
1278 channel.backChannelRequest_.cancel();
1279 channel.backChannelRequest_ = null;
1280 responseNoBackchannel();
1281 assertEquals(
1282 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
1283 lastStatEvent);
1284 }
1285
1286
1287 function testResponseNoBackchannelWithStartTimer() {
1288 connect(8);
1289 sendMap('foo1', 'bar1');
1290
1291 channel.backChannelRequest_.cancel();
1292 channel.backChannelRequest_ = null;
1293 channel.backChannelTimerId_ = 123;
1294 responseNoBackchannel();
1295 assertNotEquals(
1296 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
1297 lastStatEvent);
1298 }
1299
1300
1301 function testResponseWithNoArraySent() {
1302 connect(8);
1303 sendMap('foo1', 'bar1');
1304
1305 // Send a response as if the server hasn't sent down an array.
1306 response(-1, 0);
1307
1308 // POST response with an array ID lower than our last received is OK.
1309 assertEquals(1, channel.lastArrayId_);
1310 assertEquals(-1, channel.lastPostResponseArrayId_);
1311 }
1312
1313
1314 function testResponseWithArraysMissing() {
1315 connect(8);
1316 sendMap('foo1', 'bar1');
1317 assertEquals(-1, channel.lastPostResponseArrayId_);
1318
1319 // Send a response as if the server has sent down seven arrays.
1320 response(7, 111);
1321
1322 assertEquals(1, channel.lastArrayId_);
1323 assertEquals(7, channel.lastPostResponseArrayId_);
1324 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
1325 assertEquals(
1326 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
1327 lastStatEvent);
1328 }
1329
1330
1331 function testMultipleResponsesWithArraysMissing() {
1332 connect(8);
1333 sendMap('foo1', 'bar1');
1334 assertEquals(-1, channel.lastPostResponseArrayId_);
1335
1336 // Send a response as if the server has sent down seven arrays.
1337 response(7, 111);
1338
1339 assertEquals(1, channel.lastArrayId_);
1340 assertEquals(7, channel.lastPostResponseArrayId_);
1341 sendMap('foo2', 'bar2');
1342 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
1343 response(8, 119);
1344 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
1345 // The original timer should still fire.
1346 assertEquals(
1347 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
1348 lastStatEvent);
1349 }
1350
1351
1352 function testOnlyRetryOnceBasedOnResponse() {
1353 connect(8);
1354 sendMap('foo1', 'bar1');
1355 assertEquals(-1, channel.lastPostResponseArrayId_);
1356
1357 // Send a response as if the server has sent down seven arrays.
1358 response(7, 111);
1359
1360 assertEquals(1, channel.lastArrayId_);
1361 assertEquals(7, channel.lastPostResponseArrayId_);
1362 assertTrue(hasDeadBackChannelTimer());
1363 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
1364 assertEquals(
1365 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
1366 lastStatEvent);
1367 assertEquals(1, channel.backChannelRetryCount_);
1368 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
1369 sendMap('foo2', 'bar2');
1370 assertFalse(hasDeadBackChannelTimer());
1371 response(8, 119);
1372 assertFalse(hasDeadBackChannelTimer());
1373 }
1374
1375
1376 function testResponseWithArraysMissingAndLiveChannel() {
1377 connect(8);
1378 sendMap('foo1', 'bar1');
1379 assertEquals(-1, channel.lastPostResponseArrayId_);
1380
1381 // Send a response as if the server has sent down seven arrays.
1382 response(7, 111);
1383
1384 assertEquals(1, channel.lastArrayId_);
1385 assertEquals(7, channel.lastPostResponseArrayId_);
1386 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
1387 assertTrue(hasDeadBackChannelTimer());
1388 receive('["ack"]');
1389 assertFalse(hasDeadBackChannelTimer());
1390 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
1391 assertNotEquals(
1392 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
1393 lastStatEvent);
1394 }
1395
1396
1397 function testResponseWithBigOutstandingData() {
1398 connect(8);
1399 sendMap('foo1', 'bar1');
1400 assertEquals(-1, channel.lastPostResponseArrayId_);
1401
1402 // Send a response as if the server has sent down seven arrays and 50kbytes.
1403 response(7, 50000);
1404
1405 assertEquals(1, channel.lastArrayId_);
1406 assertEquals(7, channel.lastPostResponseArrayId_);
1407 assertFalse(hasDeadBackChannelTimer());
1408 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
1409 assertNotEquals(
1410 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
1411 lastStatEvent);
1412 }
1413
1414
1415 function testResponseInBufferedMode() {
1416 connect(8);
1417 channel.useChunked_ = false;
1418 sendMap('foo1', 'bar1');
1419 assertEquals(-1, channel.lastPostResponseArrayId_);
1420 response(7, 111);
1421
1422 assertEquals(1, channel.lastArrayId_);
1423 assertEquals(7, channel.lastPostResponseArrayId_);
1424 assertFalse(hasDeadBackChannelTimer());
1425 mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
1426 assertNotEquals(
1427 goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
1428 lastStatEvent);
1429 }
1430
1431
1432 function testResponseWithGarbage() {
1433 connect(8);
1434 sendMap('foo1', 'bar1');
1435 channel.onRequestData(getSingleForwardRequest(), 'garbage');
1436 assertEquals(
1437 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
1438 }
1439
1440
1441 function testResponseWithGarbageInArray() {
1442 connect(8);
1443 sendMap('foo1', 'bar1');
1444 channel.onRequestData(getSingleForwardRequest(), '["garbage"]');
1445 assertEquals(
1446 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
1447 }
1448
1449
1450 function testResponseWithEvilData() {
1451 connect(8);
1452 sendMap('foo1', 'bar1');
1453 channel.onRequestData(
1454 getSingleForwardRequest(), 'foo=<script>evil()\<\/script>&' +
1455 'bar=<script>moreEvil()\<\/script>');
1456 assertEquals(
1457 goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
1458 }
1459
1460
1461 function testPathAbsolute() {
1462 connect(8, undefined, '/talkgadget');
1463 assertEquals(channel.backChannelUri_.getDomain(), window.location.hostname);
1464 assertEquals(
1465 channel.forwardChannelUri_.getDomain(), window.location.hostname);
1466 }
1467
1468
1469 function testPathRelative() {
1470 connect(8, undefined, 'talkgadget');
1471 assertEquals(channel.backChannelUri_.getDomain(), window.location.hostname);
1472 assertEquals(
1473 channel.forwardChannelUri_.getDomain(), window.location.hostname);
1474 }
1475
1476
1477 function testPathWithHost() {
1478 connect(8, undefined, 'https://example.com');
1479 assertEquals(channel.backChannelUri_.getScheme(), 'https');
1480 assertEquals(channel.backChannelUri_.getDomain(), 'example.com');
1481 assertEquals(channel.forwardChannelUri_.getScheme(), 'https');
1482 assertEquals(channel.forwardChannelUri_.getDomain(), 'example.com');
1483 }
1484
1485 function testCreateXhrIo() {
1486 var xhr = channel.createXhrIo(null);
1487 assertFalse(xhr.getWithCredentials());
1488
1489 assertThrows(
1490 'Error connection to different host without CORS',
1491 goog.bind(channel.createXhrIo, channel, 'some_host'));
1492
1493 channel.setSupportsCrossDomainXhrs(true);
1494
1495 xhr = channel.createXhrIo(null);
1496 assertTrue(xhr.getWithCredentials());
1497
1498 xhr = channel.createXhrIo('some_host');
1499 assertTrue(xhr.getWithCredentials());
1500 }
1501
1502 function testSpdyLimitOption() {
1503 var webChannelTransport =
1504 new goog.labs.net.webChannel.WebChannelBaseTransport();
1505 stubSpdyCheck(true);
1506 var webChannelDefault = webChannelTransport.createWebChannel('/foo');
1507 assertEquals(
1508 10, webChannelDefault.getRuntimeProperties().getConcurrentRequestLimit());
1509 assertTrue(webChannelDefault.getRuntimeProperties().isSpdyEnabled());
1510
1511 var options = {'concurrentRequestLimit': 100};
1512
1513 stubSpdyCheck(false);
1514 var webChannelDisabled =
1515 webChannelTransport.createWebChannel('/foo', options);
1516 assertEquals(
1517 1, webChannelDisabled.getRuntimeProperties().getConcurrentRequestLimit());
1518 assertFalse(webChannelDisabled.getRuntimeProperties().isSpdyEnabled());
1519
1520 stubSpdyCheck(true);
1521 var webChannelEnabled = webChannelTransport.createWebChannel('/foo', options);
1522 assertEquals(
1523 100,
1524 webChannelEnabled.getRuntimeProperties().getConcurrentRequestLimit());
1525 assertTrue(webChannelEnabled.getRuntimeProperties().isSpdyEnabled());
1526 }