fatsify核心功能示例测试!!!

This commit is contained in:
2025-09-21 14:50:41 +08:00
commit 9145aea047
1958 changed files with 230098 additions and 0 deletions

341
node_modules/fastify/test/logger/instantiation.test.js generated vendored Normal file
View File

@@ -0,0 +1,341 @@
'use strict'
const stream = require('node:stream')
const os = require('node:os')
const fs = require('node:fs')
const t = require('node:test')
const split = require('split2')
const { streamSym } = require('pino/lib/symbols')
const Fastify = require('../../fastify')
const helper = require('../helper')
const { FST_ERR_LOG_INVALID_LOGGER } = require('../../lib/errors')
const { once, on } = stream
const { createTempFile, request } = require('./logger-test-utils')
const { partialDeepStrictEqual } = require('../toolkit')
t.test('logger instantiation', { timeout: 60000 }, async (t) => {
let localhost
let localhostForURL
t.plan(11)
t.before(async function () {
[localhost, localhostForURL] = await helper.getLoopbackHost()
})
await t.test('can use external logger instance', async (t) => {
const lines = [/^Server listening at /, /^incoming request$/, /^log success$/, /^request completed$/]
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = require('pino')(stream)
const fastify = Fastify({ loggerInstance })
t.after(() => fastify.close())
fastify.get('/foo', function (req, reply) {
t.assert.ok(req.log)
req.log.info('log success')
reply.send({ hello: 'world' })
})
await fastify.listen({ port: 0, host: localhost })
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/foo')
for await (const [line] of on(stream, 'data')) {
const regex = lines.shift()
t.assert.ok(regex.test(line.msg), '"' + line.msg + '" does not match "' + regex + '"')
if (lines.length === 0) break
}
})
await t.test('should create a default logger if provided one is invalid', (t) => {
t.plan(8)
const logger = new Date()
const fastify = Fastify({ logger })
t.after(() => fastify.close())
t.assert.strictEqual(typeof fastify.log, 'object')
t.assert.strictEqual(typeof fastify.log.fatal, 'function')
t.assert.strictEqual(typeof fastify.log.error, 'function')
t.assert.strictEqual(typeof fastify.log.warn, 'function')
t.assert.strictEqual(typeof fastify.log.info, 'function')
t.assert.strictEqual(typeof fastify.log.debug, 'function')
t.assert.strictEqual(typeof fastify.log.trace, 'function')
t.assert.strictEqual(typeof fastify.log.child, 'function')
})
await t.test('expose the logger', async (t) => {
t.plan(2)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
await fastify.ready()
t.assert.ok(fastify.log)
t.assert.strictEqual(typeof fastify.log, 'object')
})
const interfaces = os.networkInterfaces()
const ipv6 = Object.keys(interfaces)
.filter(name => name.substr(0, 2) === 'lo')
.map(name => interfaces[name])
.reduce((list, set) => list.concat(set), [])
.filter(info => info.family === 'IPv6')
.map(info => info.address)
.shift()
await t.test('Wrap IPv6 address in listening log message', { skip: !ipv6 }, async (t) => {
t.plan(1)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
await fastify.ready()
await fastify.listen({ port: 0, host: ipv6 })
{
const [line] = await once(stream, 'data')
t.assert.strictEqual(line.msg, `Server listening at http://[${ipv6}]:${fastify.server.address().port}`)
}
})
await t.test('Do not wrap IPv4 address', async (t) => {
t.plan(1)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
await fastify.ready()
await fastify.listen({ port: 0, host: '127.0.0.1' })
{
const [line] = await once(stream, 'data')
t.assert.strictEqual(line.msg, `Server listening at http://127.0.0.1:${fastify.server.address().port}`)
}
})
await t.test('file option', async (t) => {
const { file, cleanup } = createTempFile(t)
// 0600 permissions (read/write for owner only)
if (process.env.CITGM) { fs.writeFileSync(file, '', { mode: 0o600 }) }
const fastify = Fastify({
logger: { file }
})
t.after(async () => {
await helper.sleep(250)
// may fail on win
try {
// cleanup the file after sonic-boom closed
// otherwise we may face racing condition
fastify.log[streamSym].once('close', cleanup)
// we must flush the stream ourself
// otherwise buffer may whole sonic-boom
fastify.log[streamSym].flushSync()
// end after flushing to actually close file
fastify.log[streamSym].end()
} catch (err) {
console.warn(err)
}
})
t.after(() => fastify.close())
fastify.get('/', function (req, reply) {
t.assert.ok(req.log)
reply.send({ hello: 'world' })
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ req: { method: 'GET', url: '/' }, msg: 'incoming request' },
{ res: { statusCode: 200 }, msg: 'request completed' }
]
await request(`http://${localhostForURL}:` + fastify.server.address().port)
await helper.sleep(250)
const log = fs.readFileSync(file, 'utf8').split('\n')
// strip last line
log.pop()
let id
for (let line of log) {
line = JSON.parse(line)
if (id === undefined && line.reqId) id = line.reqId
if (id !== undefined && line.reqId) t.assert.strictEqual(line.reqId, id)
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
}
})
await t.test('should be able to use a custom logger', (t) => {
t.plan(7)
const loggerInstance = {
fatal: (msg) => { t.assert.strictEqual(msg, 'fatal') },
error: (msg) => { t.assert.strictEqual(msg, 'error') },
warn: (msg) => { t.assert.strictEqual(msg, 'warn') },
info: (msg) => { t.assert.strictEqual(msg, 'info') },
debug: (msg) => { t.assert.strictEqual(msg, 'debug') },
trace: (msg) => { t.assert.strictEqual(msg, 'trace') },
child: () => loggerInstance
}
const fastify = Fastify({ loggerInstance })
t.after(() => fastify.close())
fastify.log.fatal('fatal')
fastify.log.error('error')
fastify.log.warn('warn')
fastify.log.info('info')
fastify.log.debug('debug')
fastify.log.trace('trace')
const child = fastify.log.child()
t.assert.strictEqual(child, loggerInstance)
})
await t.test('should throw in case a partially matching logger is provided', async (t) => {
t.plan(1)
try {
const fastify = Fastify({ logger: console })
await fastify.ready()
} catch (err) {
t.assert.strictEqual(
err instanceof FST_ERR_LOG_INVALID_LOGGER,
true,
"Invalid logger object provided. The logger instance should have these functions(s): 'fatal,child'."
)
}
})
await t.test('can use external logger instance with custom serializer', async (t) => {
const lines = [['level', 30], ['req', { url: '/foo' }], ['level', 30], ['res', { statusCode: 200 }]]
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = require('pino')({
level: 'info',
serializers: {
req: function (req) {
return {
url: req.url
}
}
}
}, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.get('/foo', function (req, reply) {
t.assert.ok(req.log)
req.log.info('log success')
reply.send({ hello: 'world' })
})
await fastify.ready()
await fastify.listen({ port: 0, host: localhost })
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/foo')
for await (const [line] of on(stream, 'data')) {
const check = lines.shift()
const key = check[0]
const value = check[1]
t.assert.deepStrictEqual(line[key], value)
if (lines.length === 0) break
}
})
await t.test('The logger should accept custom serializer', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info',
serializers: {
req: function (req) {
return {
url: req.url
}
}
}
}
})
t.after(() => fastify.close())
fastify.get('/custom', function (req, reply) {
t.assert.ok(req.log)
reply.send(new Error('kaboom'))
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ req: { url: '/custom' }, msg: 'incoming request' },
{ res: { statusCode: 500 }, msg: 'kaboom' },
{ res: { statusCode: 500 }, msg: 'request completed' }
]
t.plan(lines.length + 1)
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/custom')
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should throw in case the external logger provided does not have a child method', async (t) => {
t.plan(1)
const loggerInstance = {
info: console.info,
error: console.error,
debug: console.debug,
fatal: console.error,
warn: console.warn,
trace: console.trace
}
try {
const fastify = Fastify({ logger: loggerInstance })
await fastify.ready()
} catch (err) {
t.assert.strictEqual(
err instanceof FST_ERR_LOG_INVALID_LOGGER,
true,
"Invalid logger object provided. The logger instance should have these functions(s): 'child'."
)
}
})
})

47
node_modules/fastify/test/logger/logger-test-utils.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
'use strict'
const http = require('node:http')
const os = require('node:os')
const fs = require('node:fs')
const path = require('node:path')
function createDeferredPromise () {
const promise = {}
promise.promise = new Promise(function (resolve) {
promise.resolve = resolve
})
return promise
}
let count = 0
function createTempFile () {
const file = path.join(os.tmpdir(), `sonic-boom-${process.pid}-${count++}`)
function cleanup () {
try {
fs.unlinkSync(file)
} catch { }
}
return { file, cleanup }
}
function request (url, cleanup = () => { }) {
const promise = createDeferredPromise()
http.get(url, (res) => {
const chunks = []
// we consume the response
res.on('data', function (chunk) {
chunks.push(chunk)
})
res.once('end', function () {
cleanup(res, Buffer.concat(chunks).toString())
promise.resolve()
})
})
return promise.promise
}
module.exports = {
request,
createTempFile
}

423
node_modules/fastify/test/logger/logging.test.js generated vendored Normal file
View File

@@ -0,0 +1,423 @@
'use strict'
const stream = require('node:stream')
const t = require('node:test')
const split = require('split2')
const pino = require('pino')
const Fastify = require('../../fastify')
const helper = require('../helper')
const { once, on } = stream
const { request } = require('./logger-test-utils')
const { partialDeepStrictEqual } = require('../toolkit')
t.test('logging', { timeout: 60000 }, async (t) => {
let localhost
let localhostForURL
t.plan(13)
t.before(async function () {
[localhost, localhostForURL] = await helper.getLoopbackHost()
})
await t.test('The default 404 handler logs the incoming request', async (t) => {
const lines = ['incoming request', 'Route GET:/not-found not found', 'request completed']
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'trace' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/not-found' })
t.assert.strictEqual(response.statusCode, 404)
}
for await (const [line] of on(stream, 'data')) {
t.assert.strictEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('should not rely on raw request to log errors', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
fastify.get('/error', function (req, reply) {
t.assert.ok(req.log)
reply.status(415).send(new Error('something happened'))
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ level: 30, msg: 'incoming request' },
{ res: { statusCode: 415 }, msg: 'something happened' },
{ res: { statusCode: 415 }, msg: 'request completed' }
]
t.plan(lines.length + 1)
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should log the error if no error handler is defined', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
fastify.get('/error', function (req, reply) {
t.assert.ok(req.log)
reply.send(new Error('a generic error'))
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ msg: 'incoming request' },
{ level: 50, msg: 'a generic error' },
{ res: { statusCode: 500 }, msg: 'request completed' }
]
t.plan(lines.length + 1)
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should log as info if error status code >= 400 and < 500 if no error handler is defined', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
fastify.get('/400', function (req, reply) {
t.assert.ok(req.log)
reply.send(Object.assign(new Error('a 400 error'), { statusCode: 400 }))
})
fastify.get('/503', function (req, reply) {
t.assert.ok(req.log)
reply.send(Object.assign(new Error('a 503 error'), { statusCode: 503 }))
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ msg: 'incoming request' },
{ level: 30, msg: 'a 400 error' },
{ res: { statusCode: 400 }, msg: 'request completed' }
]
t.plan(lines.length + 1)
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/400')
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should log as error if error status code >= 500 if no error handler is defined', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
fastify.get('/503', function (req, reply) {
t.assert.ok(req.log)
reply.send(Object.assign(new Error('a 503 error'), { statusCode: 503 }))
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ msg: 'incoming request' },
{ level: 50, msg: 'a 503 error' },
{ res: { statusCode: 503 }, msg: 'request completed' }
]
t.plan(lines.length + 1)
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/503')
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should not log the error if error handler is defined and it does not error', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
fastify.get('/error', function (req, reply) {
t.assert.ok(req.log)
reply.send(new Error('something happened'))
})
fastify.setErrorHandler((err, req, reply) => {
t.assert.ok(err)
reply.send('something bad happened')
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ level: 30, msg: 'incoming request' },
{ res: { statusCode: 200 }, msg: 'request completed' }
]
t.plan(lines.length + 2)
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('reply.send logs an error if called twice in a row', async (t) => {
const lines = [
'incoming request',
'request completed',
'Reply was already sent, did you forget to "return reply" in "/" (GET)?',
'Reply was already sent, did you forget to "return reply" in "/" (GET)?'
]
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino(stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
reply.send({ hello: 'world2' })
reply.send({ hello: 'world3' })
})
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.ok(partialDeepStrictEqual(body, { hello: 'world' }))
for await (const [line] of on(stream, 'data')) {
t.assert.strictEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('should not log incoming request and outgoing response when disabled', async (t) => {
t.plan(1)
const stream = split(JSON.parse)
const fastify = Fastify({ disableRequestLogging: true, logger: { level: 'info', stream } })
t.after(() => fastify.close())
fastify.get('/500', (req, reply) => {
reply.code(500).send(Error('500 error'))
})
await fastify.ready()
await fastify.inject({ method: 'GET', url: '/500' })
// no more readable data
t.assert.strictEqual(stream.readableLength, 0)
})
await t.test('should not log incoming request, outgoing response and route not found for 404 onBadUrl when disabled', async (t) => {
t.plan(1)
const stream = split(JSON.parse)
const fastify = Fastify({ disableRequestLogging: true, logger: { level: 'info', stream } })
t.after(() => fastify.close())
await fastify.ready()
await fastify.inject({ method: 'GET', url: '/%c0' })
// no more readable data
t.assert.strictEqual(stream.readableLength, 0)
})
await t.test('defaults to info level', async (t) => {
const lines = [
{ req: { method: 'GET' }, msg: 'incoming request' },
{ res: { statusCode: 200 }, msg: 'request completed' }
]
t.plan(lines.length * 2 + 1)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream
}
})
t.after(() => fastify.close())
fastify.get('/', function (req, reply) {
t.assert.ok(req.log)
reply.send({ hello: 'world' })
})
await fastify.ready()
await fastify.listen({ port: 0 })
await request(`http://${localhostForURL}:` + fastify.server.address().port)
let id
for await (const [line] of on(stream, 'data')) {
// we skip the non-request log
if (typeof line.reqId !== 'string') continue
if (id === undefined && line.reqId) id = line.reqId
if (id !== undefined && line.reqId) t.assert.strictEqual(line.reqId, id)
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('test log stream', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
fastify.get('/', function (req, reply) {
t.assert.ok(req.log)
reply.send({ hello: 'world' })
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ req: { method: 'GET' }, msg: 'incoming request' },
{ res: { statusCode: 200 }, msg: 'request completed' }
]
t.plan(lines.length + 3)
await request(`http://${localhostForURL}:` + fastify.server.address().port)
let id
for await (const [line] of on(stream, 'data')) {
if (id === undefined && line.reqId) id = line.reqId
if (id !== undefined && line.reqId) t.assert.strictEqual(line.reqId, id)
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('test error log stream', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
}
})
t.after(() => fastify.close())
fastify.get('/error', function (req, reply) {
t.assert.ok(req.log)
reply.send(new Error('kaboom'))
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ req: { method: 'GET' }, msg: 'incoming request' },
{ res: { statusCode: 500 }, msg: 'kaboom' },
{ res: { statusCode: 500 }, msg: 'request completed' }
]
t.plan(lines.length + 4)
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')
let id
for await (const [line] of on(stream, 'data')) {
if (id === undefined && line.reqId) id = line.reqId
if (id !== undefined && line.reqId) t.assert.strictEqual(line.reqId, id)
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should not log the error if request logging is disabled', async (t) => {
t.plan(4)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
level: 'info'
},
disableRequestLogging: true
})
t.after(() => fastify.close())
fastify.get('/error', function (req, reply) {
t.assert.ok(req.log)
reply.send(new Error('a generic error'))
})
await fastify.ready()
await fastify.listen({ port: 0, host: localhost })
await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')
{
const [line] = await once(stream, 'data')
t.assert.ok(typeof line.msg === 'string')
t.assert.ok(line.msg.startsWith('Server listening at'), 'message is set')
}
// no more readable data
t.assert.strictEqual(stream.readableLength, 0)
})
})

579
node_modules/fastify/test/logger/options.test.js generated vendored Normal file
View File

@@ -0,0 +1,579 @@
'use strict'
const stream = require('node:stream')
const t = require('node:test')
const split = require('split2')
const pino = require('pino')
const Fastify = require('../../fastify')
const { on } = stream
t.test('logger options', { timeout: 60000 }, async (t) => {
t.plan(16)
await t.test('logger can be silenced', (t) => {
t.plan(17)
const fastify = Fastify({
logger: false
})
t.after(() => fastify.close())
t.assert.ok(fastify.log)
t.assert.deepEqual(typeof fastify.log, 'object')
t.assert.deepEqual(typeof fastify.log.fatal, 'function')
t.assert.deepEqual(typeof fastify.log.error, 'function')
t.assert.deepEqual(typeof fastify.log.warn, 'function')
t.assert.deepEqual(typeof fastify.log.info, 'function')
t.assert.deepEqual(typeof fastify.log.debug, 'function')
t.assert.deepEqual(typeof fastify.log.trace, 'function')
t.assert.deepEqual(typeof fastify.log.child, 'function')
const childLog = fastify.log.child()
t.assert.deepEqual(typeof childLog, 'object')
t.assert.deepEqual(typeof childLog.fatal, 'function')
t.assert.deepEqual(typeof childLog.error, 'function')
t.assert.deepEqual(typeof childLog.warn, 'function')
t.assert.deepEqual(typeof childLog.info, 'function')
t.assert.deepEqual(typeof childLog.debug, 'function')
t.assert.deepEqual(typeof childLog.trace, 'function')
t.assert.deepEqual(typeof childLog.child, 'function')
})
await t.test('Should set a custom logLevel for a plugin', async (t) => {
const lines = ['incoming request', 'Hello', 'request completed']
t.plan(lines.length + 2)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'error' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.get('/', (req, reply) => {
req.log.info('Not Exist') // we should not see this log
reply.send({ hello: 'world' })
})
fastify.register(function (instance, opts, done) {
instance.get('/plugin', (req, reply) => {
req.log.info('Hello') // we should see this log
reply.send({ hello: 'world' })
})
done()
}, { logLevel: 'info' })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepEqual(body.hello, 'world')
}
{
const response = await fastify.inject({ method: 'GET', url: '/plugin' })
const body = await response.json()
t.assert.deepEqual(body.hello, 'world')
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should set a custom logSerializers for a plugin', async (t) => {
const lines = ['incoming request', 'XHello', 'request completed']
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'error' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.register(function (instance, opts, done) {
instance.get('/plugin', (req, reply) => {
req.log.info({ test: 'Hello' }) // we should see this log
reply.send({ hello: 'world' })
})
done()
}, { logLevel: 'info', logSerializers: { test: value => 'X' + value } })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/plugin' })
const body = await response.json()
t.assert.deepEqual(body.hello, 'world')
}
for await (const [line] of on(stream, 'data')) {
// either test or msg
t.assert.deepEqual(line.test || line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should set a custom logLevel for every plugin', async (t) => {
const lines = ['incoming request', 'info', 'request completed', 'incoming request', 'debug', 'request completed']
t.plan(lines.length * 2 + 3)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'error' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.get('/', (req, reply) => {
req.log.warn('Hello') // we should not see this log
reply.send({ hello: 'world' })
})
fastify.register(function (instance, opts, done) {
instance.get('/info', (req, reply) => {
req.log.info('info') // we should see this log
req.log.debug('hidden log')
reply.send({ hello: 'world' })
})
done()
}, { logLevel: 'info' })
fastify.register(function (instance, opts, done) {
instance.get('/debug', (req, reply) => {
req.log.debug('debug') // we should see this log
req.log.trace('hidden log')
reply.send({ hello: 'world' })
})
done()
}, { logLevel: 'debug' })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
{
const response = await fastify.inject({ method: 'GET', url: '/info' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
{
const response = await fastify.inject({ method: 'GET', url: '/debug' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(line.level === 30 || line.level === 20)
t.assert.deepEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should set a custom logSerializers for every plugin', async (t) => {
const lines = ['incoming request', 'Hello', 'request completed', 'incoming request', 'XHello', 'request completed', 'incoming request', 'ZHello', 'request completed']
t.plan(lines.length + 3)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'info' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.get('/', (req, reply) => {
req.log.warn({ test: 'Hello' })
reply.send({ hello: 'world' })
})
fastify.register(function (instance, opts, done) {
instance.get('/test1', (req, reply) => {
req.log.info({ test: 'Hello' })
reply.send({ hello: 'world' })
})
done()
}, { logSerializers: { test: value => 'X' + value } })
fastify.register(function (instance, opts, done) {
instance.get('/test2', (req, reply) => {
req.log.info({ test: 'Hello' })
reply.send({ hello: 'world' })
})
done()
}, { logSerializers: { test: value => 'Z' + value } })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
{
const response = await fastify.inject({ method: 'GET', url: '/test1' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
{
const response = await fastify.inject({ method: 'GET', url: '/test2' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.test || line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should override serializers from route', async (t) => {
const lines = ['incoming request', 'ZHello', 'request completed']
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'info' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.register(function (instance, opts, done) {
instance.get('/', {
logSerializers: {
test: value => 'Z' + value // should override
}
}, (req, reply) => {
req.log.info({ test: 'Hello' })
reply.send({ hello: 'world' })
})
done()
}, { logSerializers: { test: value => 'X' + value } })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.test || line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should override serializers from plugin', async (t) => {
const lines = ['incoming request', 'ZHello', 'request completed']
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'info' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.register(function (instance, opts, done) {
instance.register(context1, {
logSerializers: {
test: value => 'Z' + value // should override
}
})
done()
}, { logSerializers: { test: value => 'X' + value } })
function context1 (instance, opts, done) {
instance.get('/', (req, reply) => {
req.log.info({ test: 'Hello' })
reply.send({ hello: 'world' })
})
done()
}
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.test || line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should increase the log level for a specific plugin', async (t) => {
const lines = ['Hello']
t.plan(lines.length * 2 + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'info' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.register(function (instance, opts, done) {
instance.get('/', (req, reply) => {
req.log.error('Hello') // we should see this log
reply.send({ hello: 'world' })
})
done()
}, { logLevel: 'error' })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.level, 50)
t.assert.deepEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should set the log level for the customized 404 handler', async (t) => {
const lines = ['Hello']
t.plan(lines.length * 2 + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'warn' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.register(function (instance, opts, done) {
instance.setNotFoundHandler(function (req, reply) {
req.log.error('Hello')
reply.code(404).send()
})
done()
}, { logLevel: 'error' })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
t.assert.deepEqual(response.statusCode, 404)
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.level, 50)
t.assert.deepEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should set the log level for the customized 500 handler', async (t) => {
const lines = ['Hello']
t.plan(lines.length * 2 + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'warn' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.register(function (instance, opts, done) {
instance.get('/', (req, reply) => {
req.log.error('kaboom')
reply.send(new Error('kaboom'))
})
instance.setErrorHandler(function (e, request, reply) {
reply.log.fatal('Hello')
reply.code(500).send()
})
done()
}, { logLevel: 'fatal' })
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
t.assert.deepEqual(response.statusCode, 500)
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.level, 60)
t.assert.deepEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('Should set a custom log level for a specific route', async (t) => {
const lines = ['incoming request', 'Hello', 'request completed']
t.plan(lines.length + 2)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'error' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.get('/log', { logLevel: 'info' }, (req, reply) => {
req.log.info('Hello')
reply.send({ hello: 'world' })
})
fastify.get('/no-log', (req, reply) => {
req.log.info('Hello')
reply.send({ hello: 'world' })
})
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/log' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
{
const response = await fastify.inject({ method: 'GET', url: '/no-log' })
const body = await response.json()
t.assert.deepEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.deepEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
await t.test('should pass when using unWritable props in the logger option', (t) => {
t.plan(8)
const fastify = Fastify({
logger: Object.defineProperty({}, 'level', { value: 'info' })
})
t.after(() => fastify.close())
t.assert.deepEqual(typeof fastify.log, 'object')
t.assert.deepEqual(typeof fastify.log.fatal, 'function')
t.assert.deepEqual(typeof fastify.log.error, 'function')
t.assert.deepEqual(typeof fastify.log.warn, 'function')
t.assert.deepEqual(typeof fastify.log.info, 'function')
t.assert.deepEqual(typeof fastify.log.debug, 'function')
t.assert.deepEqual(typeof fastify.log.trace, 'function')
t.assert.deepEqual(typeof fastify.log.child, 'function')
})
await t.test('Should throw an error if logger instance is passed to `logger`', async (t) => {
t.plan(2)
const stream = split(JSON.parse)
const logger = require('pino')(stream)
try {
Fastify({ logger })
} catch (err) {
t.assert.ok(err)
t.assert.deepEqual(err.code, 'FST_ERR_LOG_INVALID_LOGGER_CONFIG')
}
})
await t.test('Should throw an error if options are passed to `loggerInstance`', async (t) => {
t.plan(2)
try {
Fastify({ loggerInstance: { level: 'log' } })
} catch (err) {
t.assert.ok(err)
t.assert.strictEqual(err.code, 'FST_ERR_LOG_INVALID_LOGGER_INSTANCE')
}
})
await t.test('If both `loggerInstance` and `logger` are provided, an error should be thrown', async (t) => {
t.plan(2)
const loggerInstanceStream = split(JSON.parse)
const loggerInstance = pino({ level: 'error' }, loggerInstanceStream)
const loggerStream = split(JSON.parse)
try {
Fastify({
logger: {
stream: loggerStream,
level: 'info'
},
loggerInstance
})
} catch (err) {
t.assert.ok(err)
t.assert.deepEqual(err.code, 'FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED')
}
})
await t.test('`logger` should take pino configuration and create a pino logger', async (t) => {
const lines = ['hello', 'world']
t.plan(2 * lines.length + 2)
const loggerStream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream: loggerStream,
level: 'error'
}
})
t.after(() => fastify.close())
fastify.get('/hello', (req, reply) => {
req.log.error('hello')
reply.code(404).send()
})
fastify.get('/world', (req, reply) => {
req.log.error('world')
reply.code(201).send()
})
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/hello' })
t.assert.deepEqual(response.statusCode, 404)
}
{
const response = await fastify.inject({ method: 'GET', url: '/world' })
t.assert.deepEqual(response.statusCode, 201)
}
for await (const [line] of on(loggerStream, 'data')) {
t.assert.deepEqual(line.level, 50)
t.assert.deepEqual(line.msg, lines.shift())
if (lines.length === 0) break
}
})
})

292
node_modules/fastify/test/logger/request.test.js generated vendored Normal file
View File

@@ -0,0 +1,292 @@
'use strict'
const stream = require('node:stream')
const t = require('node:test')
const split = require('split2')
const Fastify = require('../../fastify')
const helper = require('../helper')
const { on } = stream
const { request } = require('./logger-test-utils')
const { partialDeepStrictEqual } = require('../toolkit')
t.test('request', { timeout: 60000 }, async (t) => {
let localhost
t.plan(7)
t.before(async function () {
[localhost] = await helper.getLoopbackHost()
})
await t.test('The request id header key can be customized', async (t) => {
const lines = ['incoming request', 'some log message', 'request completed']
t.plan(lines.length * 2 + 2)
const REQUEST_ID = '42'
const stream = split(JSON.parse)
const fastify = Fastify({
logger: { stream, level: 'info' },
requestIdHeader: 'my-custom-request-id'
})
t.after(() => fastify.close())
fastify.get('/', (req, reply) => {
t.assert.strictEqual(req.id, REQUEST_ID)
req.log.info('some log message')
reply.send({ id: req.id })
})
const response = await fastify.inject({ method: 'GET', url: '/', headers: { 'my-custom-request-id': REQUEST_ID } })
const body = await response.json()
t.assert.strictEqual(body.id, REQUEST_ID)
for await (const [line] of on(stream, 'data')) {
t.assert.strictEqual(line.reqId, REQUEST_ID)
t.assert.strictEqual(line.msg, lines.shift(), 'message is set')
if (lines.length === 0) break
}
})
await t.test('The request id header key can be ignored', async (t) => {
const lines = ['incoming request', 'some log message', 'request completed']
t.plan(lines.length * 2 + 2)
const REQUEST_ID = 'ignore-me'
const stream = split(JSON.parse)
const fastify = Fastify({
logger: { stream, level: 'info' },
requestIdHeader: false
})
t.after(() => fastify.close())
fastify.get('/', (req, reply) => {
t.assert.strictEqual(req.id, 'req-1')
req.log.info('some log message')
reply.send({ id: req.id })
})
const response = await fastify.inject({ method: 'GET', url: '/', headers: { 'request-id': REQUEST_ID } })
const body = await response.json()
t.assert.strictEqual(body.id, 'req-1')
for await (const [line] of on(stream, 'data')) {
t.assert.strictEqual(line.reqId, 'req-1')
t.assert.strictEqual(line.msg, lines.shift(), 'message is set')
if (lines.length === 0) break
}
})
await t.test('The request id header key can be customized along with a custom id generator', async (t) => {
const REQUEST_ID = '42'
const matches = [
{ reqId: REQUEST_ID, msg: 'incoming request' },
{ reqId: REQUEST_ID, msg: 'some log message' },
{ reqId: REQUEST_ID, msg: 'request completed' },
{ reqId: 'foo', msg: 'incoming request' },
{ reqId: 'foo', msg: 'some log message 2' },
{ reqId: 'foo', msg: 'request completed' }
]
t.plan(matches.length + 4)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: { stream, level: 'info' },
requestIdHeader: 'my-custom-request-id',
genReqId (req) {
return 'foo'
}
})
t.after(() => fastify.close())
fastify.get('/one', (req, reply) => {
t.assert.strictEqual(req.id, REQUEST_ID)
req.log.info('some log message')
reply.send({ id: req.id })
})
fastify.get('/two', (req, reply) => {
t.assert.strictEqual(req.id, 'foo')
req.log.info('some log message 2')
reply.send({ id: req.id })
})
{
const response = await fastify.inject({ method: 'GET', url: '/one', headers: { 'my-custom-request-id': REQUEST_ID } })
const body = await response.json()
t.assert.strictEqual(body.id, REQUEST_ID)
}
{
const response = await fastify.inject({ method: 'GET', url: '/two' })
const body = await response.json()
t.assert.strictEqual(body.id, 'foo')
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, matches.shift()))
if (matches.length === 0) break
}
})
await t.test('The request id header key can be ignored along with a custom id generator', async (t) => {
const REQUEST_ID = 'ignore-me'
const matches = [
{ reqId: 'foo', msg: 'incoming request' },
{ reqId: 'foo', msg: 'some log message' },
{ reqId: 'foo', msg: 'request completed' },
{ reqId: 'foo', msg: 'incoming request' },
{ reqId: 'foo', msg: 'some log message 2' },
{ reqId: 'foo', msg: 'request completed' }
]
t.plan(matches.length + 4)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: { stream, level: 'info' },
requestIdHeader: false,
genReqId (req) {
return 'foo'
}
})
t.after(() => fastify.close())
fastify.get('/one', (req, reply) => {
t.assert.strictEqual(req.id, 'foo')
req.log.info('some log message')
reply.send({ id: req.id })
})
fastify.get('/two', (req, reply) => {
t.assert.strictEqual(req.id, 'foo')
req.log.info('some log message 2')
reply.send({ id: req.id })
})
{
const response = await fastify.inject({ method: 'GET', url: '/one', headers: { 'request-id': REQUEST_ID } })
const body = await response.json()
t.assert.strictEqual(body.id, 'foo')
}
{
const response = await fastify.inject({ method: 'GET', url: '/two' })
const body = await response.json()
t.assert.strictEqual(body.id, 'foo')
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, matches.shift()))
if (matches.length === 0) break
}
})
await t.test('The request id log label can be changed', async (t) => {
const REQUEST_ID = '42'
const matches = [
{ traceId: REQUEST_ID, msg: 'incoming request' },
{ traceId: REQUEST_ID, msg: 'some log message' },
{ traceId: REQUEST_ID, msg: 'request completed' }
]
t.plan(matches.length + 2)
const stream = split(JSON.parse)
const fastify = Fastify({
logger: { stream, level: 'info' },
requestIdHeader: 'my-custom-request-id',
requestIdLogLabel: 'traceId'
})
t.after(() => fastify.close())
fastify.get('/one', (req, reply) => {
t.assert.strictEqual(req.id, REQUEST_ID)
req.log.info('some log message')
reply.send({ id: req.id })
})
{
const response = await fastify.inject({ method: 'GET', url: '/one', headers: { 'my-custom-request-id': REQUEST_ID } })
const body = await response.json()
t.assert.strictEqual(body.id, REQUEST_ID)
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, matches.shift()))
if (matches.length === 0) break
}
})
await t.test('should redact the authorization header if so specified', async (t) => {
const stream = split(JSON.parse)
const fastify = Fastify({
logger: {
stream,
redact: ['req.headers.authorization'],
level: 'info',
serializers: {
req (req) {
return {
method: req.method,
url: req.url,
headers: req.headers,
hostname: req.hostname,
remoteAddress: req.ip,
remotePort: req.socket.remotePort
}
}
}
}
})
t.after(() => fastify.close())
fastify.get('/', function (req, reply) {
t.assert.deepStrictEqual(req.headers.authorization, 'Bearer abcde')
reply.send({ hello: 'world' })
})
await fastify.ready()
const server = await fastify.listen({ port: 0, host: localhost })
const lines = [
{ msg: `Server listening at ${server}` },
{ req: { headers: { authorization: '[Redacted]' } }, msg: 'incoming request' },
{ res: { statusCode: 200 }, msg: 'request completed' }
]
t.plan(lines.length + 3)
await request({
method: 'GET',
path: '/',
host: localhost,
port: fastify.server.address().port,
headers: {
authorization: 'Bearer abcde'
}
}, function (response, body) {
t.assert.strictEqual(response.statusCode, 200)
t.assert.deepStrictEqual(body, JSON.stringify({ hello: 'world' }))
})
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should not throw error when serializing custom req', (t) => {
t.plan(1)
const lines = []
const dest = new stream.Writable({
write: function (chunk, enc, cb) {
lines.push(JSON.parse(chunk))
cb()
}
})
const fastify = Fastify({ logger: { level: 'info', stream: dest } })
t.after(() => fastify.close())
fastify.log.info({ req: {} })
t.assert.deepStrictEqual(lines[0].req, {})
})
})

183
node_modules/fastify/test/logger/response.test.js generated vendored Normal file
View File

@@ -0,0 +1,183 @@
'use strict'
const stream = require('node:stream')
const t = require('node:test')
const split = require('split2')
const pino = require('pino')
const Fastify = require('../../fastify')
const { partialDeepStrictEqual } = require('../toolkit')
const { on } = stream
t.test('response serialization', { timeout: 60000 }, async (t) => {
t.plan(4)
await t.test('Should use serializers from plugin and route', async (t) => {
const lines = [
{ msg: 'incoming request' },
{ test: 'XHello', test2: 'ZHello' },
{ msg: 'request completed' }
]
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({ level: 'info' }, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.register(context1, {
logSerializers: { test: value => 'X' + value }
})
function context1 (instance, opts, done) {
instance.get('/', {
logSerializers: {
test2: value => 'Z' + value
}
}, (req, reply) => {
req.log.info({ test: 'Hello', test2: 'Hello' }) // { test: 'XHello', test2: 'ZHello' }
reply.send({ hello: 'world' })
})
done()
}
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepStrictEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('Should use serializers from instance fastify and route', async (t) => {
const lines = [
{ msg: 'incoming request' },
{ test: 'XHello', test2: 'ZHello' },
{ msg: 'request completed' }
]
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({
level: 'info',
serializers: {
test: value => 'X' + value,
test2: value => 'This should be override - ' + value
}
}, stream)
const fastify = Fastify({
loggerInstance
})
t.after(() => fastify.close())
fastify.get('/', {
logSerializers: {
test2: value => 'Z' + value
}
}, (req, reply) => {
req.log.info({ test: 'Hello', test2: 'Hello' }) // { test: 'XHello', test2: 'ZHello' }
reply.send({ hello: 'world' })
})
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepStrictEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('Should use serializers inherit from contexts', async (t) => {
const lines = [
{ msg: 'incoming request' },
{ test: 'XHello', test2: 'YHello', test3: 'ZHello' },
{ msg: 'request completed' }
]
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const loggerInstance = pino({
level: 'info',
serializers: {
test: value => 'X' + value
}
}, stream)
const fastify = Fastify({ loggerInstance })
t.after(() => fastify.close())
fastify.register(context1, { logSerializers: { test2: value => 'Y' + value } })
function context1 (instance, opts, done) {
instance.get('/', {
logSerializers: {
test3: value => 'Z' + value
}
}, (req, reply) => {
req.log.info({ test: 'Hello', test2: 'Hello', test3: 'Hello' }) // { test: 'XHello', test2: 'YHello', test3: 'ZHello' }
reply.send({ hello: 'world' })
})
done()
}
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/' })
const body = await response.json()
t.assert.deepStrictEqual(body, { hello: 'world' })
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
await t.test('should serialize request and response', async (t) => {
const lines = [
{ req: { method: 'GET', url: '/500' }, msg: 'incoming request' },
{ req: { method: 'GET', url: '/500' }, msg: '500 error' },
{ msg: 'request completed' }
]
t.plan(lines.length + 1)
const stream = split(JSON.parse)
const fastify = Fastify({ logger: { level: 'info', stream } })
t.after(() => fastify.close())
fastify.get('/500', (req, reply) => {
reply.code(500).send(Error('500 error'))
})
await fastify.ready()
{
const response = await fastify.inject({ method: 'GET', url: '/500' })
t.assert.strictEqual(response.statusCode, 500)
}
for await (const [line] of on(stream, 'data')) {
t.assert.ok(partialDeepStrictEqual(line, lines.shift()))
if (lines.length === 0) break
}
})
})

0
node_modules/fastify/test/logger/tap-parallel-not-ok generated vendored Normal file
View File