forked from camptocamp/ogc-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-utils.spec.ts
More file actions
484 lines (467 loc) · 15 KB
/
http-utils.spec.ts
File metadata and controls
484 lines (467 loc) · 15 KB
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
import { EndpointError } from './errors.js';
import {
queryXmlDocument,
setFetchOptions,
setQueryParams,
sharedFetch,
} from './http-utils.js';
import { fetchDocument } from '../ogc-api/link-utils.js';
import WfsEndpoint from '../wfs/endpoint.js';
// @ts-expect-error ts-migrate(7016)
import capabilities200 from '../../fixtures/wfs/capabilities-pigma-2-0-0.xml';
jest.useFakeTimers();
afterEach(() => {
jest.clearAllMocks();
});
describe('HTTP utils', () => {
describe('queryXmlDocument', () => {
const sampleXml = '<sample-xml><node1></node1><node2></node2></sample-xml>';
let fetchBehaviour:
| 'ok'
| 'httpError'
| 'corsError'
| 'networkError'
| 'delay';
let originalFetch;
beforeAll(() => {
fetchBehaviour = 'ok';
originalFetch = globalThis.fetch; // keep reference of native impl
globalThis.fetch = jest.fn().mockImplementation((xmlString, opts) => {
const noCors = opts && opts.mode === 'no-cors';
const headers = { get: () => null };
switch (fetchBehaviour) {
case 'ok':
return Promise.resolve({
arrayBuffer: () =>
Promise.resolve(Buffer.from(xmlString, 'utf-8')),
status: 200,
ok: true,
headers,
clone: function () {
return this;
},
});
case 'httpError':
return Promise.resolve({
text: () => Promise.resolve('<error>Random error</error>'),
status: 401,
ok: false,
clone: function () {
return this;
},
});
case 'corsError':
if (noCors)
return Promise.resolve({
status: 200,
ok: true,
clone: function () {
return this;
},
});
return Promise.reject(new Error('Cross origin headers missing'));
case 'networkError':
return Promise.reject(new Error('General network error'));
case 'delay':
return new Promise((resolve) => {
setTimeout(
() =>
resolve({
ok: true,
status: 200,
headers,
arrayBuffer: () =>
Promise.resolve(Buffer.from(sampleXml, 'utf-8')),
clone: function () {
return this;
},
}),
10
);
});
}
});
});
afterAll(() => {
globalThis.fetch = originalFetch; // restore original impl
});
describe('HTTP request returns success', () => {
beforeEach(() => {
fetchBehaviour = 'ok';
});
it('resolves with the endpoint object', async () => {
await expect(queryXmlDocument(sampleXml)).resolves.toMatchObject({
children: [
{
children: expect.any(Array),
name: 'sample-xml',
isRootNode: true,
type: 'element',
},
],
type: 'document',
});
});
});
describe('HTTP request returns error', () => {
beforeEach(() => {
fetchBehaviour = 'httpError';
});
it('rejects with an error', async () => {
await expect(queryXmlDocument(sampleXml)).rejects.toEqual(
new EndpointError(
'Received an error with code 401: <error>Random error</error>',
401,
false
)
);
});
});
describe('HTTP fails for CORS reasons', () => {
beforeEach(() => {
fetchBehaviour = 'corsError';
});
it('rejects with an error', async () => {
await expect(queryXmlDocument(sampleXml)).rejects.toThrowError(
new EndpointError(
`The document could not be fetched due to CORS limitations`
)
);
});
});
describe('HTTP fails for network reasons', () => {
beforeEach(() => {
fetchBehaviour = 'networkError';
});
it('rejects with an error', async () => {
await expect(queryXmlDocument(sampleXml)).rejects.toEqual(
new EndpointError(
'Fetching the document failed either due to network errors or unreachable host, error is: General network error'
)
);
});
});
describe('HTTP succeeds but XML is malformed', () => {
beforeEach(() => {
fetchBehaviour = 'ok';
});
it('rejects with an error related to XML parsing', async () => {
await expect(
queryXmlDocument('<broken-xml</broken-xml>')
).rejects.toThrowError('Unclosed start tag for element `broken-xml`');
});
});
describe('multiple similar HTTP requests in parallel', () => {
beforeEach(() => {
fetchBehaviour = 'delay';
queryXmlDocument('https://abcd.com');
queryXmlDocument('https://abcd.com');
queryXmlDocument('https://abcd.com');
});
it('only fetches the document once', async () => {
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
});
});
});
describe('setQueryParams', () => {
it('adds new parameters if not present', () => {
expect(
setQueryParams('https://my.host/service?arg1=123', {
ARG2: '45',
Arg3: 'hello',
})
).toBe('https://my.host/service?arg1=123&ARG2=45&Arg3=hello');
});
it('replaces existing parameters regardless of case', () => {
expect(
setQueryParams('https://my.host/service?ARG1=123&Arg2=bla&arg3', {
ARG2: '45',
Arg3: 'hello',
})
).toBe('https://my.host/service?ARG1=123&ARG2=45&Arg3=hello');
});
it('sets a parameter without value if true', () => {
expect(
setQueryParams('https://my.host/service', {
ARG2: true,
})
).toBe('https://my.host/service?ARG2=');
});
it('appends an encoded URL if found (HTTP)', () => {
expect(
setQueryParams('http://bad.proxy/?url=http%3A%2F%2Fmy.host%2Fservice', {
ARG2: '45',
Arg3: 'hello',
})
).toBe(
'http://bad.proxy/?url=http%3A%2F%2Fmy.host%2Fservice%3FARG2%3D45%26Arg3%3Dhello'
);
});
it('appends an encoded URL if found (HTTPS)', () => {
expect(
setQueryParams(
'http://bad.proxy/?url=https%3A%2F%2Fmy.host%2Fservice',
{
ARG2: '45',
Arg3: 'hello',
}
)
).toBe(
'http://bad.proxy/?url=https%3A%2F%2Fmy.host%2Fservice%3FARG2%3D45%26Arg3%3Dhello'
);
});
it('makes sure that spaces are encoded as %20', () => {
expect(
setQueryParams(
'https://my.host/service?arg1=old+value&something=else+entirely',
{
ARG1: 'new value',
'ARG 2': 'value with space',
}
)
).toBe(
'https://my.host/service?something=else%20entirely&ARG1=new%20value&ARG%202=value%20with%20space'
);
});
});
describe('sharedFetch', () => {
let originalFetch;
beforeAll(() => {
originalFetch = globalThis.fetch; // keep reference of native impl
globalThis.fetch = jest.fn(
() =>
new Promise((resolve) => {
setTimeout(() => {
// return a different result every time
const text = `request result: ${Math.floor(
Math.random() * 100000
)}`;
resolve({
text: async () => text,
status: 200,
ok: true,
headers: new Headers(),
clone: jest.fn().mockImplementation(function () {
return this;
}) as () => Response,
} as Response);
}, 10);
})
);
});
afterAll(() => {
globalThis.fetch = originalFetch; // restore original impl
});
describe('multiple GET and HEAD requests on same resource', () => {
let getResults, headResults;
beforeEach(async () => {
getResults = [];
headResults = [];
// these requests will be shared
sharedFetch('http://test.org/resource1').then(
(r) => (getResults[0] = r)
);
sharedFetch('http://test.org/resource1', 'HEAD').then(
(r) => (headResults[0] = r)
);
jest.advanceTimersByTime(2);
sharedFetch('http://test.org/resource1').then(
(r) => (getResults[1] = r)
);
sharedFetch('http://test.org/resource1', 'HEAD').then(
(r) => (headResults[1] = r)
);
jest.advanceTimersByTime(3);
sharedFetch('http://test.org/resource1').then(
(r) => (getResults[2] = r)
);
sharedFetch('http://test.org/resource1', 'HEAD').then(
(r) => (headResults[2] = r)
);
await jest.advanceTimersByTime(10);
await jest.runOnlyPendingTimers();
// first batch has resolved
sharedFetch('http://test.org/resource1', 'HEAD').then(
(r) => (headResults[3] = r)
);
sharedFetch('http://test.org/resource1').then(
(r) => (getResults[3] = r)
);
await jest.advanceTimersByTime(10);
await jest.runOnlyPendingTimers();
});
it('only triggers two GET requests and two HEAD requests', () => {
expect(globalThis.fetch).toHaveBeenCalledTimes(4);
expect((globalThis.fetch as jest.Mock).mock.calls).toEqual([
[
'http://test.org/resource1',
expect.objectContaining({ method: 'GET' }),
],
[
'http://test.org/resource1',
expect.objectContaining({ method: 'HEAD' }),
],
[
'http://test.org/resource1',
expect.objectContaining({ method: 'HEAD' }),
],
[
'http://test.org/resource1',
expect.objectContaining({ method: 'GET' }),
],
]);
});
it('calls clone() on each response', () => {
expect(getResults[0].clone).toHaveBeenCalled();
expect(headResults[0].clone).toHaveBeenCalled();
});
it('shares result for simultaneous GET requests and not subsequent ones', async () => {
const sharedResult = await getResults[0].text();
const getResultsText = await Promise.all(
getResults.map((r) => r.text())
);
expect(getResultsText).toEqual([
sharedResult,
sharedResult,
sharedResult,
expect.not.stringContaining(sharedResult),
]);
});
it('shares result for simultaneous HEAD requests and not subsequent ones', async () => {
const sharedResult = await headResults[0].text();
const headResultsText = await Promise.all(
headResults.map((r) => r.text())
);
expect(headResultsText).toEqual([
sharedResult,
sharedResult,
sharedResult,
expect.not.stringContaining(sharedResult),
]);
});
});
describe('GET and HEAD requests on different resources', () => {
let getResults, headResults;
beforeEach(async () => {
getResults = [];
headResults = [];
// these requests will be not shared
sharedFetch('http://test.org/resource1').then(
(r) => (getResults[0] = r)
);
sharedFetch('http://test.org/resource2', 'HEAD').then(
(r) => (headResults[0] = r)
);
sharedFetch('http://test.org/resource3').then(
(r) => (getResults[1] = r)
);
sharedFetch('http://test.org/resource4', 'HEAD').then(
(r) => (headResults[1] = r)
);
await jest.advanceTimersByTime(40);
await jest.runOnlyPendingTimers();
});
it('triggers two GET requests and two HEAD requests', () => {
expect(globalThis.fetch).toHaveBeenCalledTimes(4);
expect((globalThis.fetch as jest.Mock).mock.calls).toEqual([
[
'http://test.org/resource1',
expect.objectContaining({ method: 'GET' }),
],
[
'http://test.org/resource2',
expect.objectContaining({ method: 'HEAD' }),
],
[
'http://test.org/resource3',
expect.objectContaining({ method: 'GET' }),
],
[
'http://test.org/resource4',
expect.objectContaining({ method: 'HEAD' }),
],
]);
});
it('does not share GET results', () => {
expect(getResults[0].text).not.toBe(getResults[1].text);
});
it('does not share HEAD results', () => {
expect(headResults[0].text).not.toBe(headResults[1].text);
});
});
});
describe('fetch options', () => {
const sampleOptions = {
referrer: 'abcd',
mode: 'cors',
headers: { hello: 'world' },
credentials: 'include',
integrity: 'abcdefg',
redirect: 'follow',
} as const;
describe('used in queryXmlDocument', () => {
beforeEach(() => {
setFetchOptions(sampleOptions);
queryXmlDocument('./hello.xml');
});
it('is used in the fetch() call', () => {
expect(globalThis.fetch).toHaveBeenCalledWith('./hello.xml', {
...sampleOptions,
method: 'GET',
});
});
});
describe('used in sharedFetch', () => {
beforeEach(() => {
setFetchOptions(sampleOptions);
sharedFetch('./hello.xml', 'HEAD');
});
it('is used in the fetch() call', () => {
expect(globalThis.fetch).toHaveBeenCalledWith('./hello.xml', {
...sampleOptions,
method: 'HEAD',
});
});
});
describe('used in ogc-api fetchDocument', () => {
beforeEach(() => {
setFetchOptions(sampleOptions);
globalThis.fetchResponseFactory = () => '{ "hello": "world" }';
fetchDocument('./hello.json');
});
it('is used in the fetch() call', () => {
expect(globalThis.fetch).toHaveBeenCalledWith(
'http://localhost/hello.json?f=json',
{
...sampleOptions,
method: 'GET',
headers: {
...sampleOptions.headers,
Accept: 'application/json,application/schema+json',
},
}
);
});
});
describe('used in worker', () => {
let endpoint;
beforeEach(() => {
globalThis.fetchResponseFactory = () => capabilities200;
setFetchOptions(sampleOptions);
endpoint = new WfsEndpoint(
'https://my.test.service/ogc/wfs?service=wfs&request=DescribeFeatureType'
);
});
it('is used in the fetch() call', async () => {
await endpoint.isReady();
expect(globalThis.fetch).toHaveBeenCalledWith(
'https://my.test.service/ogc/wfs?SERVICE=WFS&REQUEST=GetCapabilities',
{
...sampleOptions,
method: 'GET',
}
);
});
});
});
});