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 body 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
, Buffer
.from('foobazquux'));
282 it('ignores non-head method', function () {
284 Dingus
.setHeadHandler(req
, res
, ctx
);
285 res
.write(Buffer
.from('foo'));
287 assert(origWrite
.called
);
288 assert(origEnd
.called
);
290 }); // setHeadHandler
292 describe('addEncodingHeader', function () {
294 beforeEach(function () {
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
,
303 it('adds', function () {
305 Dingus
.addEncodingHeader(res
, encoding
);
306 assert
.strictEqual(res
._headers
[Enum
.Header
.ContentEncoding
], 'gzip');
308 it('extends', function () {
310 Dingus
.addEncodingHeader(res
, encoding
);
311 assert
.strictEqual(res
._headers
[Enum
.Header
.ContentEncoding
], 'utf8');
313 Dingus
.addEncodingHeader(res
, encoding
);
314 assert
.strictEqual(res
._headers
[Enum
.Header
.ContentEncoding
], 'gzip, utf8');
316 }); // addEncodingHeader
318 describe('dispatch', function () {
319 let pathsByLengthOrig
;
323 beforeEach(function () {
327 setHeader: sinon
.stub(),
328 getHeader: sinon
.stub(),
333 setHeader: sinon
.stub(),
334 hasHeader: sinon
.stub(),
335 getHeader: sinon
.stub(),
336 getHeaders: sinon
.stub(),
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();
346 afterEach(function () {
347 dingus
.pathsByLength
= pathsByLengthOrig
;
350 it('calls handler', async
function () {
351 const urlPath
= '/:id';
352 const method
= 'GET';
353 dingus
.on(method
, urlPath
, stubHandler
);
357 await dingus
.dispatch(req
, res
, ctx
);
358 assert(stubHandler
.called
);
359 assert(!dingus
.handlerMethodNotAllowed
.called
);
360 assert(!dingus
.handlerNotFound
.called
);
362 it('calls handler without context', async
function () {
363 const urlPath
= '/:id';
364 const method
= 'GET';
365 dingus
.on(method
, urlPath
, stubHandler
);
369 await dingus
.dispatch(req
, res
);
370 assert(stubHandler
.called
);
371 assert(!dingus
.handlerMethodNotAllowed
.called
);
372 assert(!dingus
.handlerNotFound
.called
);
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';
381 await dingus
.dispatch(req
, res
, ctx
);
382 assert(stubHandler
.called
);
383 assert(!dingus
.handlerMethodNotAllowed
.called
);
384 assert(!dingus
.handlerNotFound
.called
);
386 it('handles error in handler', async
function () {
387 const urlPath
= '/:id';
388 const method
= 'GET';
389 dingus
.on(method
, urlPath
, stubHandler
);
392 stubHandler
.rejects(new Error('blah'));
394 await dingus
.dispatch(req
, res
, ctx
);
395 assert(stubHandler
.called
);
396 assert(!dingus
.handlerMethodNotAllowed
.called
);
397 assert(!dingus
.handlerNotFound
.called
);
399 it('calls unsupported method', async
function () {
400 const urlPath
= '/:id';
401 const method
= 'POST';
402 dingus
.on('GET', urlPath
, stubHandler
);
406 await dingus
.dispatch(req
, res
, ctx
);
407 assert(!stubHandler
.called
);
408 assert(dingus
.handlerMethodNotAllowed
.called
);
409 assert(!dingus
.handlerNotFound
.called
);
411 it('does not lookup nonexistent path', async
function () {
412 req
.url
= '/foo/bar';
415 await dingus
.dispatch(req
, res
, ctx
);
416 assert(!stubHandler
.called
);
417 assert(!dingus
.handlerMethodNotAllowed
.called
);
418 assert(dingus
.handlerNotFound
.called
);
420 it('covers unhandled dingus exception', async
function () {
421 const expectedException
= new DingusError('blah');
422 sinon
.stub(dingus
.router
, 'lookup').throws(expectedException
);
424 await dingus
.dispatch(req
, res
, ctx
);
425 assert(!stubHandler
.called
);
426 assert(dingus
.handlerInternalServerError
.called
);
428 it('covers other exception', async
function () {
429 const expectedException
= new Error('blah');
430 sinon
.stub(dingus
.router
, 'lookup').throws(expectedException
);
432 await dingus
.dispatch(req
, res
, ctx
);
433 assert(!stubHandler
.called
);
434 assert(dingus
.handlerInternalServerError
.called
);
436 it('covers bad uri', async
function () {
439 await dingus
.dispatch(req
, res
, ctx
);
440 assert(dingus
.handlerBadRequest
.called
);
442 it('calls handler with additional arguments', async
function () {
443 dingus
.on('GET', '/', stubHandler
, 'foo', 'bar');
444 await dingus
.dispatch(req
, res
, ctx
);
445 assert(stubHandler
.called
);
446 assert
.strictEqual(stubHandler
.args
[0][3], 'foo');
447 assert
.strictEqual(stubHandler
.args
[0][4], 'bar');
451 describe('parseBody', function () {
453 beforeEach(function () {
456 it('does not parse unknown type', function () {
458 dingus
.parseBody('unknown/type', ctx
);
459 assert
.fail(noExpectedException
);
461 assert
.strictEqual(e
.statusCode
, 415);
464 it('parses json', function () {
465 const src
= { foo: 'bar' };
466 ctx
.rawBody
= JSON
.stringify(src
);
467 dingus
.parseBody(Enum
.ContentType
.ApplicationJson
, ctx
);
468 assert
.deepStrictEqual(ctx
.parsedBody
, src
);
470 it('handles unparsable json', function () {
471 ctx
.rawBody
= 'not json';
473 dingus
.parseBody(Enum
.ContentType
.ApplicationJson
, ctx
);
474 assert
.fail(noExpectedException
);
476 assert
.strictEqual(e
.statusCode
, 400);
479 it('parses form', function () {
480 const expected
= Object
.assign(Object
.create(null), {
483 ctx
.rawBody
= 'foo=bar';
484 dingus
.parseBody('application/x-www-form-urlencoded', ctx
);
485 assert
.deepStrictEqual(ctx
.parsedBody
, expected
);
490 describe('bodyData', function () {
492 beforeEach(function () {
495 // eslint-disable-next-line security/detect-object-injection
496 on: (ev
, fn
) => resEvents
[ev
] = fn
,
499 it('provides data', async
function () {
500 const p
= dingus
.bodyData(res
);
501 resEvents
['data'](Buffer
.from('foo'));
502 resEvents
['data'](Buffer
.from('bar'));
504 const result
= await p
;
505 assert
.strictEqual(result
, 'foobar');
507 it('handles error', async
function () {
508 const p
= dingus
.bodyData(res
);
509 resEvents
['error']('foo');
512 assert
.fail(noExpectedException
);
514 assert
.strictEqual(e
, 'foo');
519 describe('ingestBody', function () {
520 it('covers', async
function () {
524 sinon
.stub(dingus
, 'bodyData').resolves('{"foo":"bar"}')
525 sinon
.stub(Dingus
, 'getRequestContentType').returns(Enum
.ContentType
.ApplicationJson
);
526 await dingus
.ingestBody(req
, res
, ctx
);
527 assert
.deepStrictEqual(ctx
.parsedBody
, { foo: 'bar' });
531 describe('setResponseType', function () {
533 let _sa
; // Preserve strictAccept
535 _sa
= dingus
.strictAccept
;
538 dingus
.strictAccept
= _sa
;
540 beforeEach(function () {
544 setHeader: sinon
.stub(),
546 sinon
.stub(Dingus
, 'getResponseContentType').returns();
548 it('rejects missing', function () {
549 dingus
.strictAccept
= true;
551 dingus
.setResponseType(['my/type'], req
, res
, ctx
);
552 assert
.fail(noExpectedException
);
554 assert
.strictEqual(e
.statusCode
, 406, 'did not get expected status code');
557 it('accepts missing', function () {
558 dingus
.strictAccept
= false;
559 dingus
.setResponseType(['my/type'], req
, res
, ctx
);
560 assert
.strictEqual(ctx
.responseType
, 'my/type');
563 }); // setResponseType
565 describe('_readFileInfo', function () {
566 let stat
, data
, statRes
, dataRes
, filename
;
567 beforeEach(function () {
568 sinon
.stub(fs
.promises
, 'stat');
569 sinon
.stub(fs
.promises
, 'readFile');
571 mtimeMs:1612553697186,
574 filename
= 'dummy.txt';
576 it('succeeds', async
function () {
577 fs
.promises
.stat
.resolves(statRes
);
578 fs
.promises
.readFile
.resolves('data');
579 [stat
, data
] = await dingus
._readFileInfo(filename
);
580 assert
.deepStrictEqual(stat
, statRes
);
581 assert
.deepStrictEqual(data
, dataRes
);
583 it('returns null for non-existant file', async
function () {
587 fs
.promises
.stat
.rejects(noEnt
);
588 fs
.promises
.readFile
.rejects(noEnt
);
589 [stat
, data
] = await dingus
._readFileInfo(filename
);
590 assert
.strictEqual(stat
, null);
591 assert
.strictEqual(data
, null);
593 it('throws unexpected error', async
function () {
594 const expectedException
= new Error('blah');
595 fs
.promises
.stat
.rejects(expectedException
);
596 await assert
.rejects(async () => {
597 await dingus
._readFileInfo(filename
);
598 }, expectedException
);
602 describe('_serveFileMetaHeaders', function () {
603 let res
, directory
, fileName
;
604 beforeEach(function () {
605 sinon
.stub(dingus
, '_readFileInfo');
607 setHeader: sinon
.stub(),
610 fileName
= 'filename';
612 it('covers no meta file', async
function() {
613 dingus
._readFileInfo
.resolves([null, null]);
614 await dingus
._serveFileMetaHeaders(res
, directory
, fileName
);
615 assert(!res
.setHeader
.called
);
617 it('adds extra headers', async
function () {
618 dingus
._readFileInfo
.resolves([{}, Buffer
.from(`Link: <https://example.com/>; rel="relation"
619 X-Folded-Header: data
622 Content-Type: image/sgi
624 await dingus
._serveFileMetaHeaders(res
, directory
, fileName
);
625 assert(res
.setHeader
.called
);
627 }); // _serveFileMetaHeaders
629 describe('serveFile', function () {
630 const path
= require('path');
631 let ctx
, req
, res
, directory
, fileName
, filestats
;
632 beforeEach(function () {
633 directory
= path
.join(__dirname
, '..', 'test-data');
634 fileName
= 'example.html';
638 [Enum
.Header
.Accept
]: undefined,
639 [Enum
.Header
.IfModifiedSince
]: undefined,
640 [Enum
.Header
.AcceptEncoding
]: undefined,
641 [Enum
.Header
.IfNoneMatch
]: undefined,
643 getHeader: (header
) => {
644 if (header
in req
._headers
) {
645 // eslint-disable-next-line security/detect-object-injection
646 return req
._headers
[header
];
648 assert
.fail(`unexpected getHeader ${header}`);
653 getHeader: sinon
.stub(),
654 getHeaders: sinon
.stub(),
655 hasHeader: sinon
.stub().returns(true),
656 setHeader: sinon
.stub(),
669 atimeMs: 1613253436842.815,
670 mtimeMs: 1603485933192.861,
671 ctimeMs: 1603485933192.861,
673 atime: '2021-02-13T21:57:16.843Z',
674 mtime: '2020-10-23T13:45:33.193Z',
675 ctime: '2020-10-23T13:45:33.193Z',
676 birthtime: '1970-01-01T00:00:00.000Z',
678 sinon
.stub(dingus
, 'handlerNotFound');
679 sinon
.stub(fs
.promises
, 'stat').resolves(filestats
);
680 sinon
.spy(fs
.promises
, 'readFile');
682 it('serves a file', async
function () {
683 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
684 assert(fs
.promises
.readFile
.called
);
685 assert(!dingus
.handlerNotFound
.called
);
687 it('covers no meta headers', async
function () {
688 dingus
.staticMetadata
= false;
689 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
690 assert(fs
.promises
.readFile
.called
);
691 assert(!dingus
.handlerNotFound
.called
);
693 it('does not serve dot-file', async
function () {
694 fileName
= '.example';
695 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
696 assert(!fs
.promises
.readFile
.called
);
697 assert(dingus
.handlerNotFound
.called
);
699 it('does not serve encoded navigation', async
function () {
700 fileName
= '/example.html';
701 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
702 assert(!fs
.promises
.readFile
.called
);
703 assert(dingus
.handlerNotFound
.called
);
705 it('does not serve missing file', async
function () {
706 fileName
= 'no-file.here';
707 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
708 assert(dingus
.handlerNotFound
.called
);
710 it('requires directory be specified', async
function () {
711 await dingus
.serveFile(req
, res
, ctx
, '', fileName
);
712 assert(!fs
.promises
.readFile
.called
);
713 assert(dingus
.handlerNotFound
.called
);
715 it('covers fs error', async
function () {
716 const expectedException
= new Error('blah');
717 fs
.promises
.stat
.restore();
718 sinon
.stub(fs
.promises
, 'stat').rejects(expectedException
);
720 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
721 assert
.fail('should have thrown');
723 assert
.strictEqual(e
, expectedException
);
726 it('caches by modified', async
function () {
727 req
._headers
[Enum
.Header
.IfModifiedSince
] = 'Fri, 23 Oct 2020 23:11:16 GMT';
728 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
729 assert
.strictEqual(res
.statusCode
, 304);
731 it('does not cache old modified', async
function () {
732 req
._headers
[Enum
.Header
.IfModifiedSince
] = 'Fri, 23 Oct 2020 01:11:16 GMT';
733 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
734 assert
.notStrictEqual(res
.statusCode
, 304);
735 assert(!dingus
.handlerNotFound
.called
);
737 it('caches ETag match', async
function () {
738 req
._headers
[Enum
.Header
.IfNoneMatch
] = '"zPPQVfXV36sgXq4fRLdsm+7rRMb8IUfb/eJ6N6mnwWs"';
739 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
740 assert
.strictEqual(res
.statusCode
, 304);
742 it('does not cache ETag non-match', async
function () {
743 req
._headers
[Enum
.Header
.IfNoneMatch
] = '"foo", "bar"';
744 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
745 assert
.notStrictEqual(res
.statusCode
, 304);
746 assert(!dingus
.handlerNotFound
.called
);
748 it('handles no possible encodings', async
function () {
749 req
._headers
[Enum
.Header
.AcceptEncoding
] = '*;q=0';
750 await assert
.rejects(async () => {
751 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
753 name: 'ResponseError',
756 it('handles a valid encoding', async
function () {
757 req
._headers
[Enum
.Header
.AcceptEncoding
] = 'gzip';
758 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
759 assert(res
.end
.called
);
761 it('handles a valid encoding among others', async
function () {
762 req
._headers
[Enum
.Header
.AcceptEncoding
] = 'flarp, br, gzip';
763 fs
.promises
.stat
.restore();
764 sinon
.stub(fs
.promises
, 'stat')
765 .onCall(0).resolves(filestats
) // identity file
766 .onCall(1).resolves(null) // br encoding
767 .onCall(2).resolves(filestats
); // gzip encoding
768 await dingus
.serveFile(req
, res
, ctx
, directory
, fileName
);
769 assert(res
.end
.called
);
773 describe('renderError', function () {
775 beforeEach(function () {
779 details: 'hunkydorey',
782 it('renders unknown type', function () {
783 const contentType
= 'unknown/type';
784 const result
= dingus
.renderError(contentType
, err
);
785 assert
.deepStrictEqual(result
, 'OK\r\nhunkydorey');
787 it('renders text', function () {
788 const contentType
= 'text/plain';
789 const result
= dingus
.renderError(contentType
, err
);
790 assert
.deepStrictEqual(result
, 'OK\r\nhunkydorey');
792 it('renders json', function () {
793 const contentType
= Enum
.ContentType
.ApplicationJson
;
794 const result
= dingus
.renderError(contentType
, err
);
795 assert
.deepStrictEqual(result
, JSON
.stringify(err
));
797 it('renders html without details', function () {
800 errorMessage: 'Created',
802 const contentType
= 'text/html';
803 const result
= dingus
.renderError(contentType
, err
);
804 assert
.deepStrictEqual(result
, `<!DOCTYPE html>
807 <title>${err.statusCode} ${err.errorMessage}</title>
810 <h1>${err.errorMessage}</h1>
814 it('renders html', function () {
815 const contentType
= 'text/html';
816 const result
= dingus
.renderError(contentType
, err
);
817 assert
.deepStrictEqual(result
, `<!DOCTYPE html>
820 <title>${err.statusCode} ${err.errorMessage}</title>
823 <h1>${err.errorMessage}</h1>
824 <p>${err.details}</p>
828 it('renders html, multiple details', function () {
829 const contentType
= 'text/html';
830 err
.details
= ['one detail', 'two detail'];
831 const result
= dingus
.renderError(contentType
, err
);
832 assert
.deepStrictEqual(result
, `<!DOCTYPE html>
835 <title>${err.statusCode} ${err.errorMessage}</title>
838 <h1>${err.errorMessage}</h1>
846 describe('sendErrorResponse', function () {
848 beforeEach(function () {
853 getHeader: sinon
.stub(),
854 getHeaders: sinon
.stub(),
855 hasHeader: sinon
.stub().returns(true),
856 setHeader: sinon
.stub(),
858 sinon
.stub(dingus
, 'renderError');
860 it('covers', function () {
864 dingus
.sendErrorResponse(err
, req
, res
, ctx
);
865 assert(res
.end
.called
);
867 }); // sendErrorResponse
869 describe('proxyPrefix', function () {
870 let req
, res
, ctx
, stubHandler
, pfxDingus
;
873 beforeEach(function () {
874 pfxDingus
= new Dingus(console
, { proxyPrefix: pfx
});
876 setHeader: sinon
.stub(),
877 getHeader: sinon
.stub(),
882 setHeader: sinon
.stub(),
883 getHeader: sinon
.stub(),
886 sinon
.stub(pfxDingus
, 'handlerMethodNotAllowed');
887 sinon
.stub(pfxDingus
, 'handlerNotFound');
888 stubHandler
= sinon
.stub();
890 afterEach(function () {
894 it('handles prefixed route', async
function () {
895 const urlPath
= '/:id';
896 const method
= 'GET';
897 pfxDingus
.on(method
, urlPath
, stubHandler
);
898 req
.url
= pfx
+ '/abc';
901 await pfxDingus
.dispatch(req
, res
, ctx
);
902 assert(stubHandler
.called
);
903 assert(!pfxDingus
.handlerMethodNotAllowed
.called
);
904 assert(!pfxDingus
.handlerNotFound
.called
);
906 it('does not handle prefixed route', async
function () {
907 const urlPath
= '/:id';
908 const method
= 'GET';
909 pfxDingus
.on(method
, urlPath
, stubHandler
);
910 req
.url
= '/wrongpfx/abc';
913 await pfxDingus
.dispatch(req
, res
, ctx
);
914 assert(!stubHandler
.called
);
915 assert(!pfxDingus
.handlerMethodNotAllowed
.called
);
916 assert(pfxDingus
.handlerNotFound
.called
);
920 describe('handlerRedirect', function () {
922 beforeEach(function () {
924 getHeader: sinon
.stub(),
927 setHeader: sinon
.stub(),
932 it('covers', async
function () {
933 await dingus
.handlerRedirect(req
, res
, ctx
);
934 assert(res
.setHeader
.called
);
935 assert(res
.end
.called
);
937 it('covers non-defaults', async
function () {
938 await dingus
.handlerRedirect(req
, res
, ctx
, 308);
939 assert(res
.setHeader
.called
);
940 assert(res
.end
.called
);
942 }); // handlerRedirect
944 describe('handlerGetStaticFile', function () {
946 beforeEach(function () {
948 getHeader: sinon
.stub(),
951 setHeader: sinon
.stub(),
958 sinon
.stub(dingus
, 'serveFile');
960 it('covers', async
function () {
961 await dingus
.handlerGetStaticFile(req
, res
, ctx
);
962 assert(dingus
.serveFile
.called
);
964 it('covers specified file', async
function () {
965 await dingus
.handlerGetStaticFile(req
, res
, ctx
, 'file.txt');
966 assert(dingus
.serveFile
.called
);
968 }); // handlerGetStaticFile