Debian Codegraph @

closure-library/closure/goog/labs/net/xhr_test.js

raw
1 // Copyright 2011 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.labs.net.xhrTest');
16 goog.setTestOnly('goog.labs.net.xhrTest');
17
18 goog.require('goog.Promise');
19 goog.require('goog.events');
20 goog.require('goog.events.EventType');
21 goog.require('goog.labs.net.xhr');
22 goog.require('goog.net.WrapperXmlHttpFactory');
23 goog.require('goog.net.XhrLike');
24 goog.require('goog.net.XmlHttp');
25 goog.require('goog.testing.MockClock');
26 goog.require('goog.testing.TestCase');
27 goog.require('goog.testing.jsunit');
28 goog.require('goog.userAgent');
29
30
31 /** Path to a small download target used for testing binary requests. */
32 var TEST_IMAGE = 'testdata/cleardot.gif';
33
34
35 /** The expected bytes of the test image. */
36 var TEST_IMAGE_BYTES = [
37 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80,
38 0xFF, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04,
39 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01,
40 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3B
41 ];
42
43 function setUpPage() {
44 goog.testing.TestCase.getActiveTestCase().promiseTimeout = 10000; // 10s
45 }
46
47 /**
48 * @param {number} status HTTP status code.
49 * @param {string=} opt_responseText
50 * @param {number=} opt_latency
51 * Milliseconds between sending a request and receiving the response.
52 * @return {!goog.net.XhrLike}
53 * The XHR stub that will be returned from the factory.
54 */
55 function stubXhrToReturn(status, opt_responseText, opt_latency) {
56 if (goog.isDefAndNotNull(opt_latency)) {
57 mockClock = new goog.testing.MockClock(true);
58 }
59
60 var stubXhr = {
61 sent: false,
62 aborted: false,
63 status: 0,
64 headers: {},
65 open: function(method, url, async) {
66 this.method = method;
67 this.url = url;
68 this.async = async;
69 },
70 setRequestHeader: function(key, value) { this.headers[key] = value; },
71 overrideMimeType: function(mimeType) { this.mimeType = mimeType; },
72 abort: function() {
73 this.aborted = true;
74 this.load(0);
75 },
76 send: function(data) {
77 this.data = data;
78 this.sent = true;
79
80 // Fulfill the send asynchronously, or possibly with the MockClock.
81 window.setTimeout(goog.bind(this.load, this, status), opt_latency || 0);
82 if (mockClock) {
83 mockClock.tick(opt_latency);
84 }
85 },
86 load: function(status) {
87 this.status = status;
88 if (goog.isDefAndNotNull(opt_responseText)) {
89 this.responseText = opt_responseText;
90 }
91 this.readyState = 4;
92 if (this.onreadystatechange) this.onreadystatechange();
93 }
94 };
95
96 stubXmlHttpWith(stubXhr);
97 return stubXhr;
98 }
99
100 /**
101 * @param {!Error} err Error to be thrown when sending the stub XHR.
102 */
103 function stubXhrToThrow(err) {
104 stubXmlHttpWith(buildThrowingStubXhr(err));
105 }
106
107 /**
108 * @param {!Error} err Error to be thrown when sending this stub XHR.
109 * @return {!goog.net.XhrLike}
110 * The XHR stub that will be returned from the factory.
111 */
112 function buildThrowingStubXhr(err) {
113 return {
114 sent: false,
115 aborted: false,
116 status: 0,
117 headers: {},
118 open: function(method, url, async) {
119 this.method = method;
120 this.url = url;
121 this.async = async;
122 },
123 setRequestHeader: function(key, value) { this.headers[key] = value; },
124 overrideMimeType: function(mimeType) { this.mimeType = mimeType; },
125 send: function(data) { throw err; }
126 };
127 }
128
129 /**
130 * Replace goog.net.XmlHttp with a function that returns a stub XHR.
131 * @param {!goog.net.XhrLike.OrNative} stubXhr
132 */
133 function stubXmlHttpWith(stubXhr) {
134 goog.net.XmlHttp = function() { return stubXhr; };
135 for (var x in originalXmlHttp) {
136 goog.net.XmlHttp[x] = originalXmlHttp[x];
137 }
138 }
139
140 var xhr = goog.labs.net.xhr;
141 var originalXmlHttp = goog.net.XmlHttp;
142 var mockClock;
143
144 function tearDown() {
145 if (mockClock) {
146 mockClock.dispose();
147 mockClock = null;
148 }
149 goog.net.XmlHttp = originalXmlHttp;
150 }
151
152
153 /**
154 * Tests whether the test was loaded from a file: protocol. Tests that use a
155 * real network request cannot be run from the local file system due to
156 * cross-origin restrictions, but will run if the tests are hosted on a server.
157 * A log message is added to the test case to warn users that the a test was
158 * skipped.
159 *
160 * @return {boolean} Whether the test is running on a local file system.
161 */
162 function isRunningLocally() {
163 if (window.location.protocol == 'file:') {
164 var testCase = goog.global['G_testRunner'].testCase;
165 testCase.saveMessage('Test skipped while running on local file system.');
166 return true;
167 }
168 return false;
169 }
170
171 function testSimpleRequest() {
172 if (isRunningLocally()) return;
173
174 return xhr.send('GET', 'testdata/xhr_test_text.data').then(function(xhr) {
175 assertEquals('Just some data.', xhr.responseText);
176 assertEquals(200, xhr.status);
177 });
178 }
179
180 function testGetText() {
181 if (isRunningLocally()) return;
182
183 return xhr.get('testdata/xhr_test_text.data').then(function(responseText) {
184 assertEquals('Just some data.', responseText);
185 });
186 }
187
188 function testGetTextWithJson() {
189 if (isRunningLocally()) return;
190
191 return xhr.get('testdata/xhr_test_json.data').then(function(responseText) {
192 assertEquals('while(1);\n{"stat":"ok","count":12345}\n', responseText);
193 });
194 }
195
196 function testPostText() {
197 if (isRunningLocally()) return;
198
199 return xhr.post('testdata/xhr_test_text.data', 'post-data')
200 .then(function(responseText) {
201 // No good way to test post-data gets transported.
202 assertEquals('Just some data.', responseText);
203 });
204 }
205
206 function testGetJson() {
207 if (isRunningLocally()) return;
208
209 return xhr.getJson('testdata/xhr_test_json.data', {xssiPrefix: 'while(1);\n'})
210 .then(function(responseObj) {
211 assertEquals('ok', responseObj['stat']);
212 assertEquals(12345, responseObj['count']);
213 });
214 }
215
216 function testGetBlob() {
217 if (isRunningLocally()) return;
218
219 // IE9 and earlier do not support blobs.
220 if (!('Blob' in goog.global)) {
221 var err = assertThrows(function() { xhr.getBlob(TEST_IMAGE); });
222 assertEquals(
223 'Assertion failed: getBlob is not supported in this browser.',
224 err.message);
225 return;
226 }
227
228 var options = {withCredentials: true};
229
230 return xhr.getBlob(TEST_IMAGE, options)
231 .then(function(blob) {
232 var reader = new FileReader();
233 return new goog.Promise(function(resolve, reject) {
234 goog.events.listenOnce(reader, goog.events.EventType.LOAD, resolve);
235 reader.readAsArrayBuffer(blob);
236 });
237 })
238 .then(function(e) {
239 assertElementsEquals(TEST_IMAGE_BYTES, new Uint8Array(e.target.result));
240 assertObjectEquals(
241 'input options should not have mutated.', {withCredentials: true},
242 options);
243 });
244 }
245
246 function testGetBytes() {
247 if (isRunningLocally()) return;
248
249 // IE8 requires a VBScript fallback to read the bytes from the response.
250 if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
251 var err = assertThrows(function() { xhr.getBytes(TEST_IMAGE); });
252 assertEquals(
253 'Assertion failed: getBytes is not supported in this browser.',
254 err.message);
255 return;
256 }
257
258 var options = {withCredentials: true};
259
260 return xhr.getBytes(TEST_IMAGE).then(function(bytes) {
261 assertElementsEquals(TEST_IMAGE_BYTES, bytes);
262 assertObjectEquals(
263 'input options should not have mutated.', {withCredentials: true},
264 options);
265 });
266 }
267
268 function testSerialRequests() {
269 if (isRunningLocally()) return;
270
271 return xhr.get('testdata/xhr_test_text.data')
272 .then(function(response) {
273 return xhr.getJson(
274 'testdata/xhr_test_json.data', {xssiPrefix: 'while(1);\n'});
275 })
276 .then(function(responseObj) {
277 // Data that comes through to callbacks should be from the 2nd request.
278 assertEquals('ok', responseObj['stat']);
279 assertEquals(12345, responseObj['count']);
280 });
281 }
282
283 function testBadUrlDetectedAsError() {
284 if (isRunningLocally()) return;
285
286 return xhr.getJson('unknown-file.dat')
287 .then(fail /* opt_onFulfilled */, function(err) {
288 assertTrue(
289 'Error should be an HTTP error', err instanceof xhr.HttpError);
290 assertEquals(404, err.status);
291 assertNotNull(err.xhr);
292 });
293 }
294
295 function testBadOriginTriggersOnErrorHandler() {
296 if (goog.userAgent.EDGE) return; // failing b/62677027
297
298 return xhr.get('http://www.google.com')
299 .then(
300 function() {
301 fail(
302 'XHR to http://www.google.com should\'ve failed due to ' +
303 'same-origin policy.');
304 } /* opt_onFulfilled */,
305 function(err) {
306 // In IE this will be a goog.labs.net.xhr.Error since it is thrown
307 // when calling xhr.open(), other browsers will raise an HttpError.
308 assertTrue(
309 'Error should be an xhr error', err instanceof xhr.Error);
310 assertNotNull(err.xhr);
311 });
312 }
313
314 //============================================================================
315 // The following tests use a stubbed out XMLHttpRequest.
316 //============================================================================
317
318 function testSendNoOptions() {
319 var called = false;
320 stubXhrToReturn(200);
321 assertFalse('Callback should not yet have been called', called);
322 return xhr.send('GET', 'test-url', null).then(function(stubXhr) {
323 called = true;
324 assertEquals('GET', stubXhr.method);
325 assertEquals('test-url', stubXhr.url);
326 });
327 }
328
329 function testSendPostSetsDefaultHeader() {
330 stubXhrToReturn(200);
331 return xhr.send('POST', 'test-url', null).then(function(stubXhr) {
332 assertEquals('POST', stubXhr.method);
333 assertEquals('test-url', stubXhr.url);
334 assertEquals(
335 'application/x-www-form-urlencoded;charset=utf-8',
336 stubXhr.headers['Content-Type']);
337 });
338 }
339
340 function testSendPostDoesntSetHeaderWithFormData() {
341 if (!goog.global['FormData']) {
342 return;
343 }
344 var formData = new goog.global['FormData']();
345 formData.append('name', 'value');
346
347 stubXhrToReturn(200);
348 return xhr.send('POST', 'test-url', formData).then(function(stubXhr) {
349 assertEquals('POST', stubXhr.method);
350 assertEquals('test-url', stubXhr.url);
351 assertEquals(undefined, stubXhr.headers['Content-Type']);
352 });
353 }
354
355 function testSendPostHeaders() {
356 stubXhrToReturn(200);
357 return xhr
358 .send(
359 'POST', 'test-url', null,
360 {headers: {'Content-Type': 'text/plain', 'X-Made-Up': 'FooBar'}})
361 .then(function(stubXhr) {
362 assertEquals('POST', stubXhr.method);
363 assertEquals('test-url', stubXhr.url);
364 assertEquals('text/plain', stubXhr.headers['Content-Type']);
365 assertEquals('FooBar', stubXhr.headers['X-Made-Up']);
366 });
367 }
368
369 function testSendPostHeadersWithFormData() {
370 if (!goog.global['FormData']) {
371 return;
372 }
373 var formData = new goog.global['FormData']();
374 formData.append('name', 'value');
375
376 stubXhrToReturn(200);
377 return xhr
378 .send(
379 'POST', 'test-url', formData,
380 {headers: {'Content-Type': 'text/plain', 'X-Made-Up': 'FooBar'}})
381 .then(function(stubXhr) {
382 assertEquals('POST', stubXhr.method);
383 assertEquals('test-url', stubXhr.url);
384 assertEquals('text/plain', stubXhr.headers['Content-Type']);
385 assertEquals('FooBar', stubXhr.headers['X-Made-Up']);
386 });
387 }
388
389 function testSendNullPostHeaders() {
390 stubXhrToReturn(200);
391 return xhr
392 .send('POST', 'test-url', null, {
393 headers:
394 {'Content-Type': null, 'X-Made-Up': 'FooBar', 'Y-Made-Up': null}
395 })
396 .then(function(stubXhr) {
397 assertEquals('POST', stubXhr.method);
398 assertEquals('test-url', stubXhr.url);
399 assertEquals(undefined, stubXhr.headers['Content-Type']);
400 assertEquals('FooBar', stubXhr.headers['X-Made-Up']);
401 assertEquals(undefined, stubXhr.headers['Y-Made-Up']);
402 });
403 }
404
405 function testSendNullPostHeadersWithFormData() {
406 if (!goog.global['FormData']) {
407 return;
408 }
409 var formData = new goog.global['FormData']();
410 formData.append('name', 'value');
411
412 stubXhrToReturn(200);
413 return xhr
414 .send('POST', 'test-url', formData, {
415 headers:
416 {'Content-Type': null, 'X-Made-Up': 'FooBar', 'Y-Made-Up': null}
417 })
418 .then(function(stubXhr) {
419 assertEquals('POST', stubXhr.method);
420 assertEquals('test-url', stubXhr.url);
421 assertEquals(undefined, stubXhr.headers['Content-Type']);
422 assertEquals('FooBar', stubXhr.headers['X-Made-Up']);
423 assertEquals(undefined, stubXhr.headers['Y-Made-Up']);
424 });
425 }
426
427 function testSendWithCredentials() {
428 stubXhrToReturn(200);
429 return xhr.send('POST', 'test-url', null, {withCredentials: true})
430 .then(function(stubXhr) {
431 assertTrue('XHR should have been sent', stubXhr.sent);
432 assertTrue(stubXhr.withCredentials);
433 });
434 }
435
436 function testSendWithMimeType() {
437 stubXhrToReturn(200);
438 return xhr.send('POST', 'test-url', null, {mimeType: 'text/plain'})
439 .then(function(stubXhr) {
440 assertTrue('XHR should have been sent', stubXhr.sent);
441 assertEquals('text/plain', stubXhr.mimeType);
442 });
443 }
444
445 function testSendWithHttpError() {
446 stubXhrToReturn(500);
447 return xhr.send('POST', 'test-url', null)
448 .then(fail /* opt_onResolved */, function(err) {
449 assertTrue(err instanceof xhr.HttpError);
450 assertTrue(err.xhr.sent);
451 assertEquals(500, err.status);
452 });
453 }
454
455 function testSendWithTimeoutNotHit() {
456 stubXhrToReturn(200, null /* opt_responseText */, 1400 /* opt_latency */);
457 return xhr.send('POST', 'test-url', null, {timeoutMs: 1500})
458 .then(function(stubXhr) {
459 assertTrue(mockClock.getTimeoutsMade() > 0);
460 assertTrue('XHR should have been sent', stubXhr.sent);
461 assertFalse('XHR should not have been aborted', stubXhr.aborted);
462 });
463 }
464
465 function testSendWithTimeoutHit() {
466 stubXhrToReturn(200, null /* opt_responseText */, 50 /* opt_latency */);
467 return xhr.send('POST', 'test-url', null, {timeoutMs: 50})
468 .then(fail /* opt_onResolved */, function(err) {
469 assertTrue('XHR should have been sent', err.xhr.sent);
470 assertTrue('XHR should have been aborted', err.xhr.aborted);
471 assertTrue(err instanceof xhr.TimeoutError);
472 });
473 }
474
475 function testCancelRequest() {
476 var request = stubXhrToReturn(200);
477 var promise =
478 xhr.send('GET', 'test-url')
479 .then(fail /* opt_onResolved */, function(error) {
480 assertTrue(error instanceof goog.Promise.CancellationError);
481 assertTrue('XHR should have been aborted', request.aborted);
482 return null; // Return a non-error value for the test runner.
483 });
484 promise.cancel();
485 return promise;
486 }
487
488 function testGetJson() {
489 stubXhrToReturn(200, '{"a": 1, "b": 2}');
490 xhr.getJson('test-url').then(function(responseObj) {
491 assertObjectEquals({a: 1, b: 2}, responseObj);
492 });
493 }
494
495 function testGetJsonWithXssiPrefix() {
496 stubXhrToReturn(200, 'while(1);\n{"a": 1, "b": 2}');
497 return xhr.getJson('test-url', {xssiPrefix: 'while(1);\n'})
498 .then(function(responseObj) {
499 assertObjectEquals({a: 1, b: 2}, responseObj);
500 });
501 }
502
503 function testSendWithClientException() {
504 stubXhrToThrow(new Error('CORS XHR with file:// schemas not allowed.'));
505 return xhr.send('POST', 'file://test-url', null)
506 .then(fail /* opt_onResolved */, function(err) {
507 assertFalse('XHR should not have been sent', err.xhr.sent);
508 assertTrue(err instanceof Error);
509 assertTrue(
510 /CORS XHR with file:\/\/ schemas not allowed./.test(err.message));
511 });
512 }
513
514 function testSendWithFactory() {
515 stubXhrToReturn(200);
516 var options = {
517 xmlHttpFactory: new goog.net.WrapperXmlHttpFactory(
518 goog.partial(buildThrowingStubXhr, new Error('Bad factory')),
519 goog.net.XmlHttp.getOptions)
520 };
521 return xhr.send('POST', 'file://test-url', null, options)
522 .then(fail /* opt_onResolved */, function(err) {
523 assertTrue(err instanceof Error);
524 });
525 }