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

Code before:
test('missing schema - delete', t => {
  t.plan(1)
  try {
    fastify.delete('/missing', function (req, reply) {
      reply.code(200).send({ hello: 'world' })
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }
})

test('body - delete', t => {
  t.plan(1)
  try {
    fastify.delete('/body', bodySchema, function (req, reply) {
      reply.send(req.body)
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }
})

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

  test('shorthand - request delete', (t, done) => {
    t.plan(4)
    sget({
      method: 'DELETE',
      url: 'http://localhost:' + fastify.server.address().port
    }, (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 - request delete params schema', (t, done) => {
    t.plan(4)
    sget({
      method: 'DELETE',
      url: 'http://localhost:' + fastify.server.address().port + '/params/world/123'
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 200)
      t.assert.strictEqual(response.headers['content-length'], '' + body.length)

Review comment (suggestion):
`ifError` doesn't exist in `t`?

```suggestion
  t.assert.ifError(err)
```

Code after:
  t.plan(1)
  try {
    fastify.delete('/missing', function (req, reply) {
      reply.code(200).send({ hello: 'world' })
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }
})

test('body - delete', t => {
  t.plan(1)
  try {
    fastify.delete('/body', bodySchema, function (req, reply) {
      reply.send(req.body)
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }
})

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

  test('shorthand - request delete', (t, done) => {
    t.plan(4)
    sget({
      method: 'DELETE',
      url: 'http://localhost:' + fastify.server.address().port
    }, (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 - request delete params schema', (t, done) => {
    t.plan(4)
    sget({
      method: 'DELETE',
      url: 'http://localhost:' + fastify.server.address().port + '/params/world/123'
    }, (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), { foo: 'world', test: 123 })
Repository: fastify/fastify
File: test/delete.test.js (JavaScript)

Code before:
'use strict'

const { ifError } = require('node:assert')
const t = require('node:test')
const test = t.test
const sget = require('simple-get').concat
const fastify = require('..')()

const schema = {
  schema: {
    response: {
      '2xx': {
        type: 'object',
        properties: {
          hello: {
            type: 'string'
          }
        }
      }
    }
  }
}

const querySchema = {
  schema: {
    querystring: {
      type: 'object',
      properties: {
        hello: {
          type: 'integer'

Review comment (suggestion):
```suggestion
const test = require('node:test')
```

Code after:
'use strict'

const assert = require('node:assert')
const { test } = require('node:test')
const sget = require('simple-get').concat
const fastify = require('..')()

const schema = {
  schema: {
    response: {
      '2xx': {
        type: 'object',
        properties: {
          hello: {
            type: 'string'
          }
        }
      }
    }
  }
}

const querySchema = {
  schema: {
    querystring: {
      type: 'object',
      properties: {
        hello: {
          type: 'integer'
        }
Repository: fastify/fastify
File: test/upgrade.test.js (JavaScript)

Code before:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')
const { connect } = require('node:net')
const { once } = require('node:events')
const dns = require('node:dns').promises

async function setup (t) {
  const localAddresses = await dns.lookup('localhost', { all: true })
  if (localAddresses.length === 1) {
    t.skip('requires both IPv4 and IPv6')
    return
  }

  test('upgrade to both servers', async t => {
    t.plan(2)
    const fastify = Fastify()
    fastify.server.on('upgrade', (req, socket, head) => {
      t.assert.ok(`upgrade event ${JSON.stringify(socket.address())}`)
      socket.end()
    })
    fastify.get('/', (req, res) => {
    })
    await fastify.listen()
    t.after(() => fastify.close())

    {
      const client = connect(fastify.server.address().port, '127.0.0.1')
      client.write('GET / HTTP/1.1\r\n')
      client.write('Upgrade: websocket\r\n')
      client.write('Connection: Upgrade\r\n')
      client.write('Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n')
      client.write('Sec-WebSocket-Protocol: com.xxx.service.v1\r\n')
      client.write('Sec-WebSocket-Version: 13\r\n\r\n')
      client.write('\r\n\r\n')
      await once(client, 'close')

Review comment (suggestion):
`t` is undefined here.

I think the `setup` function should become a `test()` and then:
https://nodejs.org/api/test.html#contextskipmessage

Code after:
'use strict'

const { describe, test } = require('node:test')
const Fastify = require('..')
const { connect } = require('node:net')
const { once } = require('node:events')
const dns = require('node:dns').promises

describe('upgrade to both servers', async t => {
  const localAddresses = await dns.lookup('localhost', { all: true })
  if (localAddresses.length === 1) {
    t.skip('requires both IPv4 and IPv6')
    return
  }

  await test('upgrade IPv4 and IPv6', async t => {
    t.plan(2)

    const fastify = Fastify()
    fastify.server.on('upgrade', (req, socket, head) => {
      t.assert.ok(`upgrade event ${JSON.stringify(socket.address())}`)
      socket.end()
    })

    fastify.get('/', (req, res) => {
      res.send()
    })

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

    {
      const clientIPv4 = connect(fastify.server.address().port, '127.0.0.1')
      clientIPv4.write('GET / HTTP/1.1\r\n')
      clientIPv4.write('Upgrade: websocket\r\n')
      clientIPv4.write('Connection: Upgrade\r\n')
      clientIPv4.write('Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n')
Repository: fastify/fastify
File: lib/contentTypeParser.js (JavaScript)

Code before:
    }

    if (asString === false) {
      body = Buffer.concat(body)
    }

    const result = parser.fn(request, body, done)
    if (result && typeof result.then === 'function') {
      result.then(body => done(null, body), done)
    }
  }
}

function getDefaultJsonParser (onProtoPoisoning, onConstructorPoisoning) {
  const parseOptions = { protoAction: onProtoPoisoning, constructorAction: onConstructorPoisoning }

  return defaultJsonParser

  function defaultJsonParser (req, body, done) {
    if (body.length === 0) {
      done(new FST_ERR_CTP_EMPTY_JSON_BODY(), undefined)
      return
    }
    let json
    try {
      json = secureJsonParse(body, parseOptions)
    } catch (err) {
      return done(new FST_ERR_CTP_INVALID_JSON_BODY(), undefined)
    }
    done(null, json)
  }
}

function defaultPlainTextParser (req, body, done) {
  done(null, body)
}

function Parser (asString, asBuffer, bodyLimit, fn) {
  this.asString = asString
  this.asBuffer = asBuffer
  this.bodyLimit = bodyLimit
  this.fn = fn
}

function buildContentTypeParser (c) {
  const contentTypeParser = new ContentTypeParser()
  contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]
  contentTypeParser.customParsers = new Map(c.customParsers.entries())
  contentTypeParser.parserList = c.parserList.slice()
  contentTypeParser.parserRegExpList = c.parserRegExpList.slice()
  return contentTypeParser

Review comment (suggestion):
```suggestion
      done(null, secureJsonParse(body, parseOptions))
```

Code after:
    }

    if (asString === false) {
      body = Buffer.concat(body)
    }

    const result = parser.fn(request, body, done)
    if (result && typeof result.then === 'function') {
      result.then(body => done(null, body), done)
    }
  }
}

function getDefaultJsonParser (onProtoPoisoning, onConstructorPoisoning) {
  const parseOptions = { protoAction: onProtoPoisoning, constructorAction: onConstructorPoisoning }

  return defaultJsonParser

  function defaultJsonParser (req, body, done) {
    if (body.length === 0) {
      done(new FST_ERR_CTP_EMPTY_JSON_BODY(), undefined)
      return
    }
    try {
      done(null, secureJsonParse(body, parseOptions))
    } catch (err) {
      done(new FST_ERR_CTP_INVALID_JSON_BODY(), undefined)
    }
  }
}

function defaultPlainTextParser (req, body, done) {
  done(null, body)
}

function Parser (asString, asBuffer, bodyLimit, fn) {
  this.asString = asString
  this.asBuffer = asBuffer
  this.bodyLimit = bodyLimit
  this.fn = fn
}

function buildContentTypeParser (c) {
  const contentTypeParser = new ContentTypeParser()
  contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]
  contentTypeParser.customParsers = new Map(c.customParsers.entries())
  contentTypeParser.parserList = c.parserList.slice()
  contentTypeParser.parserRegExpList = c.parserRegExpList.slice()
  return contentTypeParser
}
Repository: fastify/fastify
File: test/throw.test.js (JavaScript)

Code before:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')

test('Fastify should throw on wrong options', async (t) => {
  t.plan(2)
  try {
    Fastify('lol')
    t.assert.fail()
  } catch (e) {
    t.assert.strictEqual(e.message, 'Options must be an object')
    t.assert.ok(true)
  }
})

test('Fastify should throw on multiple assignment to the same route', async (t) => {
  t.plan(1)
  const fastify = Fastify()

  fastify.get('/', () => {})

  try {
    fastify.get('/', () => {})
    t.assert.fail('Should throw fastify duplicated route declaration')
  } catch (error) {
    t.assert.strictEqual(error.code, 'FST_ERR_DUPLICATED_ROUTE')
  }
})

test('Fastify should throw for an invalid schema, printing the error route - headers', async (t) => {

Review comment (bug):
there are not async operations
```suggestion
test('Fastify should throw on wrong options', (t) => {
```

Code after:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')

test('Fastify should throw on wrong options', (t) => {
  t.plan(2)
  try {
    Fastify('lol')
    t.assert.fail()
  } catch (e) {
    t.assert.strictEqual(e.message, 'Options must be an object')
    t.assert.ok(true)
  }
})

test('Fastify should throw on multiple assignment to the same route', (t) => {
  t.plan(1)
  const fastify = Fastify()

  fastify.get('/', () => {})

  try {
    fastify.get('/', () => {})
    t.assert.fail('Should throw fastify duplicated route declaration')
  } catch (error) {
    t.assert.strictEqual(error.code, 'FST_ERR_DUPLICATED_ROUTE')
  }
})

test('Fastify should throw for an invalid schema, printing the error route - headers', async (t) => {
Repository: fastify/fastify
File: test/throw.test.js (JavaScript)

Code before:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')

test('Fastify should throw on wrong options', async (t) => {
  t.plan(2)
  try {
    Fastify('lol')
    t.assert.fail()
  } catch (e) {
    t.assert.strictEqual(e.message, 'Options must be an object')
    t.assert.ok(true)
  }
})

test('Fastify should throw on multiple assignment to the same route', async (t) => {
  t.plan(1)
  const fastify = Fastify()

  fastify.get('/', () => {})

  try {
    fastify.get('/', () => {})
    t.assert.fail('Should throw fastify duplicated route declaration')
  } catch (error) {
    t.assert.strictEqual(error.code, 'FST_ERR_DUPLICATED_ROUTE')
  }
})

test('Fastify should throw for an invalid schema, printing the error route - headers', async (t) => {
  t.plan(2)

  const badSchema = {
    type: 'object',
    properties: {
      bad: {
        type: 'bad-type'
      }
    }
  }


Review comment (suggestion):
```suggestion
test('Fastify should throw on multiple assignment to the same route', (t) => {
```

Code after:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')

test('Fastify should throw on wrong options', (t) => {
  t.plan(2)
  try {
    Fastify('lol')
    t.assert.fail()
  } catch (e) {
    t.assert.strictEqual(e.message, 'Options must be an object')
    t.assert.ok(true)
  }
})

test('Fastify should throw on multiple assignment to the same route', (t) => {
  t.plan(1)
  const fastify = Fastify()

  fastify.get('/', () => {})

  try {
    fastify.get('/', () => {})
    t.assert.fail('Should throw fastify duplicated route declaration')
  } catch (error) {
    t.assert.strictEqual(error.code, 'FST_ERR_DUPLICATED_ROUTE')
  }
})

test('Fastify should throw for an invalid schema, printing the error route - headers', async (t) => {
  t.plan(1)

  const badSchema = {
    type: 'object',
    properties: {
      bad: {
        type: 'bad-type'
      }
    }
  }
  const fastify = Fastify()
Repository: fastify/fastify
File: test/throw.test.js (JavaScript)

Code before:
    done()
  }, { prefix: 'hello' })

  await fastify.ready().catch(err => {
    t.assert.strictEqual(err.code, 'FST_ERR_SCH_VALIDATION_BUILD')
    t.assert.match(err.message, /Failed building the validation schema for POST: \/hello\/form/)
  })
})

test('Should throw on unsupported method', async (t) => {
  t.plan(1)
  const fastify = Fastify()
  try {
    fastify.route({
      method: 'TROLL',
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.assert.fail()
  } catch (e) {
    t.assert.ok(true)
  }
})

test('Should throw on missing handler', async (t) => {
  t.plan(1)
  const fastify = Fastify()
  try {
    fastify.route({
      method: 'GET',
      url: '/'
    })
    t.assert.fail()
  } catch (e) {
    t.assert.ok(true)
  }
})

test('Should throw if one method is unsupported', async (t) => {
  t.plan(1)
  const fastify = Fastify()
  try {
    fastify.route({
      method: ['GET', 'TROLL'],
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.assert.fail()
  } catch (e) {

Review comment (suggestion):
```suggestion
test('Should throw on missing handler', (t) => {
```

Code after:
  }, { prefix: 'hello' })

  await t.assert.rejects(fastify.ready(), {
    code: 'FST_ERR_SCH_VALIDATION_BUILD',
    message: /Failed building the validation schema for POST: \/hello\/form/
  })
})

test('Should throw on unsupported method', async (t) => {
  t.plan(1)
  const fastify = Fastify()
  try {
    fastify.route({
      method: 'TROLL',
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.assert.fail()
  } catch (e) {
    t.assert.ok(true)
  }
})

test('Should throw on missing handler', (t) => {
  t.plan(1)
  const fastify = Fastify()
  try {
    fastify.route({
      method: 'GET',
      url: '/'
    })
    t.assert.fail()
  } catch (e) {
    t.assert.ok(true)
  }
})

test('Should throw if one method is unsupported', async (t) => {
  t.plan(1)
  const fastify = Fastify()
  try {
    fastify.route({
      method: ['GET', 'TROLL'],
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.assert.fail()
  } catch (e) {
    t.assert.ok(true)
Repository: fastify/fastify
File: test/throw.test.js (JavaScript)

Code before:
test('Should not throw on duplicate decorator encapsulation', t => {
  t.plan(1)

  const fastify = Fastify()
  const foo2Obj = {}

  fastify.decorate('foo2', foo2Obj)

  fastify.register(function (fastify, opts, done) {
    t.doesNotThrow(() => {
      fastify.decorate('foo2', foo2Obj)
    })
    done()
  })

  fastify.ready()
})

test('Should throw on duplicate request decorator', t => {
  t.plan(2)

  const fastify = Fastify()

  fastify.decorateRequest('foo', null)
  try {
    fastify.decorateRequest('foo', null)
    t.fail()
  } catch (e) {
    t.equal(e.code, 'FST_ERR_DEC_ALREADY_PRESENT')
    t.equal(e.message, 'The decorator \'foo\' has already been added!')
  }
})

test('Should throw if request decorator dependencies are not met', t => {
  t.plan(2)

  const fastify = Fastify()

  try {
    fastify.decorateRequest('bar', null, ['world'])
    t.fail()
  } catch (e) {
    t.equal(e.code, 'FST_ERR_DEC_MISSING_DEPENDENCY')
    t.equal(e.message, 'The decorator is missing dependency \'world\'.')
  }
})

test('Should throw on duplicate reply decorator', t => {
  t.plan(1)

  const fastify = Fastify()

Review comment (refactor):
If someone in future would like to clean up the test, here we can use:

```js
t.assert.throws(()=>{fastify.decorateRequest('foo', null)}, {
    code: 'FST_ERR_DEC_ALREADY_PRESENT',
    message: 'The decorator \'foo\' has already been added!'
  })
```

https://nodejs.org/api/assert.html#assertthrowsfn-error-message

But out of scope of this PR

Code after:
  const foo2Obj = {}

  fastify.decorate('foo2', foo2Obj)

  fastify.register(function (fastify, opts, done) {
    t.assert.doesNotThrow(() => {
      fastify.decorate('foo2', foo2Obj)
    })
    done()
  })

  await fastify.ready()
})

test('Should throw on duplicate request decorator', async (t) => {
  t.plan(2)

  const fastify = Fastify()

  fastify.decorateRequest('foo', null)
  try {
    fastify.decorateRequest('foo', null)
    t.assert.fail()
  } catch (e) {
    t.assert.strictEqual(e.code, 'FST_ERR_DEC_ALREADY_PRESENT')
    t.assert.strictEqual(e.message, 'The decorator \'foo\' has already been added!')
  }
})

test('Should throw if request decorator dependencies are not met', async (t) => {
  t.plan(2)

  const fastify = Fastify()

  try {
    fastify.decorateRequest('bar', null, ['world'])
    t.assert.fail()
  } catch (e) {
    t.assert.strictEqual(e.code, 'FST_ERR_DEC_MISSING_DEPENDENCY')
    t.assert.strictEqual(e.message, 'The decorator is missing dependency \'world\'.')
  }
})

test('Should throw on duplicate reply decorator', async (t) => {
  t.plan(1)

  const fastify = Fastify()

  fastify.decorateReply('foo', null)
  try {
    fastify.decorateReply('foo', null)
Repository: fastify/fastify
File: test/custom-parser.4.test.js (JavaScript)

Code before:
      t.assert.equal(body.toString(), 'xml')
    })

    sget({
      method: 'POST',
      url: getServerUrl(fastify),
      body: '',
      headers: {
        'Content-Type': 'image/png'
      }
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 415)
    })

    sget({
      method: 'POST',
      url: getServerUrl(fastify),
      body: '{test: "test"}',
      headers: {
        'Content-Type': 'application/json'
      }
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 415)
      testDone()
    })
  })
})

test('removeContentTypeParser should support encapsulation', (t, done) => {
  t.plan(6)

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

  fastify.addContentTypeParser('application/xml', function (req, payload, done) {
    payload.on('data', () => {})
    payload.on('end', () => {
      done(null, 'xml')
    })
  })

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

  fastify.register(function (instance, options, done) {
    instance.removeContentTypeParser('application/xml')

    instance.post('/encapsulated', (req, reply) => {

Review comment (refactor):
This http call could run `testDone` before the other concurrent sget ends.
We must use the `test/toolkit.js` utility here.

Example: https://github.com/fastify/fastify/pull/6021/files#diff-6a98dbdd7ca9fb8e0adfcc8787c950f65344cd9581437118754f4adb1a791f7dR75

Code after:
      body: '<?xml version="1.0">',
      headers: {
        'Content-Type': 'application/xml'
      }
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 200)
      t.assert.equal(body.toString(), 'xml')
      completion.stepIn()
    })

    sget({
      method: 'POST',
      url: getServerUrl(fastify),
      body: '',
      headers: {
        'Content-Type': 'image/png'
      }
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 415)
      completion.stepIn()
    })

    sget({
      method: 'POST',
      url: getServerUrl(fastify),
      body: '{test: "test"}',
      headers: {
        'Content-Type': 'application/json'
      }
    }, (err, response, body) => {
      t.assert.ifError(err)
      t.assert.strictEqual(response.statusCode, 415)
      completion.stepIn()
    })
    completion.patience.then(testDone)
  })
})

test('removeContentTypeParser should support encapsulation', (t, testDone) => {
  t.plan(6)

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

  fastify.addContentTypeParser('application/xml', function (req, payload, done) {
    payload.on('data', () => {})
    payload.on('end', () => {
      done(null, 'xml')
    })
Repository: fastify/fastify
File: test/fastify-instance.test.js (JavaScript)

Code before:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')
const os = require('node:os')

const {
  kOptions,
  kErrorHandler,
  kChildLoggerFactory,
  kState
} = require('../lib/symbols')

const hasIPv6 = Object.values(os.networkInterfaces()).flat().some(({ family }) => family === 'IPv6')

test('root fastify instance is an object', t => {
  t.plan(1)
  t.assert.strictEqual(typeof Fastify(), 'object')
})

test('fastify instance should contains ajv options', t => {
  t.plan(1)
  const fastify = Fastify({
    ajv: {
      customOptions: {
        nullable: false
      }
    }
  })
  t.assert.deepStrictEqual(fastify[kOptions].ajv, {
    customOptions: {
      nullable: false
    },
    plugins: []
  })
})

test('fastify instance should contains ajv options.plugins nested arrays', t => {
  t.plan(1)

Review comment (suggestion):
```suggestion
const isIPv6Missing = !Object.values(os.networkInterfaces()).flat().some(({ family }) => family === 'IPv6')
```

Code after:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')
const os = require('node:os')

const {
  kOptions,
  kErrorHandler,
  kChildLoggerFactory,
  kState
} = require('../lib/symbols')

const isIPv6Missing = !Object.values(os.networkInterfaces()).flat().some(({ family }) => family === 'IPv6')

test('root fastify instance is an object', t => {
  t.plan(1)
  t.assert.strictEqual(typeof Fastify(), 'object')
})

test('fastify instance should contains ajv options', t => {
  t.plan(1)
  const fastify = Fastify({
    ajv: {
      customOptions: {
        nullable: false
      }
    }
  })
  t.assert.deepStrictEqual(fastify[kOptions].ajv, {
    customOptions: {
      nullable: false
    },
    plugins: []
  })
})

test('fastify instance should contains ajv options.plugins nested arrays', t => {
  t.plan(1)