UNPKG

2.52 kBJavaScriptView Raw
1'use strict'
2
3const t = require('tap')
4const test = t.test
5const Fastify = require('../..')
6const loggerUtils = require('../../lib/logger')
7
8test('time resolution', t => {
9 t.plan(2)
10 t.is(typeof loggerUtils.now, 'function')
11 t.is(typeof loggerUtils.now(), 'number')
12})
13
14test('The logger should add a unique id for every request', t => {
15 const ids = []
16
17 const fastify = Fastify()
18 fastify.get('/', (req, reply) => {
19 t.ok(req.raw.id)
20 reply.send({ id: req.raw.id })
21 })
22
23 fastify.listen(0, err => {
24 t.error(err)
25 const queue = new Queue()
26 for (var i = 0; i < 10; i++) {
27 queue.add(checkId)
28 }
29 queue.add(() => {
30 fastify.close()
31 t.end()
32 })
33 })
34
35 function checkId (done) {
36 fastify.inject({
37 method: 'GET',
38 url: 'http://localhost:' + fastify.server.address().port
39 }, (err, res) => {
40 t.error(err)
41 const payload = JSON.parse(res.payload)
42 t.ok(ids.indexOf(payload.id) === -1, 'the id should not be duplicated')
43 ids.push(payload.id)
44 done()
45 })
46 }
47})
48
49test('The logger should reuse request id header for req.id', t => {
50 const fastify = Fastify()
51 fastify.get('/', (req, reply) => {
52 t.ok(req.raw.id)
53 reply.send({ id: req.raw.id })
54 })
55
56 fastify.listen(0, err => {
57 t.error(err)
58
59 fastify.inject({
60 method: 'GET',
61 url: 'http://localhost:' + fastify.server.address().port,
62 headers: {
63 'Request-Id': 'request-id-1'
64 }
65 }, (err, res) => {
66 t.error(err)
67 const payload = JSON.parse(res.payload)
68 t.ok(payload.id === 'request-id-1', 'the request id from the header should be returned')
69 fastify.close()
70 t.end()
71 })
72 })
73})
74
75function Queue () {
76 this.q = []
77 this.running = false
78}
79
80Queue.prototype.add = function add (job) {
81 this.q.push(job)
82 if (!this.running) this.run()
83}
84
85Queue.prototype.run = function run () {
86 this.running = true
87 const job = this.q.shift()
88 job(() => {
89 if (this.q.length) {
90 this.run()
91 } else {
92 this.running = false
93 }
94 })
95}
96
97test('The logger should error if both stream and file destination are given', t => {
98 t.plan(2)
99
100 const stream = require('stream').Writable
101
102 try {
103 Fastify({
104 logger: {
105 level: 'info',
106 stream: stream,
107 file: '/test'
108 }
109 })
110 } catch (err) {
111 t.is(err.code, 'FST_ERR_LOG_INVALID_DESTINATION')
112 t.is(err.message, 'FST_ERR_LOG_INVALID_DESTINATION: Cannot specify both logger.stream and logger.file options')
113 }
114})