summaryrefslogtreecommitdiff
path: root/misc/openlayers/tests/Request.html
blob: cd679c699d92d20f50bf568a3924f025f45cee04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
<html>
<head>
    <script src="OLLoader.js"></script>
    <script type="text/javascript">
    function setup() {
        window._xhr = OpenLayers.Request.XMLHttpRequest;
        var anon = new Function();
        OpenLayers.Request.XMLHttpRequest = function() {};
        OpenLayers.Request.XMLHttpRequest.prototype = {
            open: anon,
            setRequestHeader: anon,
            send: anon
        };
        OpenLayers.Request.XMLHttpRequest.DONE = 4;
    }
    function teardown() {
        OpenLayers.Request.XMLHttpRequest = window._xhr;
    }

    function test_defaultHeaders(t) {
        setup();
        t.plan(2);
        var config = {
            headers: {
                x: 'y'
            }
        };
        OpenLayers.Request.DEFAULT_CONFIG.headers = {
            foo: 'bar'
        };
        var proto = OpenLayers.Request.XMLHttpRequest.prototype;
        var issue = OpenLayers.Function.bind(OpenLayers.Request.issue,
                                             OpenLayers.Request);

        var headers = {};
        var _setRequestHeader = proto.setRequestHeader;
        proto.setRequestHeader = function(key, value) {
            headers[key] = value;
        };
        request = issue(config);
        t.eq(headers.foo, 'bar', "Header from DEFAULT_CONFIG set correctly");
        t.eq(headers.x, 'y', "Header from config set correctly");
        proto.setRequestHeader = _setRequestHeader;
        OpenLayers.Request.DEFAULT_CONFIG.headers = {};
        teardown();
    }
 
    function test_issue(t) {
        setup();

        t.plan(25);
        var request, config;
        var proto = OpenLayers.Request.XMLHttpRequest.prototype;
        var issue = OpenLayers.Function.bind(OpenLayers.Request.issue,
                                             OpenLayers.Request);

        // test that issue returns a new XMLHttpRequest - 1 test
        request = issue();
        t.ok(request instanceof OpenLayers.Request.XMLHttpRequest,
             "returns an XMLHttpRequest instance");
        
        // test that issue calls xhr.open with correct args from config - 5 tests
        var _open = proto.open;
        config = {
            method: "foo",
            url: "http://nowhere",
            async: "bar",
            user: "uncle",
            password: "sam"
        };
        proto.open = function(method, url, async, user, password) {
            t.eq(method, config.method, "open called with correct method");
            t.eq(url, config.url, "open called with correct url");
            t.eq(async, config.async, "open called with correct async");
            t.eq(user, config.user, "open called with correct user");
            t.eq(password, config.password, "open called with correct password");
        };
        request = issue(config);
        
        // test that params are serialized as query string - 1 test
        config = {
            method: "GET",
            url: "http://example.com/",
            params: {"foo": "bar"}
        };
        proto.open = function(method, url, async, user, password) {
            t.eq(url, config.url + "?foo=bar", "params serialized as query string");
        };
        request = issue(config);
        
        // test that empty params object doesn't produce query string - 1 test
        config = {
            method: "GET",
            url: "http://example.com/",
            params: {}
        };
        proto.open = function(method, url, async, user, password) {
            t.eq(url, config.url, "empty params doesn't produce query string");
        }
        request = issue(config);
        
        // test that query string doesn't get two ? separators
        config = {
            method: "GET",
            url: "http://example.com/?existing=query",
            params: {"foo": "bar"}
        };
        proto.open = function(method, url, async, user, password) {
            t.eq(url, config.url + "&foo=bar", "existing query string gets extended with &");
        }
        request = issue(config);
        
        // test that query string doesn't get ? followed by &
        config = {
            method: "GET",
            url: "http://example.com/service?",
            params: {"foo": "bar"}
        };
        proto.open = function(method, url, async, user, password) {
            t.eq(url, config.url + "foo=bar", "existing query string ending with ? gets extended without &");
        }
        request = issue(config);
        
        // reset open method
        proto.open = _open;
        
        // test that headers are correctly set - 6 tests
        var _setRequestHeader = proto.setRequestHeader;
        config = {
            headers: {
                foo: "bar",
                chicken: "soup",
                // This checks whether the autoadded 'X-Requested-With'-header
                // can be overridden, even though the given key here is spelled
                // in lowercase. 
                'x-requested-with': 'humpty'
            }
        };
        // we also track how often setRequestHeader is being called, it should
        // be called once for every header, even with the above defined
        // custom 'x-requested-with' header which we usually autoadd.
        // If the numbers match, we make sure to not send duplicate headers like
        //   x-requested-with: humpty         AND
        //   X-Requested-With: XMLHttpRequest
        var actualSetHeaderCnt = 0;
        var expectedSetHeaderCnt = 3; // and not four!
        proto.setRequestHeader = function(key, value) {
            actualSetHeaderCnt++;
            t.ok(key in config.headers, "setRequestHeader called with key: " + key);
            t.eq(value, config.headers[key], "setRequestHeader called with correct value: " + value);
        };
        request = issue(config);
        
        t.eq(actualSetHeaderCnt, expectedSetHeaderCnt, 'A custom "x-requested-with" header overrides the default "X-Requested-With" header.');

        proto.setRequestHeader = _setRequestHeader;
        
        // test that callback is called (no scope) - 1 test
        var unbound = function(request) {
            t.ok(request instanceof OpenLayers.Request.XMLHttpRequest,
                 "unbound callback called with xhr instance");
        }
        config = {
            callback: unbound
        };
        request = issue(config);
        request.readyState = OpenLayers.Request.XMLHttpRequest.DONE;
        request.onreadystatechange();

        // test that callback is called (with scope) - 2 tests
        var obj = {};
        var bound = function(request) {
            t.ok(this === obj, "bound callback has correct scope");
            t.ok(request instanceof OpenLayers.Request.XMLHttpRequest,
                 "bound callback called with xhr instance");
        }
        config = {
            callback: bound,
            scope: obj
        };
        request = issue(config);
        request.readyState = 4;
        request.onreadystatechange();
        
        // test that optional success callback is only called with 200s and
        // failure is only called with non-200s
        var _send = proto.send;
        proto.send = function() {};
        
        config = {
            success: function(req) {
                t.ok(!req.status || (req.status >= 200 && req.status < 300),
                     "success callback called with " + req.status + " status");
            },
            failure: function(req) {
                t.ok(req.status && (req.status < 200 || req.status >= 300),
                     "failure callback called with " + req.status + " status");
            }
        };
        request = issue(config);
        request.readyState = 4;
        
        // mock up status 200 (1 test)
        request.status = 200;
        request.onreadystatechange();
        
        // mock up status 299 (1 test)
        request.status = 299;
        request.onreadystatechange();
        
        // mock up status 100 (1 test)
        request.status = 100;
        request.onreadystatechange();

        // mock up status 300 (1 test)
        request.status = 300;
        request.onreadystatechange();
        
        // mock up a status null (1 test)
        request.status = null;
        request.onreadystatechange();

        proto.send = _send;

        teardown();
    }
    
    function test_delayed_send(t) {
        t.plan(1);
        var proto = OpenLayers.Request.XMLHttpRequest.prototype;
        var _send = proto.send;
        
        // test that send is called with data - 1 test
        var config = {
            method: "PUT",
            data: "bling"
        };
        var got = {};
        proto.send = function(data) {
            got.data = data;
        }
        OpenLayers.Request.issue(config);
        
        t.delay_call(1, function() {
            t.eq(got.data, config.data, "proper data sent");
            proto.send = _send;
        });        
        
    }
    
    function test_GET(t) {
        t.plan(1);
        var _issue = OpenLayers.Request.issue;
        OpenLayers.Request.issue = function(config) {
            t.eq(config.method, "GET", "calls issue with correct method");
        }
        OpenLayers.Request.GET();
        OpenLayers.Request.issue = _issue;
    }
    function test_POST(t) {
        t.plan(1);
        var _issue = OpenLayers.Request.issue;
        OpenLayers.Request.issue = function(config) {
            t.eq(config.method, "POST", "calls issue with correct method");
        }
        OpenLayers.Request.POST();
        OpenLayers.Request.issue = _issue;
    }
    function test_PUT(t) {
        t.plan(1);
        var _issue = OpenLayers.Request.issue;
        OpenLayers.Request.issue = function(config) {
            t.eq(config.method, "PUT", "calls issue with correct method");
        }
        OpenLayers.Request.PUT();
        OpenLayers.Request.issue = _issue;
    }
    function test_DELETE(t) {
        t.plan(1);
        var _issue = OpenLayers.Request.issue;
        OpenLayers.Request.issue = function(config) {
            t.eq(config.method, "DELETE", "calls issue with correct method");
        }
        OpenLayers.Request.DELETE();
        OpenLayers.Request.issue = _issue;
    }
    function test_HEAD(t) {
        t.plan(1);
        var _issue = OpenLayers.Request.issue;
        OpenLayers.Request.issue = function(config) {
            t.eq(config.method, "HEAD", "calls issue with correct method");
        }
        OpenLayers.Request.HEAD();
        OpenLayers.Request.issue = _issue;
    }
    function test_OPTIONS(t) {
        t.plan(1);
        var _issue = OpenLayers.Request.issue;
        OpenLayers.Request.issue = function(config) {
            t.eq(config.method, "OPTIONS", "calls issue with correct method");
        }
        OpenLayers.Request.OPTIONS();
        OpenLayers.Request.issue = _issue;
    }
    
    function test_events_success(t) {
        
        t.plan(5);

        var events = [];
        function listener(event) {
            events.push(event);
        }
        
        // set up event listeners
        OpenLayers.Request.events.on({
            complete: listener,
            success: listener,
            failure: listener
        });

        // issue a request that succeeds
        OpenLayers.Request.GET({
            url: ".", params: {bar: "baz"}, async: false
        });
        t.eq(events.length, 2, "two events logged");
        t.eq(events[0].type, "complete", "first event is complete");
        t.eq(events[1].type, "success", "second event is success");
        t.ok(events[1].config, "success listener sent config");
        t.eq(events[1].requestUrl, ".?bar=baz", "success listener sent config.url");

        // remove event listeners
        OpenLayers.Request.events.un({
            complete: listener,
            success: listener,
            failure: listener
        });
        
    }

    function test_events_failure(t) {
        
        t.plan(5);

        var events = [];
        function listener(event) {
            events.push(event);
        }
        
        // set up event listeners
        OpenLayers.Request.events.on({
            complete: listener,
            success: listener,
            failure: listener
        });

        // issue a request that succeeds
        OpenLayers.Request.GET({
            url: "foo", params: {bar: "baz"}, async: false
        });
        t.eq(events.length, 2, "two events logged");
        t.eq(events[0].type, "complete", "first event is complete");
        t.eq(events[1].type, "failure", "second event is failure");
        t.ok(events[1].config, "failure listener sent config");
        t.eq(events[1].requestUrl, "foo?bar=baz", "failure listener sent requestUrl");

        // remove event listeners
        OpenLayers.Request.events.un({
            complete: listener,
            success: listener,
            failure: listener
        });
        
    }

    function test_ProxyHost(t) {
        t.plan(5);

        /*
         * Setup
         */

        setup();

        var expectedURL;

        var _ProxyHost = OpenLayers.ProxyHost;

        var proto = OpenLayers.Request.XMLHttpRequest.prototype;
        var _open = proto.open;
        var log = [];
        var port;
        proto.open = function(method, url, async, user, password) {
            log.push(url);
        };

        /*
         * Test
         */

        // 2 tests
        log = [];
        OpenLayers.ProxyHost = "http://fooproxy/?url=";
        expectedURL = "http://fooproxy/?url=http%3A%2F%2Fbar%3Fk1%3Dv1%26k2%3Dv2";        
        OpenLayers.Request.GET({url: "http://bar?k1=v1&k2=v2"});
        t.eq(log.length, 1, "[1] XHR.open called once");
        t.eq(log[0], expectedURL, "[1] the URL used for XHR is correct (" + log[0] + ")");
        
        // 1 test
        log = [];
        OpenLayers.ProxyHost = "http://fooproxy/?url=";
        port = window.location.port ? ':'+window.location.port : '';
        expectedURL = window.location.protocol+"//"+window.location.hostname+port+"/service";
        OpenLayers.Request.GET({url: expectedURL});
        t.eq(log[0], expectedURL, "[2] proxy is not used when requesting the same server");
        
        // 2 tests
        log = [];
        OpenLayers.ProxyHost = function(url) {
            var p = OpenLayers.Util.getParameters(url);
            var p = OpenLayers.Util.getParameterString(p);
            return "http://barproxy/?" + p;
        };
        expectedURL = "http://barproxy/?k1=v1&k2=v2";
        OpenLayers.Request.GET({url: "http://bar?k1=v1&k2=v2"});
        t.eq(log.length, 1, "[3] XHR.open called once");
        t.eq(log[0], expectedURL, "[3] the URL used for XHR is correct (" + log[0] + ")");

        /*
         * Teardown
         */

        OpenLayers.Request.XMLHttpRequest.prototype.open = _open;
        OpenLayers.ProxyHost = _ProxyHost;
        teardown();
    }

    function test_abort(t) {

        t.plan(0);

        var sendCalled;

        // set up

        var _open = OpenLayers.Request.XMLHttpRequest.prototype.open;
        OpenLayers.Request.XMLHttpRequest.prototype.open = function() {
            this.readyState = OpenLayers.Request.XMLHttpRequest.OPENED;
        };

        var _setRequestHeader = OpenLayers.Request.XMLHttpRequest.prototype.setRequestHeader;
        OpenLayers.Request.XMLHttpRequest.prototype.setRequestHeader = function() {};

        var _send = OpenLayers.Request.XMLHttpRequest.prototype.send;
        OpenLayers.Request.XMLHttpRequest.prototype.send = function() {
            sendCalled = true;
        };

        // test

        sendCalled = false;
        OpenLayers.Request.issue().abort();

        t.delay_call(0.5, function() {
            if (sendCalled) {
                t.fail("Send should not be called because request is aborted");
            }

            // tear down
            OpenLayers.Request.XMLHttpRequest.prototype.open = _open;
            OpenLayers.Request.XMLHttpRequest.prototype.setRequestHeader = _setRequestHeader;
            OpenLayers.Request.XMLHttpRequest.prototype.send = _send;
        });
    }

    function test_abort2(t) {
        t.plan(0);
        var fail = false;
        OpenLayers.Request.XMLHttpRequest.onsend = function(args) {
            fail = true;
        }
        t.delay_call(0.5, function() {
            if (fail === true) {
                t.fail("Send should not be called because request is aborted");
            }
            OpenLayers.Request.XMLHttpRequest.onsend = null;
        });
        var req = OpenLayers.Request.GET();
        req.abort();
    }
    
    function test_XRequestedWithHeaderAutoadded(t) {
        t.plan( 2 );
        
        var headerSet = false;
        var headerGot = '';
        var headerExpected = 'XMLHttpRequest';
        
        // save to be able to restore later
        var _setRequestHeader = OpenLayers.Request.XMLHttpRequest.prototype.setRequestHeader;
        
        OpenLayers.Request.XMLHttpRequest.prototype.setRequestHeader = function(field, value) {
            if (field === 'X-Requested-With') {
                headerSet = true;
                headerGot = value;
            }
        };
        
        var req = OpenLayers.Request.issue({
            url: location.href,
            async: false
        });
                
        t.ok( headerSet, 'We call the method "setRequestHeader" to set a "X-Requested-With"-header' );
        t.eq( headerGot, headerExpected,  'The "X-Requested-With"-header is set to "' + headerExpected + '" as expected.' );
        
        // restore old setRequestHeader
        OpenLayers.Request.XMLHttpRequest.prototype.setRequestHeader = _setRequestHeader;
    }
    </script>
</head>
<body>
</body>
</html>