aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/labs/net/xhr_test.html
blob: 992a6462dec735dbcffa82d01cdb98ee827afbd1 (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
<!DOCTYPE html>
<html>
<!--
Copyright 2011 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>Closure Unit Tests - goog.labs.net.xhr</title>
<script src="../../base.js"></script>
<script>
  goog.require('goog.labs.net.xhr');
  goog.require('goog.result');
  goog.require('goog.string');
  goog.require('goog.testing.AsyncTestCase');
  goog.require('goog.testing.MockClock');
  goog.require('goog.testing.jsunit');
  goog.require('goog.userAgent');
</script>
</head>
<body>
<script>

  function setupStubXMLHttpRequest() {

    mockClock = new goog.testing.MockClock(true);

    var stubXhr = {
      sent: false,
      aborted: false,
      status: 0,
      headers: {},
      open: function(method, url, async) {
        this.method = method;
        this.url = url;
        this.async = async;
      },
      setRequestHeader: function(key, value) {
        this.headers[key] = value;
      },
      overrideMimeType: function(mimeType) {
        this.mimeType = mimeType;
      },
      abort: function() {
        this.aborted = true;
        this.load(0);
      },
      send: function(data) {
        this.data = data;
        this.sent = true;
      },
      load: function(status) {
        this.status = status;
        this.readyState = 4;
        if (this.onreadystatechange) this.onreadystatechange();
      }
    };

    goog.net.XmlHttp = function() {
      return stubXhr;
    };
    for (var x in originalXmlHttp) {
      goog.net.XmlHttp[x] = originalXmlHttp[x];
    }

    return stubXhr;
  }


  var xhr = goog.labs.net.xhr;
  var originalXmlHttp = goog.net.XmlHttp;
  var mockClock;

  var testCase = new goog.testing.AsyncTestCase(document.title);
  testCase.stepTimeout = 5 * 1000;

  testCase.setUpPage = function() {
    this.autoDiscoverTests();
  };

  testCase.tearDown = function() {
    if (mockClock) {
      mockClock.dispose();
      mockClock = null;
    }
    goog.net.XmlHttp = originalXmlHttp;
  };

  G_testRunner.initialize(testCase);

  // Many tests don't work on the local file system due to cross-origin
  // restrictions in Chrome without --allow-file-access-from-files.
  // They will run on the farm or on a Closure Test server.
  var shouldRunLocally = goog.userAgent.IE || goog.userAgent.GECKO ||
      goog.string.startsWith(document.location.href, 'file://');

  function testSimpleRequest() {
    if (shouldRunLocally) return;

    testCase.waitForAsync('simpleRequest');
    var result = xhr.send('GET', 'testdata/xhr_test_text.data');
    goog.result.waitOnSuccess(result,
        function(xhr) {
          assertEquals('Just some data.', xhr.responseText);
          assertEquals(200, xhr.status);
          testCase.continueTesting();
        });
    goog.result.waitOnError(result, fail);
  }

  function testGetText() {
    if (shouldRunLocally) return;

    testCase.waitForAsync('getText');
    var result = xhr.get('testdata/xhr_test_text.data');
    goog.result.waitOnSuccess(result, function(content) {
        assertEquals('Just some data.', content);
        testCase.continueTesting();
      });
    goog.result.waitOnError(result, fail);
  }

  function testGetTextWithJson() {
    if (shouldRunLocally) return;

    testCase.waitForAsync('getTextWithJson');
    var result = xhr.get('testdata/xhr_test_json.data');
    goog.result.waitOnSuccess(result, function(content) {
        assertEquals('while(1);\n{"stat":"ok","count":12345}\n', content);
        testCase.continueTesting();
      });
    goog.result.waitOnError(result, fail);
  }

  function testPostText() {
    if (shouldRunLocally) return;

    testCase.waitForAsync('postText');
    var result = xhr.post('testdata/xhr_test_text.data', 'post-data');
    goog.result.waitOnSuccess(result, function(content) {
        // No good way to test post-data gets transported.
        assertEquals('Just some data.', content);
        testCase.continueTesting();
      });
    goog.result.waitOnError(result, fail);
  }

  function testGetJson() {
    if (shouldRunLocally) return;

    testCase.waitForAsync('getJson');
    xhr.getJson('testdata/xhr_test_json.data', {xssiPrefix: 'while(1);\n'}).
        addCallback(function(content) {
          assertEquals('ok', content['stat']);
          assertEquals(12345, content['count']);
          testCase.continueTesting();
        }).
        addErrback(fail);
  }

  function testSerialRequests() {
    if (shouldRunLocally) return;

    var result = xhr.get('testdata/xhr_test_text.data');
    var chainedResult = goog.result.chain(result, function(result) {
          return xhr.getJson(
              'testdata/xhr_test_json.data', {xssiPrefix: 'while(1);\n'});
        });

    // Data that comes through to callbacks should be from the 2nd request.
    goog.result.waitOnSuccess(chainedResult, function(json) {
      assertEquals('ok', json['stat']);
      assertEquals(12345, json['count']);
      testCase.continueTesting();
    });
    goog.result.waitOnError(chainedResult, fail);
  }

  function testParallelRequest() {
    if (shouldRunLocally) return;

    var textData, jsonData;
    function loadText(response) {
      textData = response;
    }
    function loadJson(response) {
      jsonData = response;
    }

    var fetchTextResult = xhr.get('testdata/xhr_test_text.data');
    var textDataResult = goog.result.transform(fetchTextResult, loadText);

    var fetchJsonResult = xhr.getJson('testdata/xhr_test_json.data',
                                      {xssiPrefix: 'while(1);\n'});
    var jsonDataResult = goog.result.transform(fetchJsonResult, loadJson);

    var combinedResult = goog.result.combine(textDataResult,
                                                 jsonDataResult);

    goog.result.waitOnSuccess(combinedResult, function() {
      assertEquals('Just some data.', textData);
      assertEquals('ok', jsonData['stat']);
      testCase.continueTesting();
    });
    goog.result.waitOnError(combinedResult, fail);
  }

  function testBadUrlDetectedAsError() {
    if (shouldRunLocally) return;

    testCase.waitForAsync('badUrl');
    var result = xhr.getJson('unknown-file.dat');
    goog.result.waitOnSuccess(result, fail);
    goog.result.waitOnError(result, function(result) {
        var err = result.getError();
        assertTrue('Error should be an HTTP error',
            err instanceof xhr.HttpError);
        assertEquals(404, err.status);
        assertNotNull(err.xhr);
        testCase.continueTesting();
      });
  }

  function testBadOriginTriggersOnErrorHandler() {
    testCase.waitForAsync('badOrigin');
    var result = xhr.get('http://www.google.com');
    goog.result.waitOnSuccess(result, fail);
    goog.result.waitOnError(result, function(result) {
        var err = result.getError();
        // In IE this will be a goog.labs.net.xhr.Error since it is thrown
        //  when calling xhr.open(), other browsers will raise an HttpError.
        assertTrue('Error should be an xhr error',
            err instanceof xhr.Error);
        assertNotNull(err.xhr);
        testCase.continueTesting();
      });
  }

  function testAbortRequest() {
    if (shouldRunLocally) return;

    var err;
    var result = xhr.send('GET', 'test-url', null);
    goog.result.waitOnSuccess(result, fail);
    goog.result.waitOnError(result, function(result) {
          err = result.getError();
        });
    result.cancel();
    assertTrue(err instanceof goog.result.Result.CancelError);
  }

  //============================================================================
  // The following tests are synchronous and use a stubbed out XMLHttpRequest.
  //============================================================================

  function testSendNoOptions() {
    var stubXhr = setupStubXMLHttpRequest();
    var called = false;
    var result = xhr.send('GET', 'test-url', null);
    goog.result.waitOnSuccess(result, function(xhr) {
        called = true;
        assertEquals('Objects should be equal', xhr, stubXhr);
      });
    goog.result.waitOnError(result, fail);

    assertTrue('XHR should have been sent', stubXhr.sent);
    assertFalse('Callback should not yet have been called', called);

    stubXhr.load(200);

    assertTrue('Callback should have been called', called);

    assertEquals('GET', stubXhr.method);
    assertEquals('test-url', stubXhr.url);
  }

  function testSendPostSetsDefaultHeader() {
    var stubXhr = setupStubXMLHttpRequest();
    var result = xhr.send('POST', 'test-url', null);
    goog.result.waitOnError(result, fail);

    stubXhr.load(200);

    assertEquals('POST', stubXhr.method);
    assertEquals('test-url', stubXhr.url);
    assertEquals('application/x-www-form-urlencoded;charset=utf-8',
        stubXhr.headers['Content-Type']);
  }

  function testSendPostHeaders() {
    var stubXhr = setupStubXMLHttpRequest();
    var result = xhr.send('POST', 'test-url', null, {
      headers: {'Content-Type': 'text/plain', 'X-Made-Up': 'FooBar'}
      });
    goog.result.waitOnError(result, fail);

    stubXhr.load(200);

    assertEquals('POST', stubXhr.method);
    assertEquals('test-url', stubXhr.url);
    assertEquals('text/plain', stubXhr.headers['Content-Type']);
    assertEquals('FooBar', stubXhr.headers['X-Made-Up']);
  }

  function testSendWithCredentials() {
    var stubXhr = setupStubXMLHttpRequest();
    var result = xhr.send('POST', 'test-url', null, {withCredentials: true});
    goog.result.waitOnError(result, fail);
    stubXhr.load(200);
    assertTrue('XHR should have been sent', stubXhr.sent);
    assertTrue(stubXhr.withCredentials);
  }

  function testSendWithMimeType() {
    var stubXhr = setupStubXMLHttpRequest();
    var result = xhr.send('POST', 'test-url', null, {mimeType: 'text/plain'});
    goog.result.waitOnError(result, fail);

    stubXhr.load(200);
    assertTrue('XHR should have been sent', stubXhr.sent);
    assertEquals('text/plain', stubXhr.mimeType);
  }

  function testSendWithHttpError() {
    var stubXhr = setupStubXMLHttpRequest();
    var err;
    var result = xhr.send('POST', 'test-url', null);
    goog.result.waitOnSuccess(result, fail);
    goog.result.waitOnError(result, function(result) {
        err = result.getError();
      });

    stubXhr.load(500);

    assertTrue('XHR should have been sent', stubXhr.sent);
    assertTrue(err instanceof xhr.HttpError);
    assertEquals(500, err.status);
  }

  function testSendWithTimeoutNotHit() {
    // TODO(user): This test fails in safari if it is run as part of a batch
    // but passes when run on its own.  Something strange is going on to do
    // with the references to window.clearTimeout inside onreadystatechange and
    // the mockclock overrides.
    if (goog.userAgent.SAFARI) return;

    var stubXhr = setupStubXMLHttpRequest();
    var err;
    var result = xhr.send('POST', 'test-url', null, {timeoutMs: 1500});
    goog.result.waitOnError(result, fail);
    assertTrue(mockClock.getTimeoutsMade() > 0);
    mockClock.tick(1400);
    stubXhr.load(200);
    mockClock.tick(200);
    assertTrue('XHR should have been sent', stubXhr.sent);
    assertFalse('XHR should not have been aborted', stubXhr.aborted);
  }

  function testSendWithTimeoutHit() {
    var stubXhr = setupStubXMLHttpRequest();
    var err;
    var result = xhr.send('POST', 'test-url', null, {timeoutMs: 50});
    goog.result.waitOnSuccess(result, fail);
    goog.result.waitOnError(result, function(res) { err = res.getError(); });
    assertTrue(mockClock.getTimeoutsMade() > 0);
    mockClock.tick(50);
    assertTrue('XHR should have been sent', stubXhr.sent);
    assertTrue('XHR should have been aborted', stubXhr.aborted);
    assertTrue(err instanceof xhr.TimeoutError);
  }

  function testSendWithTimeoutWithoutDeferreds() {
    var stubXhr = setupStubXMLHttpRequest();
    var err;
    xhr.makeRequest('POST', 'test-url', null, {timeoutMs: 50}, fail,
        function(e) { err = e; });
    assertTrue(mockClock.getTimeoutsMade() > 0);
    mockClock.tick(50);
    assertTrue('XHR should have been sent', stubXhr.sent);
    assertTrue('XHR should have been aborted', stubXhr.aborted);
    assertTrue(err instanceof xhr.TimeoutError);
  }

  function testCancelRequest() {
    var stubXhr = setupStubXMLHttpRequest();
    var err;
    var result = xhr.send('GET', 'test-url', null, {timeoutMs: 50});
    goog.result.waitOnSuccess(result, fail);
    goog.result.waitOnError(result, function(result) {
        err = result.getError();
      });
    result.cancel();
    stubXhr.load(0);  // Call load anyway, shoudn't make a difference.
    mockClock.tick(100);  // Timeout should never be called.

    assertTrue('XHR should have been sent', stubXhr.sent);
    assertTrue('XHR should have been aborted', stubXhr.aborted);
    assertTrue(err instanceof goog.result.Result.CancelError);
  }

  function testGetJson() {
    var stubXhr = setupStubXMLHttpRequest();
    var responseData;
    var result = xhr.getJson('test-url');
    goog.result.waitOnSuccess(result, function(data) {
        responseData = data;
      });
    goog.result.waitOnError(result, fail);

    stubXhr.responseText = '{"a": 1, "b": 2}';
    stubXhr.load(200);

    assertObjectEquals({a: 1, b: 2}, responseData);
  }

  function testGetJsonWithXssiPrefix() {
    var stubXhr = setupStubXMLHttpRequest();
    var responseData;
    var result = xhr.getJson('test-url', {xssiPrefix: 'while(1);\n'});
    goog.result.waitOnSuccess(result, function(data) {
        responseData = data;
      });
    goog.result.waitOnError(result, fail);

    stubXhr.responseText = 'while(1);\n{"a": 1, "b": 2}';
    stubXhr.load(200);

    assertObjectEquals({a: 1, b: 2}, responseData);
  }

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