ronantakizawa/codereview-bench huggingface dataset:
Repository: fastify/fastify
File: test/fastify-instance.test.js (JavaScript)

Code before:
  const host = '127.0.0.1'
  const fastify = Fastify()
  await fastify.listen({ port, host })
  t.assert.deepStrictEqual(fastify.listeningOrigin, `http://${host}:${port}`)
  await fastify.close()
})

test('fastify instance should contains listeningOrigin property (with port and https)', async t => {
  t.plan(1)
  const port = 3000
  const host = '127.0.0.1'
  const fastify = Fastify({ https: {} })
  await fastify.listen({ port, host })
  t.assert.deepStrictEqual(fastify.listeningOrigin, `https://${host}:${port}`)
  await fastify.close()
})

test('fastify instance should contains listeningOrigin property (unix socket)', { skip: os.platform() === 'win32' }, async t => {
  const fastify = Fastify()
  const path = `fastify.${Date.now()}.sock`
  await fastify.listen({ path })
  t.assert.deepStrictEqual(fastify.listeningOrigin, path)
  await fastify.close()
})

test('fastify instance should contains listeningOrigin property (IPv6)', { skip: !hasIPv6 }, async t => {
  t.plan(1)
  const port = 3000
  const host = '::1'
  const fastify = Fastify()
  await fastify.listen({ port, host })
  t.assert.deepStrictEqual(fastify.listeningOrigin, `http://[::1]:${port}`)
  await fastify.close()
})

test('fastify instance should ensure ready promise cleanup on ready', async t => {
  t.plan(1)
  const fastify = Fastify()
  await fastify.ready()
  t.assert.strictEqual(fastify[kState].readyPromise, null)
})


Review comment (suggestion):
```suggestion
test('fastify instance should contains listeningOrigin property (IPv6)', { skip: isIPv6Missing }, async t => {
```

Code after:
  const host = '127.0.0.1'
  const fastify = Fastify()
  await fastify.listen({ port, host })
  t.assert.deepStrictEqual(fastify.listeningOrigin, `http://${host}:${port}`)
  await fastify.close()
})

test('fastify instance should contains listeningOrigin property (with port and https)', async t => {
  t.plan(1)
  const port = 3000
  const host = '127.0.0.1'
  const fastify = Fastify({ https: {} })
  await fastify.listen({ port, host })
  t.assert.deepStrictEqual(fastify.listeningOrigin, `https://${host}:${port}`)
  await fastify.close()
})

test('fastify instance should contains listeningOrigin property (unix socket)', { skip: os.platform() === 'win32' }, async t => {
  const fastify = Fastify()
  const path = `fastify.${Date.now()}.sock`
  await fastify.listen({ path })
  t.assert.deepStrictEqual(fastify.listeningOrigin, path)
  await fastify.close()
})

test('fastify instance should contains listeningOrigin property (IPv6)', { skip: isIPv6Missing }, async t => {
  t.plan(1)
  const port = 3000
  const host = '::1'
  const fastify = Fastify()
  await fastify.listen({ port, host })
  t.assert.deepStrictEqual(fastify.listeningOrigin, `http://[::1]:${port}`)
  await fastify.close()
})

test('fastify instance should ensure ready promise cleanup on ready', async t => {
  t.plan(1)
  const fastify = Fastify()
  await fastify.ready()
  t.assert.strictEqual(fastify[kState].readyPromise, null)
})
Repository: fastify/fastify
File: test/custom-parser.0.test.js (JavaScript)

Code before:
'use strict'

const fs = require('node:fs')
const { test } = require('node:test')
const sget = require('simple-get').concat
const Fastify = require('../fastify')
const jsonParser = require('fast-json-body')
const { getServerUrl, plainTextParser } = require('./helper')
const { waitForCb } = require('./toolkit')

process.removeAllListeners('warning')

test('contentTypeParser method should exist', t => {
  t.plan(1)
  const fastify = Fastify()
  t.assert.ok(fastify.addContentTypeParser)
})

test('contentTypeParser should add a custom parser', (t, testDone) => {
  t.plan(3)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.options('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.addContentTypeParser('application/jsoff', function (req, payload, done) {
    jsonParser(payload, function (err, body) {
      done(err, body)
    })
  })

  fastify.listen({ port: 0 }, err => {
    t.assert.ifError(err)

    const completion = waitForCb({ steps: 2 })

    t.after(() => fastify.close())

    t.test('in POST', (t, testDone) => {

Review comment (suggestion):
```suggestion
test('contentTypeParser should add a custom parser', (t, mainTestDone) => {
```

Code after:
'use strict'

const fs = require('node:fs')
const { test } = require('node:test')
const sget = require('simple-get').concat
const Fastify = require('../fastify')
const jsonParser = require('fast-json-body')
const { getServerUrl, plainTextParser } = require('./helper')
const { waitForCb } = require('./toolkit')

process.removeAllListeners('warning')

test('contentTypeParser method should exist', t => {
  t.plan(1)
  const fastify = Fastify()
  t.assert.ok(fastify.addContentTypeParser)
})

test('contentTypeParser should add a custom parser', (t, mainTestDone) => {
  t.plan(3)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.options('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.addContentTypeParser('application/jsoff', function (req, payload, done) {
    jsonParser(payload, function (err, body) {
      done(err, body)
    })
  })

  fastify.listen({ port: 0 }, err => {
    t.assert.ifError(err)

    const completion = waitForCb({ steps: 2 })

    t.after(() => fastify.close())

    t.test('in POST', (t, testDone) => {
Repository: fastify/fastify
File: test/custom-parser.0.test.js (JavaScript)

Code before:
        t.assert.strictEqual(response.statusCode, 200)
        t.assert.strictEqual(body.toString(), JSON.stringify({ hello: 'world' }))
        testDone()
        completion.stepIn()
      })
    })

    t.test('in OPTIONS', (t, testDone) => {
      t.plan(3)

      sget({
        method: 'OPTIONS',
        url: getServerUrl(fastify),
        body: '{"hello":"world"}',
        headers: {
          'Content-Type': 'application/jsoff'
        }
      }, (err, response, body) => {
        t.assert.ifError(err)
        t.assert.strictEqual(response.statusCode, 200)
        t.assert.strictEqual(body.toString(), JSON.stringify({ hello: 'world' }))
        testDone()
        completion.stepIn()
      })
    })
    completion.patience.then(testDone)
  })
})

test('contentTypeParser should handle multiple custom parsers', (t, testDone) => {
  t.plan(7)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.post('/hello', (req, reply) => {
    reply.send(req.body)
  })

  function customParser (req, payload, done) {
    jsonParser(payload, function (err, body) {
      done(err, body)
    })
  }

  fastify.addContentTypeParser('application/jsoff', customParser)
  fastify.addContentTypeParser('application/ffosj', customParser)

  fastify.listen({ port: 0 }, err => {

Review comment (suggestion):
```suggestion
    completion.patience.then(mainTestDone)
```

Code after:
        t.assert.strictEqual(response.statusCode, 200)
        t.assert.strictEqual(body.toString(), JSON.stringify({ hello: 'world' }))
        testDone()
        completion.stepIn()
      })
    })

    t.test('in OPTIONS', (t, testDone) => {
      t.plan(3)

      sget({
        method: 'OPTIONS',
        url: getServerUrl(fastify),
        body: '{"hello":"world"}',
        headers: {
          'Content-Type': 'application/jsoff'
        }
      }, (err, response, body) => {
        t.assert.ifError(err)
        t.assert.strictEqual(response.statusCode, 200)
        t.assert.strictEqual(body.toString(), JSON.stringify({ hello: 'world' }))
        testDone()
        completion.stepIn()
      })
    })
    completion.patience.then(mainTestDone)
  })
})

test('contentTypeParser should handle multiple custom parsers', (t, testDone) => {
  t.plan(7)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.post('/hello', (req, reply) => {
    reply.send(req.body)
  })

  function customParser (req, payload, done) {
    jsonParser(payload, function (err, body) {
      done(err, body)
    })
  }

  fastify.addContentTypeParser('application/jsoff', customParser)
  fastify.addContentTypeParser('application/ffosj', customParser)

  fastify.listen({ port: 0 }, err => {
Repository: fastify/fastify
File: test/promises.test.js (JavaScript)

Code before:
    reply.send(new Error('kaboom'))
  })
  return reply
})

fastify.get('/return-reply', opts, function (req, reply) {
  return reply.send({ hello: 'world' })
})

// Setup Fastify to listen before tests
before(async () => {
  try {
    await fastify.listen({ port: 0 })
  } catch (err) {
    throw new Error('Failed to start Fastify server')
  }
})

// Cleanup after all tests
after(() => {
  fastify.close()
})

test('shorthand - sget return promise es6 get', async (t) => {
  const res = await new Promise((resolve, reject) => {
    sget(
      {
        method: 'GET',
        url: 'http://localhost:' + fastify.server.address().port + '/return',
      },
      (err, response, body) => {
        if (err) reject(err)
        resolve({ response, body })
      }
    )
  })

  t.assert.strictEqual(res.response.statusCode, 200)
  t.assert.strictEqual(res.response.headers['content-length'], '' + res.body.length)
  t.assert.deepStrictEqual(JSON.parse(res.body), { hello: 'world' })
})

test('shorthand - sget promise es6 get return error', async (t) => {
  const res = await new Promise((resolve, reject) => {
    sget(
      {
        method: 'GET',
        url: 'http://localhost:' + fastify.server.address().port + '/return-error',
      },
      (err, response) => {
        if (err) reject(err)

Review comment (refactor):
We may think to create an `sgetAsync(options)` utility in the toolbox - it is a recurring code to write this one

Code after:

fastify.get('/thenable-error', opts, function (req, reply) {
  setImmediate(function () {
    reply.send(new Error('kaboom'))
  })
  return reply
})

fastify.get('/return-reply', opts, function (req, reply) {
  return reply.send({ hello: 'world' })
})

fastify.listen({ port: 0 }, err => {
  assert.ifError(err)

  test('shorthand - sget return promise es6 get', (t, done) => {
    t.plan(4)
    sget({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/return'
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 200)
      t.assert.strictEqual(response.headers['content-length'], '' + body.length)
      t.assert.deepStrictEqual(JSON.parse(body), { hello: 'world' })
      done()
    })
  })

  test('shorthand - sget promise es6 get return error', (t, done) => {
    t.plan(2)
    sget({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/return-error'
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 500)
      done()
    })
  })

  test('sget promise double send', (t, done) => {
    t.plan(3)
    sget({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/double'
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 200)
      t.assert.deepStrictEqual(JSON.parse(body), { hello: '42' })
      done()
Repository: fastify/fastify
File: test/promises.test.js (JavaScript)

Code before:
})

// Setup Fastify to listen before tests
before(async () => {
  try {
    await fastify.listen({ port: 0 })
  } catch (err) {
    throw new Error('Failed to start Fastify server')
  }
})

// Cleanup after all tests
after(() => {
  fastify.close()
})

test('shorthand - sget return promise es6 get', async (t) => {
  const res = await new Promise((resolve, reject) => {
    sget(
      {
        method: 'GET',
        url: 'http://localhost:' + fastify.server.address().port + '/return',
      },
      (err, response, body) => {
        if (err) reject(err)
        resolve({ response, body })
      }
    )
  })

  t.assert.strictEqual(res.response.statusCode, 200)
  t.assert.strictEqual(res.response.headers['content-length'], '' + res.body.length)
  t.assert.deepStrictEqual(JSON.parse(res.body), { hello: 'world' })
})

test('shorthand - sget promise es6 get return error', async (t) => {
  const res = await new Promise((resolve, reject) => {
    sget(
      {
        method: 'GET',
        url: 'http://localhost:' + fastify.server.address().port + '/return-error',
      },
      (err, response) => {
        if (err) reject(err)
        resolve({ response })
      }
    )
  })

  t.assert.strictEqual(res.response.statusCode, 500)
})

Review comment (suggestion):
in case of error, we resolve the promise twice because after `reject(err)` we don't return and we run `resolve()` too.

Code after:

fastify.get('/return-reply', opts, function (req, reply) {
  return reply.send({ hello: 'world' })
})

fastify.listen({ port: 0 }, err => {
  assert.ifError(err)

  test('shorthand - sget return promise es6 get', (t, done) => {
    t.plan(4)
    sget({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/return'
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 200)
      t.assert.strictEqual(response.headers['content-length'], '' + body.length)
      t.assert.deepStrictEqual(JSON.parse(body), { hello: 'world' })
      done()
    })
  })

  test('shorthand - sget promise es6 get return error', (t, done) => {
    t.plan(2)
    sget({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/return-error'
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 500)
      done()
    })
  })

  test('sget promise double send', (t, done) => {
    t.plan(3)
    sget({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/double'
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 200)
      t.assert.deepStrictEqual(JSON.parse(body), { hello: '42' })
      done()
    })
  })

  test('thenable', (t, done) => {
    t.plan(4)
    sget({
      method: 'GET',
Repository: fastify/fastify
File: lib/validation.js (JavaScript)

Code before:
}

function wrapValidationError (result, dataVar, schemaErrorFormatter) {
  if (result instanceof Error) {
    result.statusCode = result.statusCode || 400
    result.code = result.code || 'FST_ERR_VALIDATION'
    result.validationContext = result.validationContext || dataVar
    return result
  }

  const error = schemaErrorFormatter(result, dataVar)
  error.statusCode = error.statusCode || 400
  error.code = error.code || 'FST_ERR_VALIDATION'
  error.validation = result
  error.validationContext = dataVar
  return error
}

/**
 * simple function to retrieve the essence media type
 * @param {string} header
 * @returns {string} Mimetype string.
 */
function getEssenceMediaType (header) {
  if (!header) return ''
  return header.split(/[ ;]/)[0].trim().toLowerCase()
}

module.exports = {
  symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema },
  compileSchemasForValidation,
  compileSchemasForSerialization,
  validate
}


Review comment (suggestion):
```suggestion
  return header.split(/[ ;]/, 1)[0].trim().toLowerCase()
```

Code after:
}

function wrapValidationError (result, dataVar, schemaErrorFormatter) {
  if (result instanceof Error) {
    result.statusCode = result.statusCode || 400
    result.code = result.code || 'FST_ERR_VALIDATION'
    result.validationContext = result.validationContext || dataVar
    return result
  }

  const error = schemaErrorFormatter(result, dataVar)
  error.statusCode = error.statusCode || 400
  error.code = error.code || 'FST_ERR_VALIDATION'
  error.validation = result
  error.validationContext = dataVar
  return error
}

/**
 * simple function to retrieve the essence media type
 * @param {string} header
 * @returns {string} Mimetype string.
 */
function getEssenceMediaType (header) {
  if (!header) return ''
  return header.split(/[ ;]/, 1)[0].trim().toLowerCase()
}

module.exports = {
  symbols: { bodySchema, querystringSchema, responseSchema, paramsSchema, headersSchema },
  compileSchemasForValidation,
  compileSchemasForSerialization,
  validate
}
Repository: fastify/fastify
File: test/output-validation.test.js (JavaScript)

Code before:
        properties: {
          hello: {
            type: 'string'
          }
        }
      },
      '2xx': {
        type: 'object',
        properties: {
          hello: {
            type: 'number'
          }
        }
      }
    }
  }
}

test('shorthand - output string', t => {
  t.plan(1)
  try {
    fastify.get('/string', opts, function (req, reply) {
      reply.code(200).send({ hello: 'world' })
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('shorthand - output number', t => {
  t.plan(1)
  try {
    fastify.get('/number', opts, function (req, reply) {
      reply.code(201).send({ hello: 55 })
    })
    t.pass()
  } catch (e) {
    t.fail()
  }
})

test('wrong object for schema - output', t => {
  t.plan(1)
  try {
    fastify.get('/wrong-object-for-schema', opts, function (req, reply) {
      // will send { }
      reply.code(201).send({ hello: 'world' })
    })
    t.pass()
  } catch (e) {

Review comment (suggestion):
Maybe we should use [assert.doesNotThrow()](https://nodejs.org/api/assert.html#assertdoesnotthrowfn-error-message)?

Same for similar tests.

Code after:
          hello: {
            type: 'string'
          }
        }
      },
      '2xx': {
        type: 'object',
        properties: {
          hello: {
            type: 'number'
          }
        }
      }
    }
  }
}

test('shorthand - output string', t => {
  t.plan(1)
  try {
    fastify.get('/string', opts, function (req, reply) {
      reply.code(200).send({ hello: 'world' })
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }
})

test('shorthand - output number', t => {
  t.plan(1)
  try {
    fastify.get('/number', opts, function (req, reply) {
      reply.code(201).send({ hello: 55 })
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }
})

test('wrong object for schema - output', t => {
  t.plan(1)
  try {
    fastify.get('/wrong-object-for-schema', opts, function (req, reply) {
      // will send { }
      reply.code(201).send({ hello: 'world' })
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
Repository: fastify/fastify
File: test/toolkit.js (JavaScript)

Code before:
'use strict'

exports.sequence = function (steps) {
  let index = 0

  function next (stop) {
    if (index >= steps.length) {
      if (stop) {
        stop()
      }

      return
    }

    const step = steps[index++]

    step(next)
  }

  next()
}

exports.waitForCb = function (options) {
  let count = null
  let done = false
  let iResolve
  let iReject

  function stepIn () {
    if (done) {
      iReject(new Error('Unexpected done call'))
      return
    }

    if (--count) {
      return
    }

    done = true
    iResolve()
  }

  const patience = new Promise((resolve, reject) => {
    iResolve = resolve
    iReject = reject
  })

  count = options.steps || 1

Review comment (bug):
The problem for my use case is that `waitForCb` doesn't guarantee that the code is executed sequentially, which can lead to race conditions and unpredictable assertions count.

Code after:
'use strict'

exports.waitForCb = function (options) {
  let count = null
  let done = false
  let iResolve
  let iReject

  function stepIn () {
    if (done) {
      iReject(new Error('Unexpected done call'))
      return
    }

    if (--count) {
      return
    }

    done = true
    iResolve()
  }

  const patience = new Promise((resolve, reject) => {
    iResolve = resolve
    iReject = reject
  })

  count = options.steps || 1
  done = false

  return { stepIn, patience }
}

exports.partialDeepStrictEqual = function partialDeepStrictEqual (actual, expected) {
  if (typeof expected !== 'object' || expected === null) {
    return actual === expected
  }

  if (typeof actual !== 'object' || actual === null) {
    return false
  }

  if (Array.isArray(expected)) {
    if (!Array.isArray(actual)) return false
    if (expected.length > actual.length) return false

    for (let i = 0; i < expected.length; i++) {
      if (!partialDeepStrictEqual(actual[i], expected[i])) {
Repository: fastify/fastify
File: test/hooks-async.test.js (JavaScript)

Code before:
  })

  fastify.register(plugin)
  fastify.get('/', (req, reply) => reply.send('ok'))

  async function plugin (fastify, opts) {
    fastify.decorate('foo', 'bar')
    fastify.get('/nested', (req, reply) => reply.send('ok'))
  }

  await fastify.inject({ method: 'GET', path: '/' })
  await fastify.inject({ method: 'GET', path: '/nested' })
  await fastify.inject({ method: 'GET', path: '/' })
  await fastify.inject({ method: 'GET', path: '/nested' })
})

describe('preSerializationEnd should handle errors if the serialize method throws', () => {
  test('works with sync preSerialization', (t, testDone) => {
    t.plan(3)
    const fastify = Fastify()

    fastify.addHook('preSerialization', (request, reply, payload, done) => {
      t.assert.ok('called')
      done(null, payload)
    })

    fastify.post('/', {
      handler (req, reply) { reply.send({ notOk: true }) },
      schema: { response: { 200: { required: ['ok'], properties: { ok: { type: 'boolean' } } } } }
    })

    fastify.inject({
      method: 'POST',
      url: '/'
    }, (err, res) => {
      t.assert.ifError(err)
      t.assert.notEqual(res.statusCode, 200)
      testDone()
    })
  })

  test('works with async preSerialization', (t, testDone) => {
    t.plan(3)
    const fastify = Fastify()

    fastify.addHook('preSerialization', async (request, reply, payload) => {
      t.assert.ok('called')
      return payload
    })

    fastify.post('/', {

Review comment (suggestion):
It may be obvious that this has been called, I'd rather be a little more careful, tell me if I should delete these assertions in `preSerialization` hook tests.

Code after:
    }
  })

  fastify.register(plugin)
  fastify.get('/', (req, reply) => reply.send('ok'))

  async function plugin (fastify, opts) {
    fastify.decorate('foo', 'bar')
    fastify.get('/nested', (req, reply) => reply.send('ok'))
  }

  await fastify.inject({ method: 'GET', path: '/' })
  await fastify.inject({ method: 'GET', path: '/nested' })
  await fastify.inject({ method: 'GET', path: '/' })
  await fastify.inject({ method: 'GET', path: '/nested' })
})

describe('preSerializationEnd should handle errors if the serialize method throws', () => {
  test('works with sync preSerialization', (t, testDone) => {
    t.plan(3)
    const fastify = Fastify()

    fastify.addHook('preSerialization', (request, reply, payload, done) => {
      t.assert.ok('called')
      done(null, payload)
    })

    fastify.post('/', {
      handler (req, reply) { reply.send({ notOk: true }) },
      schema: { response: { 200: { required: ['ok'], properties: { ok: { type: 'boolean' } } } } }
    })

    fastify.inject({
      method: 'POST',
      url: '/'
    }, (err, res) => {
      t.assert.ifError(err)
      t.assert.notEqual(res.statusCode, 200)
      testDone()
    })
  })

  test('works with async preSerialization', (t, testDone) => {
    t.plan(3)
    const fastify = Fastify()

    fastify.addHook('preSerialization', async (request, reply, payload) => {
      t.assert.ok('called')
      return payload
    })