1 /* eslint-disable capitalized-comments */
5 const assert
= require('assert');
6 const sinon
= require('sinon'); // eslint-disable-line node/no-unpublished-require
7 const fs
= require('fs');
9 const Dingus
= require('../../lib/dingus');
10 const { DingusError
} = require('../../lib/errors');
11 const Enum
= require('../../lib/enum');
13 const noExpectedException
= 'did not get expected exception';
15 describe('Dingus', function () {
17 beforeEach(function () {
18 dingus
= new Dingus();
20 afterEach(function () {
24 describe('constructor', function () {
25 it('covers', function () {
26 const d
= new Dingus({}, {});
28 assert('log' in d
.logger
);
32 describe('_normalizePath', function () {
33 it('returns normal path', function () {
35 const r
= dingus
._normalizePath(p
);
36 assert
.strictEqual(r
, p
);
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
);
46 describe('_splitUrl', function () {
47 const nullObject
= Object
.create(null);
49 it('splits a simple path', function () {
53 queryParams: nullObject
,
55 const r
= dingus
._splitUrl(p
);
56 assert
.deepStrictEqual(r
, expected
);
58 it('splits a path with trailing slash preserved', function () {
62 queryParams: nullObject
,
64 const r
= dingus
._splitUrl(p
);
65 assert
.deepStrictEqual(r
, expected
);
67 it('splits a path with trailing slash ignored', function () {
71 queryParams: nullObject
,
73 dingus
.ignoreTrailingSlash
= true;
74 const r
= dingus
._splitUrl(p
);
75 assert
.deepStrictEqual(r
, expected
);
77 it('splits a path with empty query string', function () {
81 queryParams: nullObject
,
83 const r
= dingus
._splitUrl(p
);
84 assert
.deepStrictEqual(r
, expected
);
86 it('splits a path with query string', function () {
87 const p
= '/a/b/c?x=1&y=2&z';
90 queryParams: Object
.assign(Object
.create(null), {
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.
96 const r
= dingus
._splitUrl(p
);
97 assert
.deepStrictEqual(r
, expected
);
101 describe('tagContext', function () {
103 beforeEach(function () {
105 getHeader: sinon
.stub(),
106 setHeader: sinon
.stub(),
109 getHeader: sinon
.stub(),
110 setHeader: sinon
.stub(),
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
);
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);
130 describe('clientAddressContext', function () {
134 _tp
= dingus
.trustProxy
;
137 dingus
.trustProxy
= _tp
;
139 beforeEach(function () {
141 getHeader: sinon
.stub(),
142 setHeader: sinon
.stub(),
146 getHeader: sinon
.stub(),
147 setHeader: sinon
.stub(),
151 it ('covers untrusted proxy', function () {
152 dingus
.trustProxy
= false;
155 clientProtocol: 'http',
157 dingus
.clientAddressContext(req
, res
, ctx
);
158 assert
.deepStrictEqual(ctx
, expected
);
159 assert(!req
.getHeader
.called
);
161 it ('covers missing', function () {
162 dingus
.trustProxy
= true;
164 clientAddress: '::1',
165 clientProtocol: 'https',
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
);
173 }); // clientAddressContext
175 describe('getRequestContentType', function () {
177 beforeEach(function () {
179 getHeader: sinon
.stub(),
180 setHeader: sinon
.stub(),
183 it('handles missing header', function () {
184 const result
= Dingus
.getRequestContentType(req
);
185 assert
.strictEqual(result
, '');
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
);
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
);
197 }); // getRequestContentType
199 describe('setResponseContentType', function () {
200 let req
, responseTypes
;
201 beforeEach(function () {
204 setHeader: sinon
.stub(),
205 getHeader: sinon
.stub(),
208 it('handles missing header', function () {
209 const result
= Dingus
.getResponseContentType(responseTypes
, req
);
210 assert
.strictEqual(result
, undefined);
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
);
218 }); // setResponseContentType
220 describe('on', function () {
222 beforeEach(function () {
223 stubOn
= sinon
.stub(dingus
.router
, 'on');
225 it('covers', function () {
226 dingus
.on('GET', '/', () => {});
227 assert(stubOn
.called
);
231 describe('setEndBodyHandler', function () {
232 let req
, res
, ctx
, handler
, origEnd
, origWrite
;
233 beforeEach(function () {
234 origEnd
= sinon
.stub();
235 origWrite
= sinon
.stub();
242 handler
= sinon
.stub();
244 it('collects body and handles', function () {
245 Dingus
.setEndBodyHandler(req
, res
, ctx
, handler
);
246 res
.write(Buffer
.from('foo'));
250 assert(origWrite
.called
);
251 assert(origEnd
.called
);
252 assert
.deepStrictEqual(ctx
.responseBody
, Buffer
.from('foobazquux'));
253 assert(handler
.called
);
255 }); // setEndBodyHandler
257 describe('setHeadHandler', function () {
258 let req
, res
, ctx
, origEnd
, origWrite
;
259 beforeEach(function () {
260 origEnd
= sinon
.stub();
261 origWrite
= sinon
.stub();
268 setHeader: sinon
.stub(),
272 it('collects response without writing', function () {
273 Dingus
.setHeadHandler(req
, res
, ctx
);
274 res
.write(Buffer
.from('foo'));
278 assert(!origWrite
.called
);
279 assert(origEnd
.called
);
280 assert
.deepStrictEqual(ctx
.responseBody
, undefined);
282 it('collects response without writing, persists written data', function () {
283 Dingus
.setHeadHandler(req
, res
, ctx
, true);
284 res
.write(Buffer
.from('foo'));
288 assert(!origWrite
.called
);
289 assert(origEnd
.called
);
290 assert
.deepStrictEqual(ctx
.responseBody
, Buffer
.from('foobazquux'));
292 it('ignores non-head method', function () {
294 Dingus
.setHeadHandler(req
, res
, ctx
);
295 res
.write(Buffer
.from('foo'));
297 assert(origWrite
.called
);
298 assert(origEnd
.called
);
300 }); // setHeadHandler
302 describe('addEncodingHeader', function () {
304 beforeEach(function () {
307 // eslint-disable-next-line security/detect-object-injection
308 getHeader: (h
) => res
._headers
[h
],
309 // eslint-disable-next-line security/detect-object-injection
310 setHeader: (h
, v
) => res
._headers
[h
] = v
,
313 it('adds', function () {
315 Dingus
.addEncodingHeader(res
, encoding
);
316 assert
.strictEqual(res
._headers
[Enum
.Header
.ContentEncoding
], 'gzip');
318 it('extends', function () {
320 Dingus
.addEncodingHeader(res
, encoding
);
321 assert
.strictEqual(res
._headers
[Enum
.Header
.ContentEncoding
], 'utf8');
323 Dingus
.addEncodingHeader(res
, encoding
);
324 assert
.strictEqual(res
._headers
[Enum
.Header
.ContentEncoding
], 'gzip, utf8');
326 }); // addEncodingHeader
328 describe('dispatch', function () {
329 let pathsByLengthOrig
;
333 beforeEach(function () {
337 setHeader: sinon
.stub(),
338 getHeader: sinon
.stub(),
343 setHeader: sinon
.stub(),
344 hasHeader: sinon
.stub(),
345 getHeader: sinon
.stub(),
346 getHeaders: sinon
.stub(),
349 pathsByLengthOrig
= dingus
.pathsByLength
;
350 sinon
.spy(dingus
, 'handlerMethodNotAllowed');
351 sinon
.spy(dingus
, 'handlerNotFound');
352 sinon
.spy(dingus
, 'handlerBadRequest');
353 sinon
.spy(dingus
, 'handlerInternalServerError');
354 stubHandler
= sinon
.stub();
356 afterEach(function () {
357 dingus
.pathsByLength
= pathsByLengthOrig
;
360 it('calls handler', async
function () {
361 const urlPath
= '/:id';
362 const method
= 'GET';
363 dingus
.on(method
, urlPath
, stubHandler
);
367 await dingus
.dispatch(req
, res
, ctx
);
368 assert(stubHandler
.called
);
369 assert(!dingus
.handlerMethodNotAllowed
.called
);
370 assert(!dingus
.handlerNotFound
.called
);
372 it('calls handler without context', async
function () {
373 const urlPath
= '/:id';
374 const method
= 'GET';
375 dingus
.on(method
, urlPath
, stubHandler
);
379 await dingus
.dispatch(req
, res
);
380 assert(stubHandler
.called
);
381 assert(!dingus
.handlerMethodNotAllowed
.called
);
382 assert(!dingus
.handlerNotFound
.called
);
384 it('calls fallback handler', async
function () {
385 const urlPath
= '/abc/:id';
386 const method
= 'GET';
387 dingus
.on('*', urlPath
, stubHandler
);
388 req
.url
= '/abc/def';
391 await dingus
.dispatch(req
, res
, ctx
);
392 assert(stubHandler
.called
);
393 assert(!dingus
.handlerMethodNotAllowed
.called
);
394 assert(!dingus
.handlerNotFound
.called
);
396 it('handles error in handler', async
function () {
397 const urlPath
= '/:id';
398 const method
= 'GET';
399 dingus
.on(method
, urlPath
, stubHandler
);
402 stubHandler
.rejects(new Error('blah'));
404 await dingus
.dispatch(req
, res
, ctx
);
405 assert(stubHandler
.called
);
406 assert(!dingus
.handlerMethodNotAllowed
.called
);
407 assert(!dingus
.handlerNotFound
.called
);
409 it('calls unsupported method', async
function () {
410 const urlPath
= '/:id';
411 const method
= 'POST';
412 dingus
.on('GET', urlPath
, stubHandler
);
416 await dingus
.dispatch(req
, res
, ctx
);
417 assert(!stubHandler
.called
);
418 assert(dingus
.handlerMethodNotAllowed
.called
);
419 assert(!dingus
.handlerNotFound
.called
);
421 it('does not lookup nonexistent path', async
function () {
422 req
.url
= '/foo/bar';
425 await dingus
.dispatch(req
, res
, ctx
);
426 assert(!stubHandler
.called
);
427 assert(!dingus
.handlerMethodNotAllowed
.called
);
428 assert(dingus
.handlerNotFound
.called
);
430 it('covers unhandled dingus exception', async
function () {
431 const expectedException
= new DingusError('blah');
432 sinon
.stub(dingus
.router
, 'lookup').throws(expectedException
);
434 await dingus
.dispatch(req
, res
, ctx
);
435 assert(!stubHandler
.called
);
436 assert(dingus
.handlerInternalServerError
.called
);
438 it('covers other exception', async
function () {
439 const expectedException
= new Error('blah');
440 sinon
.stub(dingus
.router
, 'lookup').throws(expectedException
);
442 await dingus
.dispatch(req
, res
, ctx
);
443 assert(!stubHandler
.called
);
444 assert(dingus
.handlerInternalServerError
.called
);
446 it('covers bad uri', async
function () {
449 await dingus
.dispatch(req
, res
, ctx
);
450 assert(dingus
.handlerBadRequest
.called
);
452 it('calls handler with additional arguments', async
function () {
453 dingus
.on('GET', '/', stubHandler
, 'foo', 'bar');
454 await dingus
.dispatch(req
, res
, ctx
);
455 assert(stubHandler
.called
);
456 assert
.strictEqual(stubHandler
.args
[0][3], 'foo');
457 assert
.strictEqual(stubHandler
.args
[0][4], 'bar');
461 describe('parseBody', function () {
463 beforeEach(function () {
466 it('does not parse unknown type', function () {
468 dingus
.parseBody('unknown/type', ctx
);
469 assert
.fail(noExpectedException
);
471 assert
.strictEqual(e
.statusCode
, 415);
474 it('parses json', function () {
475 const src
= { foo: 'bar' };
476 ctx
.rawBody
= JSON
.stringify(src
);
477 dingus
.parseBody(Enum
.ContentType
.ApplicationJson
, ctx
);
478 assert
.deepStrictEqual(ctx
.parsedBody
, src
);
480 it('handles unparsable json', function () {
481 ctx
.rawBody
= 'not json';
483 dingus
.parseBody(Enum
.ContentType
.ApplicationJson
, ctx
);
484 assert
.fail(noExpectedException
);
486 assert
.strictEqual(e
.statusCode
, 400);
489 it('parses form', function () {
490 const expected
= Object
.assign(Object
.create(null), {
493 ctx
.rawBody
= 'foo=bar';
494 dingus
.parseBody('application/x-www-form-urlencoded', ctx
);
495 assert
.deepStrictEqual(ctx
.parsedBody
, expected
);
500 describe('bodyData', function () {
502 beforeEach(function () {
505 // eslint-disable-next-line security/detect-object-injection
506 on: (ev
, fn
) => resEvents
[ev
] = fn
,
509 it('provides data', async
function () {
510 const p
= dingus
.bodyData(res
);
511 resEvents
['data'](Buffer
.from('foo'));
512 resEvents
['data'](Buffer
.from('bar'));
514 const result
= await p
;
515 assert
.strictEqual(result
, 'foobar');
517 it('handles error', async
function () {
518 const p
= dingus
.bodyData(res
);
519 resEvents
['error']('foo');
522 assert
.fail(noExpectedException
);
524 assert
.strictEqual(e
, 'foo');
527 it('limits size', async
function () {
528 const p
= dingus
.bodyData(res
, 8);
529 resEvents
['data'](Buffer
.from('foobar'));
530 resEvents
['data'](Buffer
.from('bazquux'));
533 assert
.fail(noExpectedException
);
535 assert
.strictEqual(e
.statusCode
, 413);
540 describe('ingestBody', function () {
541 it('ingests json', async
function () {
545 sinon
.stub(dingus
, 'bodyData').resolves('{"foo":"bar"}')
546 sinon
.stub(Dingus
, 'getRequestContentType').returns(Enum
.ContentType
.ApplicationJson
);
547 await dingus
.ingestBody(req
, res
, ctx
);
548 assert
.deepStrictEqual(ctx
.parsedBody
, { foo: 'bar' });
549 assert
.deepStrictEqual(ctx
.rawBody
, undefined);
551 it('persists rawBody', async
function () {
555 const body
= '{"foo":"bar"}';
556 sinon
.stub(dingus
, 'bodyData').resolves(body
);
557 sinon
.stub(Dingus
, 'getRequestContentType').returns(Enum
.ContentType
.ApplicationJson
);
558 await dingus
.ingestBody(req
, res
, ctx
, { persistRawBody: true });
559 assert
.deepStrictEqual(ctx
.parsedBody
, { foo: 'bar' });
560 assert
.deepStrictEqual(ctx
.rawBody
, body
);
562 it('skips parsing empty body', async
function () {
567 sinon
.stub(dingus
, 'bodyData').resolves(body
);
568 sinon
.stub(Dingus
, 'getRequestContentType').returns(Enum
.ContentType
.ApplicationJson
);
569 sinon
.spy(dingus
, 'parseBody');
570 await dingus
.ingestBody(req
, res
, ctx
, { parseEmptyBody: false });
571 assert
.deepStrictEqual(ctx
.parsedBody
, undefined);
572 assert(dingus
.parseBody
.notCalled
);
576 describe('setResponseType', function () {
578 let _sa
; // Preserve strictAccept
580 _sa
= dingus
.strictAccept
;
583 dingus
.strictAccept
= _sa
;
585 beforeEach(function () {
589 setHeader: sinon
.stub(),
591 sinon
.stub(Dingus
, 'getResponseContentType').returns();
593 it('rejects missing', function () {
594 dingus
.strictAccept
= true;
596 dingus
.setResponseType(['my/type'], req
, res
, ctx
);
597 assert
.fail(noExpectedException
);
599 assert
.strictEqual(e
.statusCode
, 406, 'did not get expected status code');
602 it('accepts missing', function () {
603 dingus
.strictAccept
= false;
604 dingus
.setResponseType(['my/type'], req
, res
, ctx
);
605 assert
.strictEqual(ctx
.responseType
, 'my/type');
608 }); // setResponseType
610 describe('_readFileInfo', function () {
611 let stat
, data
, statRes
, dataRes
, filename
;
612 beforeEach(function () {
613 sinon
.stub(fs
.promises
, 'stat');
614 sinon
.stub(fs
.promises
, 'readFile');
616 mtimeMs:1612553697186,
619 filename
= 'dummy.txt';
621 it('succeeds', async
function () {
622 fs
.promises
.stat
.resolves(statRes
);
623 fs
.promises
.readFile
.resolves('data');
624 [stat
, data
] = await dingus
._readFileInfo(filename
);
625 assert
.deepStrictEqual(stat
, statRes
);
626 assert
.deepStrictEqual(data
, dataRes
);
628 it('returns null for non-existant file', async
function () {
632 fs
.promises
.stat
.rejects(noEnt
);
633 fs
.promises
.readFile
.rejects(noEnt
);
634 [stat
, data
] = await dingus
._readFileInfo(filename
);
635 assert
.strictEqual(stat
, null);
636 assert
.strictEqual(data
, null);
638 it('throws unexpected error', async
function () {
639 const expectedException
= new Error('blah');
640 fs
.promises
.stat
.rejects(expectedException
);
641 await assert
.rejects(async () => {
642 await dingus
._readFileInfo(filename
);
643 }, expectedException
);
647 describe('_serveFileMetaHeaders', function () {
648 let res
, directory
, fileName
;
649 beforeEach(function () {
650 sinon
.stub(dingus
, '_readFileInfo');
652 setHeader: sinon
.stub(),
655 fileName
= 'filename';
657 it('covers no meta file', async
function() {
658 dingus
._readFileInfo
.resolves([null, null]);
659 await dingus
._serveFileMetaHeaders(res
, directory
, fileName
);
660 assert(!res
.setHeader
.called
);
662 it('adds extra headers', async
function () {
663 dingus
._readFileInfo
.resolves([{}, Buffer
.from(`Link: <https://example.com/>; rel="relation"
664 X-Folded-Header: data
667 Content-Type: image/sgi
669 await dingus
._serveFileMetaHeaders(res
, directory
, fileName
);
670 assert(res
.setHeader
.called
);
672 }); // _serveFileMetaHeaders
674 describe('serveFile', function () {
675 const path
= require('path');
676 let ctx
, req
, res
, directory
, fileName
, filestats
;
677 beforeEach(function () {
678 directory
= path
.join(__dirname
, '..', 'test-data');
679 fileName
= 'example.html';
683 [Enum
.Header
.Accept
]: undefined,
684 [Enum
.Header
.IfModifiedSince
]: undefined,
685 [Enum
.Header
.AcceptEncoding
]: undefined,
686 [Enum
.Header
.IfNoneMatch
]: undefined,
688 getHeader: (header
) => {
689 if (header
in req
._headers
) {
690 // eslint-disable-next-line security/detect-object-injection
691 return req
._headers
[header
];
693 assert
.fail(`unexpected getHeader ${header}`);
698 getHeader: sinon
.stub(),
699 getHeaders: sinon
.stub(),
700 hasHeader: sinon
.stub().returns(true),
701 setHeader: sinon
.stub(),
714 atimeMs: 1613253436842.815,
715 mtimeMs: 1603485933192.861,
716 ctimeMs: 1603485933192.861,
718 atime: '2021-02-13T21:57:16.843Z',
719 mtime: '2020-10-23T13:45:33.193Z',
720 ctime: '2020-10-23T13:45:33.193Z',
721 birthtime: '1970-01-01T00:00:00.000Z',
723 sinon
.stub(dingus
, 'handlerNotFound');
724 sinon
.stub(fs
.promises
, 'stat').resolves(filestats
);
725 sinon
.spy(fs
.promises
, 'readFile');
727 it('serves a file', async
function () {
728 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
729 assert(fs
.promises
.readFile
.called
);
730 assert(!dingus
.handlerNotFound
.called
);
732 it('covers no meta headers', async
function () {
733 dingus
.staticMetadata
= false;
734 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
735 assert(fs
.promises
.readFile
.called
);
736 assert(!dingus
.handlerNotFound
.called
);
738 it('does not serve dot-file', async
function () {
739 fileName
= '.example';
740 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
741 assert(!fs
.promises
.readFile
.called
);
742 assert(dingus
.handlerNotFound
.called
);
744 it('does not serve encoded navigation', async
function () {
745 fileName
= '/example.html';
746 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
747 assert(!fs
.promises
.readFile
.called
);
748 assert(dingus
.handlerNotFound
.called
);
750 it('does not serve missing file', async
function () {
751 fileName
= 'no-file.here';
752 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
753 assert(dingus
.handlerNotFound
.called
);
755 it('requires directory be specified', async
function () {
756 await dingus
.serveFile(req
, res
, ctx
, '', fileName
);
757 assert(!fs
.promises
.readFile
.called
);
758 assert(dingus
.handlerNotFound
.called
);
760 it('covers fs error', async
function () {
761 const expectedException
= new Error('blah');
762 fs
.promises
.stat
.restore();
763 sinon
.stub(fs
.promises
, 'stat').rejects(expectedException
);
765 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
766 assert
.fail('should have thrown');
768 assert
.strictEqual(e
, expectedException
);
771 it('caches by modified', async
function () {
772 req
._headers
[Enum
.Header
.IfModifiedSince
] = 'Fri, 23 Oct 2020 23:11:16 GMT';
773 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
774 assert
.strictEqual(res
.statusCode
, 304);
776 it('does not cache old modified', async
function () {
777 req
._headers
[Enum
.Header
.IfModifiedSince
] = 'Fri, 23 Oct 2020 01:11:16 GMT';
778 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
779 assert
.notStrictEqual(res
.statusCode
, 304);
780 assert(!dingus
.handlerNotFound
.called
);
782 it('caches ETag match', async
function () {
783 req
._headers
[Enum
.Header
.IfNoneMatch
] = '"zPPQVfXV36sgXq4fRLdsm+7rRMb8IUfb/eJ6N6mnwWs"';
784 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
785 assert
.strictEqual(res
.statusCode
, 304);
787 it('does not cache ETag non-match', async
function () {
788 req
._headers
[Enum
.Header
.IfNoneMatch
] = '"foo", "bar"';
789 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
790 assert
.notStrictEqual(res
.statusCode
, 304);
791 assert(!dingus
.handlerNotFound
.called
);
793 it('handles no possible encodings', async
function () {
794 req
._headers
[Enum
.Header
.AcceptEncoding
] = '*;q=0';
795 await assert
.rejects(async () => {
796 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
798 name: 'ResponseError',
801 it('handles a valid encoding', async
function () {
802 req
._headers
[Enum
.Header
.AcceptEncoding
] = 'gzip';
803 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
804 assert(res
.end
.called
);
806 it('handles a valid encoding among others', async
function () {
807 req
._headers
[Enum
.Header
.AcceptEncoding
] = 'flarp, br, gzip';
808 fs
.promises
.stat
.restore();
809 sinon
.stub(fs
.promises
, 'stat')
810 .onCall(0).resolves(filestats
) // identity file
811 .onCall(1).resolves(null) // br encoding
812 .onCall(2).resolves(filestats
); // gzip encoding
813 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
814 assert(res
.end
.called
);
818 describe('renderError', function () {
820 beforeEach(function () {
824 details: 'hunkydorey',
827 it('renders unknown type', function () {
828 const contentType
= 'unknown/type';
829 const result
= dingus
.renderError(contentType
, err
);
830 assert
.deepStrictEqual(result
, 'OK\r\nhunkydorey');
832 it('renders text', function () {
833 const contentType
= 'text/plain';
834 const result
= dingus
.renderError(contentType
, err
);
835 assert
.deepStrictEqual(result
, 'OK\r\nhunkydorey');
837 it('renders json', function () {
838 const contentType
= Enum
.ContentType
.ApplicationJson
;
839 const result
= dingus
.renderError(contentType
, err
);
840 assert
.deepStrictEqual(result
, JSON
.stringify(err
));
842 it('renders html without details', function () {
845 errorMessage: 'Created',
847 const contentType
= 'text/html';
848 const result
= dingus
.renderError(contentType
, err
);
849 assert
.deepStrictEqual(result
, `<!DOCTYPE html>
852 <title>${err.statusCode} ${err.errorMessage}</title>
855 <h1>${err.errorMessage}</h1>
859 it('renders html', function () {
860 const contentType
= 'text/html';
861 const result
= dingus
.renderError(contentType
, err
);
862 assert
.deepStrictEqual(result
, `<!DOCTYPE html>
865 <title>${err.statusCode} ${err.errorMessage}</title>
868 <h1>${err.errorMessage}</h1>
869 <p>${err.details}</p>
873 it('renders html, multiple details', function () {
874 const contentType
= 'text/html';
875 err
.details
= ['one detail', 'two detail'];
876 const result
= dingus
.renderError(contentType
, err
);
877 assert
.deepStrictEqual(result
, `<!DOCTYPE html>
880 <title>${err.statusCode} ${err.errorMessage}</title>
883 <h1>${err.errorMessage}</h1>
891 describe('sendErrorResponse', function () {
893 beforeEach(function () {
898 getHeader: sinon
.stub(),
899 getHeaders: sinon
.stub(),
900 hasHeader: sinon
.stub().returns(true),
901 setHeader: sinon
.stub(),
903 sinon
.stub(dingus
, 'renderError');
905 it('covers', function () {
909 dingus
.sendErrorResponse(err
, req
, res
, ctx
);
910 assert(res
.end
.called
);
912 }); // sendErrorResponse
914 describe('proxyPrefix', function () {
915 let req
, res
, ctx
, stubHandler
, pfxDingus
;
918 beforeEach(function () {
919 pfxDingus
= new Dingus(console
, { proxyPrefix: pfx
});
921 setHeader: sinon
.stub(),
922 getHeader: sinon
.stub(),
927 setHeader: sinon
.stub(),
928 getHeader: sinon
.stub(),
931 sinon
.stub(pfxDingus
, 'handlerMethodNotAllowed');
932 sinon
.stub(pfxDingus
, 'handlerNotFound');
933 stubHandler
= sinon
.stub();
935 afterEach(function () {
939 it('handles prefixed route', async
function () {
940 const urlPath
= '/:id';
941 const method
= 'GET';
942 pfxDingus
.on(method
, urlPath
, stubHandler
);
943 req
.url
= pfx
+ '/abc';
946 await pfxDingus
.dispatch(req
, res
, ctx
);
947 assert(stubHandler
.called
);
948 assert(!pfxDingus
.handlerMethodNotAllowed
.called
);
949 assert(!pfxDingus
.handlerNotFound
.called
);
951 it('does not handle prefixed route', async
function () {
952 const urlPath
= '/:id';
953 const method
= 'GET';
954 pfxDingus
.on(method
, urlPath
, stubHandler
);
955 req
.url
= '/wrongpfx/abc';
958 await pfxDingus
.dispatch(req
, res
, ctx
);
959 assert(!stubHandler
.called
);
960 assert(!pfxDingus
.handlerMethodNotAllowed
.called
);
961 assert(pfxDingus
.handlerNotFound
.called
);
965 describe('handlerRedirect', function () {
967 beforeEach(function () {
969 getHeader: sinon
.stub(),
972 setHeader: sinon
.stub(),
977 it('covers', async
function () {
978 await dingus
.handlerRedirect(req
, res
, ctx
);
979 assert(res
.setHeader
.called
);
980 assert(res
.end
.called
);
982 it('covers non-defaults', async
function () {
983 await dingus
.handlerRedirect(req
, res
, ctx
, 308);
984 assert(res
.setHeader
.called
);
985 assert(res
.end
.called
);
987 }); // handlerRedirect
989 describe('handlerGetStaticFile', function () {
991 beforeEach(function () {
993 getHeader: sinon
.stub(),
996 setHeader: sinon
.stub(),
1003 sinon
.stub(dingus
, 'serveFile');
1005 it('covers', async
function () {
1006 await dingus
.handlerGetStaticFile(req
, res
, ctx
);
1007 assert(dingus
.serveFile
.called
);
1009 it('covers specified file', async
function () {
1010 await dingus
.handlerGetStaticFile(req
, res
, ctx
, 'file.txt');
1011 assert(dingus
.serveFile
.called
);
1013 }); // handlerGetStaticFile