60b0dad59d68ea21bfba45c759df89b5a7ccebe9
[squeep-api-dingus] / test / lib / dingus.js
1 /* eslint-disable capitalized-comments */
2 /* eslint-env mocha */
3 'use strict';
4
5 const assert = require('assert');
6 const sinon = require('sinon'); // eslint-disable-line node/no-unpublished-require
7 const fs = require('fs');
8
9 const Dingus = require('../../lib/dingus');
10 const { DingusError } = require('../../lib/errors');
11 const Enum = require('../../lib/enum');
12
13 const noExpectedException = 'did not get expected exception';
14
15 describe('Dingus', function () {
16 let dingus;
17 beforeEach(function () {
18 dingus = new Dingus();
19 });
20 afterEach(function () {
21 sinon.restore();
22 });
23
24 describe('constructor', function () {
25 it('covers', function () {
26 const d = new Dingus({}, {});
27 assert(d);
28 assert('log' in d.logger);
29 });
30 }); // constructor
31
32 describe('_normalizePath', function () {
33 it('returns normal path', function () {
34 const p = '/a/b/c';
35 const r = dingus._normalizePath(p);
36 assert.strictEqual(r, p);
37 });
38 it('returns normal path', function () {
39 const p = '////a///b/./bar/..///c';
40 const expected = '/a/b/c'
41 const r = dingus._normalizePath(p);
42 assert.strictEqual(r, expected);
43 });
44 }); // _normalizePath
45
46 describe('_splitUrl', function () {
47 const nullObject = Object.create(null);
48
49 it('splits a simple path', function () {
50 const p = '/a/b/c';
51 const expected = {
52 pathPart: p,
53 queryParams: nullObject,
54 };
55 const r = dingus._splitUrl(p);
56 assert.deepStrictEqual(r, expected);
57 });
58 it('splits a path with trailing slash preserved', function () {
59 const p = '/a/b/c/';
60 const expected = {
61 pathPart: p,
62 queryParams: nullObject,
63 };
64 const r = dingus._splitUrl(p);
65 assert.deepStrictEqual(r, expected);
66 });
67 it('splits a path with trailing slash ignored', function () {
68 const p = '/a/b/c/';
69 const expected = {
70 pathPart: p,
71 queryParams: nullObject,
72 };
73 dingus.ignoreTrailingSlash = true;
74 const r = dingus._splitUrl(p);
75 assert.deepStrictEqual(r, expected);
76 });
77 it('splits a path with empty query string', function () {
78 const p = '/a/b/c?';
79 const expected = {
80 pathPart: '/a/b/c',
81 queryParams: nullObject,
82 };
83 const r = dingus._splitUrl(p);
84 assert.deepStrictEqual(r, expected);
85 });
86 it('splits a path with query string', function () {
87 const p = '/a/b/c?x=1&y=2&z';
88 const expected = {
89 pathPart: '/a/b/c',
90 queryParams: Object.assign(Object.create(null), {
91 x: '1',
92 y: '2',
93 z: '', // Subjective Editorial: disagree with the default querystring parser behavior here: null would be better than empty string, esp as result is null-prototyped object.
94 }),
95 };
96 const r = dingus._splitUrl(p);
97 assert.deepStrictEqual(r, expected);
98 });
99 }); // _splitUrl
100
101 describe('tagContext', function () {
102 let req, res, ctx;
103 beforeEach(function () {
104 req = {
105 getHeader: sinon.stub(),
106 setHeader: sinon.stub(),
107 };
108 res = {
109 getHeader: sinon.stub(),
110 setHeader: sinon.stub(),
111 };
112 ctx = {};
113 });
114 it ('sets id in context', function () {
115 const result = Dingus.tagContext(req, res, ctx);
116 assert.strictEqual(ctx.requestId, result);
117 assert(res.setHeader.called);
118 });
119 it ('sets provided header', function () {
120 req.getHeader.onCall(0).returns('abc'); // X-Request-ID
121 const result = Dingus.tagContext(req, res, ctx);
122 assert.strictEqual(ctx.requestId, result);
123 assert.strictEqual(res.setHeader.getCall(0).args[0], 'Request-ID');
124 assert.strictEqual(res.setHeader.getCall(1).args[0], 'X-Request-ID');
125 assert.strictEqual(res.setHeader.getCall(1).args[1], 'abc');
126 assert.strictEqual(res.setHeader.callCount, 2);
127 });
128 }); // tagContext
129
130 describe('clientAddressContext', function () {
131 let req, res, ctx;
132 let _tp;
133 before(function () {
134 _tp = dingus.trustProxy;
135 });
136 after(function () {
137 dingus.trustProxy = _tp;
138 });
139 beforeEach(function () {
140 req = {
141 getHeader: sinon.stub(),
142 setHeader: sinon.stub(),
143 connection: {},
144 };
145 res = {
146 getHeader: sinon.stub(),
147 setHeader: sinon.stub(),
148 };
149 ctx = {};
150 });
151 it ('covers untrusted proxy', function () {
152 dingus.trustProxy = false;
153 const expected = {
154 clientAddress: '',
155 clientProtocol: 'http',
156 }
157 dingus.clientAddressContext(req, res, ctx);
158 assert.deepStrictEqual(ctx, expected);
159 assert(!req.getHeader.called);
160 });
161 it ('covers missing', function () {
162 dingus.trustProxy = true;
163 const expected = {
164 clientAddress: '::1',
165 clientProtocol: 'https',
166 }
167 req.connection.remoteAddress = '::1';
168 req.connection.encrypted = true;
169 dingus.clientAddressContext(req, res, ctx);
170 assert(req.getHeader.called);
171 assert.deepStrictEqual(ctx, expected);
172 });
173 }); // clientAddressContext
174
175 describe('getRequestContentType', function () {
176 let req;
177 beforeEach(function () {
178 req = {
179 getHeader: sinon.stub(),
180 setHeader: sinon.stub(),
181 };
182 });
183 it('handles missing header', function () {
184 const result = Dingus.getRequestContentType(req);
185 assert.strictEqual(result, '');
186 });
187 it('parses simple type', function () {
188 req.getHeader.onCall(0).returns(Enum.ContentType.ApplicationJson);
189 const result = Dingus.getRequestContentType(req);
190 assert.strictEqual(result, Enum.ContentType.ApplicationJson);
191 });
192 it('parses complex type', function () {
193 req.getHeader.onCall(0).returns('application/json ; charset=UTF-8');
194 const result = Dingus.getRequestContentType(req);
195 assert.strictEqual(result, Enum.ContentType.ApplicationJson);
196 });
197 }); // getRequestContentType
198
199 describe('setResponseContentType', function () {
200 let req, responseTypes;
201 beforeEach(function () {
202 responseTypes = [];
203 req = {
204 setHeader: sinon.stub(),
205 getHeader: sinon.stub(),
206 };
207 });
208 it('handles missing header', function () {
209 const result = Dingus.getResponseContentType(responseTypes, req);
210 assert.strictEqual(result, undefined);
211 });
212 it('behaves as expected', function () {
213 responseTypes.push(Enum.ContentType.ApplicationJson);
214 req.getHeader.onCall(0).returns('text, image/png;q=0.5, application/*;q=0.2, audio;q=0.1');
215 const result = Dingus.getResponseContentType(responseTypes, req);
216 assert.strictEqual(result, Enum.ContentType.ApplicationJson);
217 });
218 }); // setResponseContentType
219
220 describe('on', function () {
221 let stubOn;
222 beforeEach(function () {
223 stubOn = sinon.stub(dingus.router, 'on');
224 });
225 it('covers', function () {
226 dingus.on('GET', '/', () => {});
227 assert(stubOn.called);
228 });
229 }); // on
230
231 describe('setEndBodyHandler', function () {
232 let req, res, ctx, handler, origEnd, origWrite;
233 beforeEach(function () {
234 origEnd = sinon.stub();
235 origWrite = sinon.stub();
236 req = {};
237 res = {
238 write: origWrite,
239 end: origEnd,
240 };
241 ctx = {};
242 handler = sinon.stub();
243 });
244 it('collects body and handles', function () {
245 Dingus.setEndBodyHandler(req, res, ctx, handler);
246 res.write(Buffer.from('foo'));
247 res.write('baz');
248 res.write();
249 res.end('quux');
250 assert(origWrite.called);
251 assert(origEnd.called);
252 assert.deepStrictEqual(ctx.responseBody, Buffer.from('foobazquux'));
253 assert(handler.called);
254 });
255 }); // setEndBodyHandler
256
257 describe('setHeadHandler', function () {
258 let req, res, ctx, origEnd, origWrite;
259 beforeEach(function () {
260 origEnd = sinon.stub();
261 origWrite = sinon.stub();
262 req = {
263 method: 'HEAD',
264 };
265 res = {
266 end: origEnd,
267 write: origWrite,
268 setHeader: sinon.stub(),
269 };
270 ctx = {};
271 });
272 it('collects body without writing', function () {
273 Dingus.setHeadHandler(req, res, ctx);
274 res.write(Buffer.from('foo'));
275 res.write('baz');
276 res.write();
277 res.end('quux');
278 assert(!origWrite.called);
279 assert(origEnd.called);
280 assert.deepStrictEqual(ctx.responseBody, Buffer.from('foobazquux'));
281 });
282 it('ignores non-head method', function () {
283 req.method = 'GET';
284 Dingus.setHeadHandler(req, res, ctx);
285 res.write(Buffer.from('foo'));
286 res.end('bar');
287 assert(origWrite.called);
288 assert(origEnd.called);
289 });
290 }); // setHeadHandler
291
292 describe('addEncodingHeader', function () {
293 let res, encoding;
294 beforeEach(function () {
295 res = {
296 _headers: {},
297 // eslint-disable-next-line security/detect-object-injection
298 getHeader: (h) => res._headers[h],
299 // eslint-disable-next-line security/detect-object-injection
300 setHeader: (h, v) => res._headers[h] = v,
301 };
302 });
303 it('adds', function () {
304 encoding = 'gzip';
305 Dingus.addEncodingHeader(res, encoding);
306 assert.strictEqual(res._headers[Enum.Header.ContentEncoding], 'gzip');
307 });
308 it('extends', function () {
309 encoding = 'utf8';
310 Dingus.addEncodingHeader(res, encoding);
311 assert.strictEqual(res._headers[Enum.Header.ContentEncoding], 'utf8');
312 encoding = 'gzip';
313 Dingus.addEncodingHeader(res, encoding);
314 assert.strictEqual(res._headers[Enum.Header.ContentEncoding], 'gzip, utf8');
315 });
316 }); // addEncodingHeader
317
318 describe('dispatch', function () {
319 let pathsByLengthOrig;
320 let req, res, ctx;
321 let stubHandler;
322
323 beforeEach(function () {
324 req = {
325 url: '/',
326 method: 'GET',
327 setHeader: sinon.stub(),
328 getHeader: sinon.stub(),
329 };
330 res = {
331 statusCode: 200,
332 end: sinon.stub(),
333 setHeader: sinon.stub(),
334 hasHeader: sinon.stub(),
335 getHeader: sinon.stub(),
336 getHeaders: sinon.stub(),
337 };
338 ctx = {};
339 pathsByLengthOrig = dingus.pathsByLength;
340 sinon.spy(dingus, 'handlerMethodNotAllowed');
341 sinon.spy(dingus, 'handlerNotFound');
342 sinon.spy(dingus, 'handlerBadRequest');
343 sinon.spy(dingus, 'handlerInternalServerError');
344 stubHandler = sinon.stub();
345 });
346 afterEach(function () {
347 dingus.pathsByLength = pathsByLengthOrig;
348 });
349
350 it('calls handler', async function () {
351 const urlPath = '/:id';
352 const method = 'GET';
353 dingus.on(method, urlPath, stubHandler);
354 req.url = '/abc';
355 req.method = method;
356
357 await dingus.dispatch(req, res, ctx);
358 assert(stubHandler.called);
359 assert(!dingus.handlerMethodNotAllowed.called);
360 assert(!dingus.handlerNotFound.called);
361 });
362 it('calls handler without context', async function () {
363 const urlPath = '/:id';
364 const method = 'GET';
365 dingus.on(method, urlPath, stubHandler);
366 req.url = '/abc';
367 req.method = method;
368
369 await dingus.dispatch(req, res);
370 assert(stubHandler.called);
371 assert(!dingus.handlerMethodNotAllowed.called);
372 assert(!dingus.handlerNotFound.called);
373 });
374 it('calls fallback handler', async function () {
375 const urlPath = '/abc/:id';
376 const method = 'GET';
377 dingus.on('*', urlPath, stubHandler);
378 req.url = '/abc/def';
379 req.method = method;
380
381 await dingus.dispatch(req, res, ctx);
382 assert(stubHandler.called);
383 assert(!dingus.handlerMethodNotAllowed.called);
384 assert(!dingus.handlerNotFound.called);
385 });
386 it('handles error in handler', async function () {
387 const urlPath = '/:id';
388 const method = 'GET';
389 dingus.on(method, urlPath, stubHandler);
390 req.url = '/abc';
391 req.method = method;
392 stubHandler.rejects(new Error('blah'));
393
394 await dingus.dispatch(req, res, ctx);
395 assert(stubHandler.called);
396 assert(!dingus.handlerMethodNotAllowed.called);
397 assert(!dingus.handlerNotFound.called);
398 });
399 it('calls unsupported method', async function () {
400 const urlPath = '/:id';
401 const method = 'POST';
402 dingus.on('GET', urlPath, stubHandler);
403 req.url = '/abc';
404 req.method = method;
405
406 await dingus.dispatch(req, res, ctx);
407 assert(!stubHandler.called);
408 assert(dingus.handlerMethodNotAllowed.called);
409 assert(!dingus.handlerNotFound.called);
410 });
411 it('does not lookup nonexistent path', async function () {
412 req.url = '/foo/bar';
413 req.method = 'GET';
414
415 await dingus.dispatch(req, res, ctx);
416 assert(!stubHandler.called);
417 assert(!dingus.handlerMethodNotAllowed.called);
418 assert(dingus.handlerNotFound.called);
419 });
420 it('covers unhandled dingus exception', async function () {
421 const expectedException = new DingusError('blah');
422 sinon.stub(dingus.router, 'lookup').throws(expectedException);
423
424 await dingus.dispatch(req, res, ctx);
425 assert(!stubHandler.called);
426 assert(dingus.handlerInternalServerError.called);
427 });
428 it('covers other exception', async function () {
429 const expectedException = new Error('blah');
430 sinon.stub(dingus.router, 'lookup').throws(expectedException);
431
432 await dingus.dispatch(req, res, ctx);
433 assert(!stubHandler.called);
434 assert(dingus.handlerInternalServerError.called);
435 });
436 it('covers bad uri', async function () {
437 req.url = '/%f';
438
439 await dingus.dispatch(req, res, ctx);
440 assert(dingus.handlerBadRequest.called);
441 });
442
443 }); // dispatch
444
445 describe('parseBody', function () {
446 let ctx;
447 beforeEach(function () {
448 ctx = {};
449 });
450 it('does not parse unknown type', function () {
451 try {
452 dingus.parseBody('unknown/type', ctx);
453 assert.fail(noExpectedException);
454 } catch (e) {
455 assert.strictEqual(e.statusCode, 415);
456 }
457 });
458 it('parses json', function () {
459 const src = { foo: 'bar' };
460 ctx.rawBody = JSON.stringify(src);
461 dingus.parseBody(Enum.ContentType.ApplicationJson, ctx);
462 assert.deepStrictEqual(ctx.parsedBody, src);
463 });
464 it('handles unparsable json', function () {
465 ctx.rawBody = 'not json';
466 try {
467 dingus.parseBody(Enum.ContentType.ApplicationJson, ctx);
468 assert.fail(noExpectedException);
469 } catch (e) {
470 assert.strictEqual(e.statusCode, 400);
471 }
472 });
473 it('parses form', function () {
474 const expected = Object.assign(Object.create(null), {
475 foo: 'bar',
476 });
477 ctx.rawBody = 'foo=bar';
478 dingus.parseBody('application/x-www-form-urlencoded', ctx);
479 assert.deepStrictEqual(ctx.parsedBody, expected);
480 });
481
482 }); // parseBody
483
484 describe('bodyData', function () {
485 let res, resEvents;
486 beforeEach(function () {
487 resEvents = {};
488 res = {
489 // eslint-disable-next-line security/detect-object-injection
490 on: (ev, fn) => resEvents[ev] = fn,
491 };
492 });
493 it('provides data', async function () {
494 const p = dingus.bodyData(res);
495 resEvents['data'](Buffer.from('foo'));
496 resEvents['data'](Buffer.from('bar'));
497 resEvents['end']();
498 const result = await p;
499 assert.strictEqual(result, 'foobar');
500 });
501 it('handles error', async function () {
502 const p = dingus.bodyData(res);
503 resEvents['error']('foo');
504 try {
505 await p;
506 assert.fail(noExpectedException);
507 } catch (e) {
508 assert.strictEqual(e, 'foo');
509 }
510 });
511 }); // bodyData
512
513 describe('ingestBody', function () {
514 it('covers', async function () {
515 const req = {};
516 const res = {};
517 const ctx = {};
518 sinon.stub(dingus, 'bodyData').resolves('{"foo":"bar"}')
519 sinon.stub(Dingus, 'getRequestContentType').returns(Enum.ContentType.ApplicationJson);
520 await dingus.ingestBody(req, res, ctx);
521 assert.deepStrictEqual(ctx.parsedBody, { foo: 'bar' });
522 });
523 }); // ingestBody
524
525 describe('setResponseType', function () {
526 let req, res, ctx;
527 let _sa; // Preserve strictAccept
528 before(function () {
529 _sa = dingus.strictAccept;
530 });
531 after(function () {
532 dingus.strictAccept = _sa;
533 });
534 beforeEach(function () {
535 ctx = {};
536 req = {};
537 res = {
538 setHeader: sinon.stub(),
539 };
540 sinon.stub(Dingus, 'getResponseContentType').returns();
541 });
542 it('rejects missing', function () {
543 dingus.strictAccept = true;
544 try {
545 dingus.setResponseType(['my/type'], req, res, ctx);
546 assert.fail(noExpectedException);
547 } catch (e) {
548 assert.strictEqual(e.statusCode, 406, 'did not get expected status code');
549 }
550 });
551 it('accepts missing', function () {
552 dingus.strictAccept = false;
553 dingus.setResponseType(['my/type'], req, res, ctx);
554 assert.strictEqual(ctx.responseType, 'my/type');
555 });
556
557 }); // setResponseType
558
559 describe('_readFileInfo', function () {
560 let stat, data, statRes, dataRes, filename;
561 beforeEach(function () {
562 sinon.stub(fs.promises, 'stat');
563 sinon.stub(fs.promises, 'readFile');
564 statRes = {
565 mtimeMs:1612553697186,
566 };
567 dataRes = 'data';
568 filename = 'dummy.txt';
569 });
570 it('succeeds', async function () {
571 fs.promises.stat.resolves(statRes);
572 fs.promises.readFile.resolves('data');
573 [stat, data] = await dingus._readFileInfo(filename);
574 assert.deepStrictEqual(stat, statRes);
575 assert.deepStrictEqual(data, dataRes);
576 });
577 it('returns null for non-existant file', async function () {
578 const noEnt = {
579 code: 'ENOENT',
580 };
581 fs.promises.stat.rejects(noEnt);
582 fs.promises.readFile.rejects(noEnt);
583 [stat, data] = await dingus._readFileInfo(filename);
584 assert.strictEqual(stat, null);
585 assert.strictEqual(data, null);
586 });
587 it('throws unexpected error', async function () {
588 const expectedException = new Error('blah');
589 fs.promises.stat.rejects(expectedException);
590 await assert.rejects(async () => {
591 await dingus._readFileInfo(filename);
592 }, expectedException);
593 });
594 }); // _readFileInfo
595
596 describe('_serveFileMetaHeaders', function () {
597 let res, directory, fileName;
598 beforeEach(function () {
599 sinon.stub(dingus, '_readFileInfo');
600 res = {
601 setHeader: sinon.stub(),
602 };
603 directory = '/path';
604 fileName = 'filename';
605 });
606 it('covers no meta file', async function() {
607 dingus._readFileInfo.resolves([null, null]);
608 await dingus._serveFileMetaHeaders(res, directory, fileName);
609 assert(!res.setHeader.called);
610 });
611 it('adds extra headers', async function () {
612 dingus._readFileInfo.resolves([{}, Buffer.from(`Link: <https://example.com/>; rel="relation"
613 X-Folded-Header: data
614 data under
615 the fold
616 Content-Type: image/sgi
617 `)]);
618 await dingus._serveFileMetaHeaders(res, directory, fileName);
619 assert(res.setHeader.called);
620 });
621 }); // _serveFileMetaHeaders
622
623 describe('serveFile', function () {
624 const path = require('path');
625 let ctx, req, res, directory, fileName, filestats;
626 beforeEach(function () {
627 directory = path.join(__dirname, '..', 'test-data');
628 fileName = 'example.html';
629 ctx = {};
630 req = {
631 _headers: {
632 [Enum.Header.Accept]: undefined,
633 [Enum.Header.IfModifiedSince]: undefined,
634 [Enum.Header.AcceptEncoding]: undefined,
635 [Enum.Header.IfNoneMatch]: undefined,
636 },
637 getHeader: (header) => {
638 if (header in req._headers) {
639 // eslint-disable-next-line security/detect-object-injection
640 return req._headers[header];
641 }
642 assert.fail(`unexpected getHeader ${header}`);
643 },
644 };
645 res = {
646 end: sinon.stub(),
647 getHeader: sinon.stub(),
648 getHeaders: sinon.stub(),
649 hasHeader: sinon.stub().returns(true),
650 setHeader: sinon.stub(),
651 };
652 filestats = {
653 dev: 39,
654 mode: 33188,
655 nlink: 1,
656 uid: 1002,
657 gid: 1002,
658 rdev: 0,
659 blksize: 512,
660 ino: 897653,
661 size: 8,
662 blocks: 17,
663 atimeMs: 1613253436842.815,
664 mtimeMs: 1603485933192.8610,
665 ctimeMs: 1603485933192.8610,
666 birthtimeMs: 0,
667 atime: '2021-02-13T21:57:16.843Z',
668 mtime: '2020-10-23T13:45:33.193Z',
669 ctime: '2020-10-23T13:45:33.193Z',
670 birthtime: '1970-01-01T00:00:00.000Z',
671 };
672 sinon.stub(dingus, 'handlerNotFound');
673 sinon.stub(fs.promises, 'stat').resolves(filestats);
674 sinon.spy(fs.promises, 'readFile');
675 });
676 it('serves a file', async function () {
677 await dingus.serveFile(req, res, ctx, directory, fileName);
678 assert(fs.promises.readFile.called);
679 assert(!dingus.handlerNotFound.called);
680 });
681 it('covers no meta headers', async function () {
682 dingus.staticMetadata = false;
683 await dingus.serveFile(req, res, ctx, directory, fileName);
684 assert(fs.promises.readFile.called);
685 assert(!dingus.handlerNotFound.called);
686 });
687 it('does not serve dot-file', async function () {
688 fileName = '.example';
689 await dingus.serveFile(req, res, ctx, directory, fileName);
690 assert(!fs.promises.readFile.called);
691 assert(dingus.handlerNotFound.called);
692 });
693 it('does not serve encoded navigation', async function () {
694 fileName = '/example.html';
695 await dingus.serveFile(req, res, ctx, directory, fileName);
696 assert(!fs.promises.readFile.called);
697 assert(dingus.handlerNotFound.called);
698 });
699 it('does not serve missing file', async function () {
700 fileName = 'no-file.here';
701 await dingus.serveFile(req, res, ctx, directory, fileName);
702 assert(dingus.handlerNotFound.called);
703 });
704 it('covers fs error', async function () {
705 const expectedException = new Error('blah');
706 fs.promises.stat.restore();
707 sinon.stub(fs.promises, 'stat').rejects(expectedException);
708 try {
709 await dingus.serveFile(req, res, ctx, directory, fileName);
710 assert.fail('should have thrown');
711 } catch (e) {
712 assert.strictEqual(e, expectedException);
713 }
714 });
715 it('caches by modified', async function () {
716 req._headers[Enum.Header.IfModifiedSince] = 'Fri, 23 Oct 2020 23:11:16 GMT';
717 await dingus.serveFile(req, res, ctx, directory, fileName);
718 assert.strictEqual(res.statusCode, 304);
719 });
720 it('does not cache old modified', async function () {
721 req._headers[Enum.Header.IfModifiedSince] = 'Fri, 23 Oct 2020 01:11:16 GMT';
722 await dingus.serveFile(req, res, ctx, directory, fileName);
723 assert.notStrictEqual(res.statusCode, 304);
724 assert(!dingus.handlerNotFound.called);
725 });
726 it('caches ETag match', async function () {
727 req._headers[Enum.Header.IfNoneMatch] = '"zPPQVfXV36sgXq4fRLdsm+7rRMb8IUfb/eJ6N6mnwWs"';
728 await dingus.serveFile(req, res, ctx, directory, fileName);
729 assert.strictEqual(res.statusCode, 304);
730 });
731 it('does not cache ETag non-match', async function () {
732 req._headers[Enum.Header.IfNoneMatch] = '"foo", "bar"';
733 await dingus.serveFile(req, res, ctx, directory, fileName);
734 assert.notStrictEqual(res.statusCode, 304);
735 assert(!dingus.handlerNotFound.called);
736 });
737 it('handles no possible encodings', async function () {
738 req._headers[Enum.Header.AcceptEncoding] = '*;q=0';
739 await assert.rejects(async () => {
740 await dingus.serveFile(req, res, ctx, directory, fileName);
741 }, {
742 name: 'ResponseError',
743 });
744 });
745 it('handles a valid encoding', async function () {
746 req._headers[Enum.Header.AcceptEncoding] = 'gzip';
747 await dingus.serveFile(req, res, ctx, directory, fileName);
748 assert(res.end.called);
749 });
750 it('handles a valid encoding among others', async function () {
751 req._headers[Enum.Header.AcceptEncoding] = 'flarp, br, gzip';
752 fs.promises.stat.restore();
753 sinon.stub(fs.promises, 'stat')
754 .onCall(0).resolves(filestats) // identity file
755 .onCall(1).resolves(null) // br encoding
756 .onCall(2).resolves(filestats); // gzip encoding
757 await dingus.serveFile(req, res, ctx, directory, fileName);
758 assert(res.end.called);
759 });
760 }); // serveFile
761
762 describe('renderError', function () {
763 let err;
764 beforeEach(function () {
765 err = {
766 statusCode: '200',
767 errorMessage: 'OK',
768 details: 'hunkydorey',
769 };
770 });
771 it('renders unknown type', function () {
772 const contentType = 'unknown/type';
773 const result = dingus.renderError(contentType, err);
774 assert.deepStrictEqual(result, 'OK\r\nhunkydorey');
775 });
776 it('renders text', function () {
777 const contentType = 'text/plain';
778 const result = dingus.renderError(contentType, err);
779 assert.deepStrictEqual(result, 'OK\r\nhunkydorey');
780 });
781 it('renders json', function () {
782 const contentType = Enum.ContentType.ApplicationJson;
783 const result = dingus.renderError(contentType, err);
784 assert.deepStrictEqual(result, JSON.stringify(err));
785 });
786 it('renders html without details', function () {
787 err = {
788 statusCode: '201',
789 errorMessage: 'Created',
790 };
791 const contentType = 'text/html';
792 const result = dingus.renderError(contentType, err);
793 assert.deepStrictEqual(result, `<!DOCTYPE html>
794 <html lang="en">
795 <head>
796 <title>${err.statusCode} ${err.errorMessage}</title>
797 </head>
798 <body>
799 <h1>${err.errorMessage}</h1>
800 </body>
801 </html>`);
802 });
803 it('renders html', function () {
804 const contentType = 'text/html';
805 const result = dingus.renderError(contentType, err);
806 assert.deepStrictEqual(result, `<!DOCTYPE html>
807 <html lang="en">
808 <head>
809 <title>${err.statusCode} ${err.errorMessage}</title>
810 </head>
811 <body>
812 <h1>${err.errorMessage}</h1>
813 <p>${err.details}</p>
814 </body>
815 </html>`);
816 });
817 it('renders html, multiple details', function () {
818 const contentType = 'text/html';
819 err.details = ['one detail', 'two detail'];
820 const result = dingus.renderError(contentType, err);
821 assert.deepStrictEqual(result, `<!DOCTYPE html>
822 <html lang="en">
823 <head>
824 <title>${err.statusCode} ${err.errorMessage}</title>
825 </head>
826 <body>
827 <h1>${err.errorMessage}</h1>
828 <p>one detail</p>
829 <p>two detail</p>
830 </body>
831 </html>`);
832 });
833 }); // renderError
834
835 describe('sendErrorResponse', function () {
836 let ctx, req, res;
837 beforeEach(function () {
838 ctx = {};
839 req = {};
840 res = {
841 end: sinon.stub(),
842 getHeader: sinon.stub(),
843 getHeaders: sinon.stub(),
844 hasHeader: sinon.stub().returns(true),
845 setHeader: sinon.stub(),
846 };
847 sinon.stub(dingus, 'renderError');
848 });
849 it('covers', function () {
850 const err = {
851 statusCode: 444,
852 };
853 dingus.sendErrorResponse(err, req, res, ctx);
854 assert(res.end.called);
855 });
856 }); // sendErrorResponse
857
858 describe('proxyPrefix', function () {
859 let req, res, ctx, stubHandler, pfxDingus;
860 const pfx = '/pfx';
861
862 beforeEach(function () {
863 pfxDingus = new Dingus(console, { proxyPrefix: pfx });
864 req = {
865 setHeader: sinon.stub(),
866 getHeader: sinon.stub(),
867 };
868 res = {
869 statusCode: 200,
870 end: sinon.stub(),
871 setHeader: sinon.stub(),
872 getHeader: sinon.stub(),
873 };
874 ctx = {};
875 sinon.stub(pfxDingus, 'handlerMethodNotAllowed');
876 sinon.stub(pfxDingus, 'handlerNotFound');
877 stubHandler = sinon.stub();
878 });
879 afterEach(function () {
880 sinon.restore();
881 });
882
883 it('handles prefixed route', async function () {
884 const urlPath = '/:id';
885 const method = 'GET';
886 pfxDingus.on(method, urlPath, stubHandler);
887 req.url = pfx + '/abc';
888 req.method = method;
889
890 await pfxDingus.dispatch(req, res, ctx);
891 assert(stubHandler.called);
892 assert(!pfxDingus.handlerMethodNotAllowed.called);
893 assert(!pfxDingus.handlerNotFound.called);
894 });
895 it('does not handle prefixed route', async function () {
896 const urlPath = '/:id';
897 const method = 'GET';
898 pfxDingus.on(method, urlPath, stubHandler);
899 req.url = '/wrongpfx/abc';
900 req.method = method;
901
902 await pfxDingus.dispatch(req, res, ctx);
903 assert(!stubHandler.called);
904 assert(!pfxDingus.handlerMethodNotAllowed.called);
905 assert(pfxDingus.handlerNotFound.called);
906 });
907 }); // proxyPrefix
908 });