aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/messaging/portchannel_test.html
blob: 845a488872d0dc2010ef5be0abebad20e62e01a6 (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
<!DOCTYPE html>
<html>
<!--
Copyright 2010 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>
<title>
  Closure Unit Tests - goog.messaging.PortChannel
</title>
<script src="../base.js"></script>
<script>
goog.require('goog.dom');
goog.require('goog.events.EventTarget');
goog.require('goog.json');
goog.require('goog.messaging.PortChannel');
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.async.MockControl');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.messaging.MockMessageEvent');
goog.require('goog.userAgent.product');
</script>
</head>
<body>
<div id="frame"></div>
<script>

var mockControl;
var asyncMockControl;
var mockPort;
var portChannel;

var workerChannel;
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
var timer;

// Use a relatively long timeout because workers can take a while to start up.
asyncTestCase.stepTimeout = 3 * 1000;

function setUpPage() {
  if (!('Worker' in goog.global)) {
    return;
  }
  workerChannel = new goog.messaging.PortChannel(
      new Worker('testdata/portchannel_worker.js'));
}

function tearDownPage() {
  goog.dispose(workerChannel);
}

function setUp() {
  timer = new goog.Timer(50);
  mockControl = new goog.testing.MockControl();
  asyncMockControl = new goog.testing.async.MockControl(mockControl);
  mockPort = new goog.events.EventTarget();
  mockPort.postMessage = mockControl.createFunctionMock('postMessage');
  portChannel = new goog.messaging.PortChannel(mockPort);
}

function tearDown() {
  goog.dispose(timer);
  portChannel.dispose();
  mockControl.$verifyAll();
}

function makeMessage(serviceName, payload) {
  var msg = {'serviceName': serviceName, 'payload': payload};
  msg[goog.messaging.PortChannel.FLAG] = true;
  if (goog.messaging.PortChannel.REQUIRES_SERIALIZATION_) {
    msg = goog.json.serialize(msg);
  }
  return msg;
}

function expectNoMessage() {
  portChannel.registerDefaultService(
    mockControl.createFunctionMock('expectNoMessage'));
}

function receiveMessage(serviceName, payload, opt_origin, opt_ports) {
  mockPort.dispatchEvent(
      goog.testing.messaging.MockMessageEvent.wrap(
          makeMessage(serviceName, payload),
          opt_origin || 'http://google.com',
          undefined, undefined, opt_ports));
}

function receiveNonChannelMessage(data) {
  if (goog.messaging.PortChannel.REQUIRES_SERIALIZATION_ &&
      !goog.isString(data)) {
    data = goog.json.serialize(data);
  }
  mockPort.dispatchEvent(
      goog.testing.messaging.MockMessageEvent.wrap(
          data, 'http://google.com'));
}

function testPostMessage() {
  mockPort.postMessage(makeMessage('foobar', 'This is a value'), []);
  mockControl.$replayAll();
  portChannel.send('foobar', 'This is a value');
}

function testPostMessageWithPorts() {
  if (!('MessageChannel' in goog.global)) {
    return;
  }
  var channel = new MessageChannel();
  var port1 = channel.port1;
  var port2 = channel.port2;
  mockPort.postMessage(makeMessage('foobar', {'val': [
    {'_port': {'type': 'real', 'index': 0}},
    {'_port': {'type': 'real', 'index': 1}}
  ]}), [port1, port2]);
  mockControl.$replayAll();
  portChannel.send('foobar', {'val': [port1, port2]});
}

function testReceiveMessage() {
  portChannel.registerService(
      'foobar', asyncMockControl.asyncAssertEquals(
          'testReceiveMessage', 'This is a string'));
  mockControl.$replayAll();
  receiveMessage('foobar', 'This is a string');
}

function testReceiveMessageWithPorts() {
  if (!('MessageChannel' in goog.global)) {
    return;
  }
  var channel = new MessageChannel();
  var port1 = channel.port1;
  var port2 = channel.port2;
  portChannel.registerService(
      'foobar', asyncMockControl.asyncAssertEquals(
          'testReceiveMessage', {'val': [port1, port2]}),
      true);
  mockControl.$replayAll();
  receiveMessage('foobar', {'val': [
    {'_port': {'type': 'real', 'index': 0}},
    {'_port': {'type': 'real', 'index': 1}}
  ]}, null, [port1, port2]);
}

function testReceiveNonChannelMessageWithStringBody() {
  expectNoMessage();
  mockControl.$replayAll();
  receiveNonChannelMessage('Foo bar');
}

function testReceiveNonChannelMessageWithArrayBody() {
  expectNoMessage();
  mockControl.$replayAll();
  receiveNonChannelMessage([5, 'Foo bar']);
}

function testReceiveNonChannelMessageWithNoFlag() {
  expectNoMessage();
  mockControl.$replayAll();
  receiveNonChannelMessage({
    serviceName: 'foobar',
    payload: 'this is a payload'
  });
}

function testReceiveNonChannelMessageWithFalseFlag() {
  expectNoMessage();
  mockControl.$replayAll();
  var body = {
    serviceName: 'foobar',
    payload: 'this is a payload'
  };
  body[goog.messaging.PortChannel.FLAG] = false;
  receiveNonChannelMessage(body);
}

// Integration tests

function testWorker() {
  if (!('Worker' in goog.global)) {
    return;
  }
  workerChannel.registerService('pong', function(msg) {
    assertObjectEquals({'val': 'fizzbang'}, msg);
    asyncTestCase.continueTesting();
  }, true);
  workerChannel.send('ping', {'val': 'fizzbang'});
  asyncTestCase.waitForAsync('worker response');
}

function testWorkerWithPorts() {
  if (!('Worker' in goog.global) || !('MessageChannel' in goog.global)) {
    return;
  }
  var messageChannel = new MessageChannel();
  workerChannel.registerService('pong', function(msg) {
    assertPortsEntangled(msg['port'], messageChannel.port2, function() {
      asyncTestCase.continueTesting();
    });
  }, true);
  workerChannel.send('ping', {'port': messageChannel.port1});
  asyncTestCase.waitForAsync('worker response');
}

function testPort() {
  if (!('Worker' in goog.global) || !('MessageChannel' in goog.global)) {
    return;
  }
  var messageChannel = new MessageChannel();
  workerChannel.send('addPort', messageChannel.port1);
  messageChannel.port2.start();
  var realPortChannel = new goog.messaging.PortChannel(messageChannel.port2);
  realPortChannel.registerService('pong', function(msg) {
    assertObjectEquals({'val': 'fizzbang'}, msg);

    messageChannel.port2.close();
    realPortChannel.dispose();
    asyncTestCase.continueTesting();
  }, true);
  realPortChannel.send('ping', {'val': 'fizzbang'});
  asyncTestCase.waitForAsync('port response');
}

function testPortIgnoresOrigin() {
  if (!('Worker' in goog.global) || !('MessageChannel' in goog.global)) {
    return;
  }
  var messageChannel = new MessageChannel();
  workerChannel.send('addPort', messageChannel.port1);
  messageChannel.port2.start();
  var realPortChannel = new goog.messaging.PortChannel(
      messageChannel.port2, 'http://somewhere-else.com');
  realPortChannel.registerService('pong', function(msg) {
    assertObjectEquals({'val': 'fizzbang'}, msg);

    messageChannel.port2.close();
    realPortChannel.dispose();
    asyncTestCase.continueTesting();
  }, true);
  realPortChannel.send('ping', {'val': 'fizzbang'});
  asyncTestCase.waitForAsync('port response');
}

function testWindow() {
  if (!('Worker' in goog.global) || !('MessageChannel' in goog.global)) {
    return;
  }

  // NOTE(nicksantos): This test is having problems in Safari4 on the
  // test farm, but no one can reproduce them locally. Just turn it off.
  if (goog.userAgent.product.SAFARI) {
    return;
  }

  withIframe(function() {
    var iframeChannel = goog.messaging.PortChannel.forEmbeddedWindow(
        window.frames['inner'], '*', timer);
    iframeChannel.registerService('pong', function(msg) {
      assertEquals('fizzbang', msg);

      goog.dispose(iframeChannel);
      asyncTestCase.continueTesting();
    });
    iframeChannel.send('ping', 'fizzbang');
    asyncTestCase.waitForAsync('window response');
  });
}

function testWindowCancelled() {
  if (!('Worker' in goog.global) || !('MessageChannel' in goog.global)) {
    return;
  }
  withIframe(function() {
    var iframeChannel = goog.messaging.PortChannel.forEmbeddedWindow(
        window.frames['inner'], '*', timer);
    iframeChannel.cancel();

    iframeChannel.registerService('pong', function(msg) {
      fail('no messages should be received due to cancellation');
      goog.dispose(iframeChannel);
      asyncTestCase.continueTesting();
    });

    iframeChannel.send('ping', 'fizzbang');
    asyncTestCase.waitForAsync('window response');

    // Leave plenty of time for the connection to be made if the test fails, but
    // stop the test before the asyncTestCase timeout is hit.
    setTimeout(goog.bind(asyncTestCase.continueTesting, asyncTestCase),
               asyncTestCase.stepTimeout / 3);
  });
}

function testWindowWontSendToWrongOrigin() {
  if (!('Worker' in goog.global) || !('MessageChannel' in goog.global)) {
    return;
  }
  withIframe(function() {
    var iframeChannel = goog.messaging.PortChannel.forEmbeddedWindow(
        window.frames['inner'], 'http://somewhere-else.com', timer);
    iframeChannel.registerService('pong', function(msg) {
      fail('Should not receive pong from unexpected origin');
      iframeChannel.dispose();
      asyncTestCase.continueTesting();
    });
    iframeChannel.send('ping', 'fizzbang');

    setTimeout(function() {
      iframeChannel.dispose();
      asyncTestCase.continueTesting();
    }, asyncTestCase.stepTimeout - 500);
    asyncTestCase.waitForAsync('window response');
  });
}

function testWindowWontReceiveFromWrongOrigin() {
  if (!('Worker' in goog.global) || !('MessageChannel' in goog.global)) {
    return;
  }
  withIframe(function() {
    var iframeChannel = goog.messaging.PortChannel.forEmbeddedWindow(
        window.frames['inner'], '*', timer);
    iframeChannel.registerService('pong', function(msg) {
      fail('Should not receive pong from unexpected origin');
      iframeChannel.dispose();
      asyncTestCase.continueTesting();
    });
    iframeChannel.send('ping', 'fizzbang');

    setTimeout(function() {
      iframeChannel.dispose();
      asyncTestCase.continueTesting();
    }, asyncTestCase.stepTimeout - 500);
    asyncTestCase.waitForAsync('window response');
  }, 'testdata/portchannel_wrong_origin_inner.html');
}

/**
 * Assert that two HTML5 MessagePorts are entangled by posting messages from
 * each to the other.
 *
 * @param {!MessagePort} port1
 * @param {!MessagePort} port2
 * @param {function()} callback Called when the assertion is finished.
 */
function assertPortsEntangled(port1, port2, callback) {
  port1.onmessage = function(e) {
    assertEquals('port 2 should send messages to port 1',
                 'port2 to port1', e.data);
    callback();
  };

  port2.onmessage = function(e) {
    assertEquals('port 1 should send messages to port 2',
                 'port1 to port2', e.data);
    port2.postMessage('port2 to port1');
    asyncTestCase.waitForAsync('port 1 receiving message');
  };

  port1.postMessage('port1 to port2');
  asyncTestCase.waitForAsync('port 2 receiving message');
}

function withIframe(callback, opt_url) {
  var frameDiv = goog.dom.$('frame');
  goog.dom.removeChildren(frameDiv);
  goog.dom.appendChild(frameDiv, goog.dom.createDom('iframe', {
    style: 'display: none',
    name: 'inner',
    id: 'inner',
    src: opt_url || 'testdata/portchannel_inner.html'
  }));

  asyncTestCase.waitForAsync('creating iframe');
  // We need to pass control back to the event loop to give the iframe a chance
  // to load.
  setTimeout(function() {
    asyncTestCase.continueTesting();
    callback();
  }, 0);
}

</script>
</body>
</html>