Skip to content
Myr

express.json.js

This file

Path

test/express.json.js

665 lines · 20.7 KiB · JavaScript

Last changed by

tests: use strict modeDouglas Christopher Wilsonbefore adoptiona659137

History of this file

Take it

1'use strict'23var assert = require('assert')4var Buffer = require('safe-buffer').Buffer5var express = require('..')6var request = require('supertest')78describe('express.json()', function () {9  it('should parse JSON', function (done) {10    request(createApp())11      .post('/')12      .set('Content-Type', 'application/json')13      .send('{"user":"tobi"}')14      .expect(200, '{"user":"tobi"}', done)15  })1617  it('should handle Content-Length: 0', function (done) {18    request(createApp())19      .post('/')20      .set('Content-Type', 'application/json')21      .set('Content-Length', '0')22      .expect(200, '{}', done)23  })2425  it('should handle empty message-body', function (done) {26    request(createApp())27      .post('/')28      .set('Content-Type', 'application/json')29      .set('Transfer-Encoding', 'chunked')30      .expect(200, '{}', done)31  })3233  it('should handle no message-body', function (done) {34    request(createApp())35      .post('/')36      .set('Content-Type', 'application/json')37      .unset('Transfer-Encoding')38      .expect(200, '{}', done)39  })4041  it('should 400 when invalid content-length', function (done) {42    var app = express()4344    app.use(function (req, res, next) {45      req.headers['content-length'] = '20' // bad length46      next()47    })4849    app.use(express.json())5051    app.post('/', function (req, res) {52      res.json(req.body)53    })5455    request(app)56      .post('/')57      .set('Content-Type', 'application/json')58      .send('{"str":')59      .expect(400, /content length/, done)60  })6162  it('should handle duplicated middleware', function (done) {63    var app = express()6465    app.use(express.json())66    app.use(express.json())6768    app.post('/', function (req, res) {69      res.json(req.body)70    })7172    request(app)73      .post('/')74      .set('Content-Type', 'application/json')75      .send('{"user":"tobi"}')76      .expect(200, '{"user":"tobi"}', done)77  })7879  describe('when JSON is invalid', function () {80    before(function () {81      this.app = createApp()82    })8384    it('should 400 for bad token', function (done) {85      request(this.app)86        .post('/')87        .set('Content-Type', 'application/json')88        .send('{:')89        .expect(400, parseError('{:'), done)90    })9192    it('should 400 for incomplete', function (done) {93      request(this.app)94        .post('/')95        .set('Content-Type', 'application/json')96        .send('{"user"')97        .expect(400, parseError('{"user"'), done)98    })99100    it('should error with type = "entity.parse.failed"', function (done) {101      request(this.app)102        .post('/')103        .set('Content-Type', 'application/json')104        .set('X-Error-Property', 'type')105        .send(' {"user"')106        .expect(400, 'entity.parse.failed', done)107    })108109    it('should include original body on error object', function (done) {110      request(this.app)111        .post('/')112        .set('Content-Type', 'application/json')113        .set('X-Error-Property', 'body')114        .send(' {"user"')115        .expect(400, ' {"user"', done)116    })117  })118119  describe('with limit option', function () {120    it('should 413 when over limit with Content-Length', function (done) {121      var buf = Buffer.alloc(1024, '.')122      request(createApp({ limit: '1kb' }))123        .post('/')124        .set('Content-Type', 'application/json')125        .set('Content-Length', '1034')126        .send(JSON.stringify({ str: buf.toString() }))127        .expect(413, done)128    })129130    it('should error with type = "entity.too.large"', function (done) {131      var buf = Buffer.alloc(1024, '.')132      request(createApp({ limit: '1kb' }))133        .post('/')134        .set('Content-Type', 'application/json')135        .set('Content-Length', '1034')136        .set('X-Error-Property', 'type')137        .send(JSON.stringify({ str: buf.toString() }))138        .expect(413, 'entity.too.large', done)139    })140141    it('should 413 when over limit with chunked encoding', function (done) {142      var buf = Buffer.alloc(1024, '.')143      var server = createApp({ limit: '1kb' })144      var test = request(server).post('/')145      test.set('Content-Type', 'application/json')146      test.set('Transfer-Encoding', 'chunked')147      test.write('{"str":')148      test.write('"' + buf.toString() + '"}')149      test.expect(413, done)150    })151152    it('should accept number of bytes', function (done) {153      var buf = Buffer.alloc(1024, '.')154      request(createApp({ limit: 1024 }))155        .post('/')156        .set('Content-Type', 'application/json')157        .send(JSON.stringify({ str: buf.toString() }))158        .expect(413, done)159    })160161    it('should not change when options altered', function (done) {162      var buf = Buffer.alloc(1024, '.')163      var options = { limit: '1kb' }164      var server = createApp(options)165166      options.limit = '100kb'167168      request(server)169        .post('/')170        .set('Content-Type', 'application/json')171        .send(JSON.stringify({ str: buf.toString() }))172        .expect(413, done)173    })174175    it('should not hang response', function (done) {176      var buf = Buffer.alloc(10240, '.')177      var server = createApp({ limit: '8kb' })178      var test = request(server).post('/')179      test.set('Content-Type', 'application/json')180      test.write(buf)181      test.write(buf)182      test.write(buf)183      test.expect(413, done)184    })185  })186187  describe('with inflate option', function () {188    describe('when false', function () {189      before(function () {190        this.app = createApp({ inflate: false })191      })192193      it('should not accept content-encoding', function (done) {194        var test = request(this.app).post('/')195        test.set('Content-Encoding', 'gzip')196        test.set('Content-Type', 'application/json')197        test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))198        test.expect(415, 'content encoding unsupported', done)199      })200    })201202    describe('when true', function () {203      before(function () {204        this.app = createApp({ inflate: true })205      })206207      it('should accept content-encoding', function (done) {208        var test = request(this.app).post('/')209        test.set('Content-Encoding', 'gzip')210        test.set('Content-Type', 'application/json')211        test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))212        test.expect(200, '{"name":"论"}', done)213      })214    })215  })216217  describe('with strict option', function () {218    describe('when undefined', function () {219      before(function () {220        this.app = createApp()221      })222223      it('should 400 on primitives', function (done) {224        request(this.app)225          .post('/')226          .set('Content-Type', 'application/json')227          .send('true')228          .expect(400, parseError('#rue').replace('#', 't'), done)229      })230    })231232    describe('when false', function () {233      before(function () {234        this.app = createApp({ strict: false })235      })236237      it('should parse primitives', function (done) {238        request(this.app)239          .post('/')240          .set('Content-Type', 'application/json')241          .send('true')242          .expect(200, 'true', done)243      })244    })245246    describe('when true', function () {247      before(function () {248        this.app = createApp({ strict: true })249      })250251      it('should not parse primitives', function (done) {252        request(this.app)253          .post('/')254          .set('Content-Type', 'application/json')255          .send('true')256          .expect(400, parseError('#rue').replace('#', 't'), done)257      })258259      it('should not parse primitives with leading whitespaces', function (done) {260        request(this.app)261          .post('/')262          .set('Content-Type', 'application/json')263          .send('    true')264          .expect(400, parseError('    #rue').replace('#', 't'), done)265      })266267      it('should allow leading whitespaces in JSON', function (done) {268        request(this.app)269          .post('/')270          .set('Content-Type', 'application/json')271          .send('   { "user": "tobi" }')272          .expect(200, '{"user":"tobi"}', done)273      })274275      it('should error with type = "entity.parse.failed"', function (done) {276        request(this.app)277          .post('/')278          .set('Content-Type', 'application/json')279          .set('X-Error-Property', 'type')280          .send('true')281          .expect(400, 'entity.parse.failed', done)282      })283284      it('should include correct message in stack trace', function (done) {285        request(this.app)286          .post('/')287          .set('Content-Type', 'application/json')288          .set('X-Error-Property', 'stack')289          .send('true')290          .expect(400)291          .expect(shouldContainInBody(parseError('#rue').replace('#', 't')))292          .end(done)293      })294    })295  })296297  describe('with type option', function () {298    describe('when "application/vnd.api+json"', function () {299      before(function () {300        this.app = createApp({ type: 'application/vnd.api+json' })301      })302303      it('should parse JSON for custom type', function (done) {304        request(this.app)305          .post('/')306          .set('Content-Type', 'application/vnd.api+json')307          .send('{"user":"tobi"}')308          .expect(200, '{"user":"tobi"}', done)309      })310311      it('should ignore standard type', function (done) {312        request(this.app)313          .post('/')314          .set('Content-Type', 'application/json')315          .send('{"user":"tobi"}')316          .expect(200, '{}', done)317      })318    })319320    describe('when ["application/json", "application/vnd.api+json"]', function () {321      before(function () {322        this.app = createApp({323          type: ['application/json', 'application/vnd.api+json']324        })325      })326327      it('should parse JSON for "application/json"', function (done) {328        request(this.app)329          .post('/')330          .set('Content-Type', 'application/json')331          .send('{"user":"tobi"}')332          .expect(200, '{"user":"tobi"}', done)333      })334335      it('should parse JSON for "application/vnd.api+json"', function (done) {336        request(this.app)337          .post('/')338          .set('Content-Type', 'application/vnd.api+json')339          .send('{"user":"tobi"}')340          .expect(200, '{"user":"tobi"}', done)341      })342343      it('should ignore "application/x-json"', function (done) {344        request(this.app)345          .post('/')346          .set('Content-Type', 'application/x-json')347          .send('{"user":"tobi"}')348          .expect(200, '{}', done)349      })350    })351352    describe('when a function', function () {353      it('should parse when truthy value returned', function (done) {354        var app = createApp({ type: accept })355356        function accept (req) {357          return req.headers['content-type'] === 'application/vnd.api+json'358        }359360        request(app)361          .post('/')362          .set('Content-Type', 'application/vnd.api+json')363          .send('{"user":"tobi"}')364          .expect(200, '{"user":"tobi"}', done)365      })366367      it('should work without content-type', function (done) {368        var app = createApp({ type: accept })369370        function accept (req) {371          return true372        }373374        var test = request(app).post('/')375        test.write('{"user":"tobi"}')376        test.expect(200, '{"user":"tobi"}', done)377      })378379      it('should not invoke without a body', function (done) {380        var app = createApp({ type: accept })381382        function accept (req) {383          throw new Error('oops!')384        }385386        request(app)387          .get('/')388          .expect(404, done)389      })390    })391  })392393  describe('with verify option', function () {394    it('should assert value if function', function () {395      assert.throws(createApp.bind(null, { verify: 'lol' }),396        /TypeError: option verify must be function/)397    })398399    it('should error from verify', function (done) {400      var app = createApp({ verify: function (req, res, buf) {401        if (buf[0] === 0x5b) throw new Error('no arrays')402      } })403404      request(app)405        .post('/')406        .set('Content-Type', 'application/json')407        .send('["tobi"]')408        .expect(403, 'no arrays', done)409    })410411    it('should error with type = "entity.verify.failed"', function (done) {412      var app = createApp({ verify: function (req, res, buf) {413        if (buf[0] === 0x5b) throw new Error('no arrays')414      } })415416      request(app)417        .post('/')418        .set('Content-Type', 'application/json')419        .set('X-Error-Property', 'type')420        .send('["tobi"]')421        .expect(403, 'entity.verify.failed', done)422    })423424    it('should allow custom codes', function (done) {425      var app = createApp({ verify: function (req, res, buf) {426        if (buf[0] !== 0x5b) return427        var err = new Error('no arrays')428        err.status = 400429        throw err430      } })431432      request(app)433        .post('/')434        .set('Content-Type', 'application/json')435        .send('["tobi"]')436        .expect(400, 'no arrays', done)437    })438439    it('should allow custom type', function (done) {440      var app = createApp({ verify: function (req, res, buf) {441        if (buf[0] !== 0x5b) return442        var err = new Error('no arrays')443        err.type = 'foo.bar'444        throw err445      } })446447      request(app)448        .post('/')449        .set('Content-Type', 'application/json')450        .set('X-Error-Property', 'type')451        .send('["tobi"]')452        .expect(403, 'foo.bar', done)453    })454455    it('should include original body on error object', function (done) {456      var app = createApp({ verify: function (req, res, buf) {457        if (buf[0] === 0x5b) throw new Error('no arrays')458      } })459460      request(app)461        .post('/')462        .set('Content-Type', 'application/json')463        .set('X-Error-Property', 'body')464        .send('["tobi"]')465        .expect(403, '["tobi"]', done)466    })467468    it('should allow pass-through', function (done) {469      var app = createApp({ verify: function (req, res, buf) {470        if (buf[0] === 0x5b) throw new Error('no arrays')471      } })472473      request(app)474        .post('/')475        .set('Content-Type', 'application/json')476        .send('{"user":"tobi"}')477        .expect(200, '{"user":"tobi"}', done)478    })479480    it('should work with different charsets', function (done) {481      var app = createApp({ verify: function (req, res, buf) {482        if (buf[0] === 0x5b) throw new Error('no arrays')483      } })484485      var test = request(app).post('/')486      test.set('Content-Type', 'application/json; charset=utf-16')487      test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex'))488      test.expect(200, '{"name":"论"}', done)489    })490491    it('should 415 on unknown charset prior to verify', function (done) {492      var app = createApp({ verify: function (req, res, buf) {493        throw new Error('unexpected verify call')494      } })495496      var test = request(app).post('/')497      test.set('Content-Type', 'application/json; charset=x-bogus')498      test.write(Buffer.from('00000000', 'hex'))499      test.expect(415, 'unsupported charset "X-BOGUS"', done)500    })501  })502503  describe('charset', function () {504    before(function () {505      this.app = createApp()506    })507508    it('should parse utf-8', function (done) {509      var test = request(this.app).post('/')510      test.set('Content-Type', 'application/json; charset=utf-8')511      test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))512      test.expect(200, '{"name":"论"}', done)513    })514515    it('should parse utf-16', function (done) {516      var test = request(this.app).post('/')517      test.set('Content-Type', 'application/json; charset=utf-16')518      test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex'))519      test.expect(200, '{"name":"论"}', done)520    })521522    it('should parse when content-length != char length', function (done) {523      var test = request(this.app).post('/')524      test.set('Content-Type', 'application/json; charset=utf-8')525      test.set('Content-Length', '13')526      test.write(Buffer.from('7b2274657374223a22c3a5227d', 'hex'))527      test.expect(200, '{"test":"å"}', done)528    })529530    it('should default to utf-8', function (done) {531      var test = request(this.app).post('/')532      test.set('Content-Type', 'application/json')533      test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))534      test.expect(200, '{"name":"论"}', done)535    })536537    it('should fail on unknown charset', function (done) {538      var test = request(this.app).post('/')539      test.set('Content-Type', 'application/json; charset=koi8-r')540      test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex'))541      test.expect(415, 'unsupported charset "KOI8-R"', done)542    })543544    it('should error with type = "charset.unsupported"', function (done) {545      var test = request(this.app).post('/')546      test.set('Content-Type', 'application/json; charset=koi8-r')547      test.set('X-Error-Property', 'type')548      test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex'))549      test.expect(415, 'charset.unsupported', done)550    })551  })552553  describe('encoding', function () {554    before(function () {555      this.app = createApp({ limit: '1kb' })556    })557558    it('should parse without encoding', function (done) {559      var test = request(this.app).post('/')560      test.set('Content-Type', 'application/json')561      test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))562      test.expect(200, '{"name":"论"}', done)563    })564565    it('should support identity encoding', function (done) {566      var test = request(this.app).post('/')567      test.set('Content-Encoding', 'identity')568      test.set('Content-Type', 'application/json')569      test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))570      test.expect(200, '{"name":"论"}', done)571    })572573    it('should support gzip encoding', function (done) {574      var test = request(this.app).post('/')575      test.set('Content-Encoding', 'gzip')576      test.set('Content-Type', 'application/json')577      test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))578      test.expect(200, '{"name":"论"}', done)579    })580581    it('should support deflate encoding', function (done) {582      var test = request(this.app).post('/')583      test.set('Content-Encoding', 'deflate')584      test.set('Content-Type', 'application/json')585      test.write(Buffer.from('789cab56ca4bcc4d55b2527ab16e97522d00274505ac', 'hex'))586      test.expect(200, '{"name":"论"}', done)587    })588589    it('should be case-insensitive', function (done) {590      var test = request(this.app).post('/')591      test.set('Content-Encoding', 'GZIP')592      test.set('Content-Type', 'application/json')593      test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))594      test.expect(200, '{"name":"论"}', done)595    })596597    it('should 415 on unknown encoding', function (done) {598      var test = request(this.app).post('/')599      test.set('Content-Encoding', 'nulls')600      test.set('Content-Type', 'application/json')601      test.write(Buffer.from('000000000000', 'hex'))602      test.expect(415, 'unsupported content encoding "nulls"', done)603    })604605    it('should error with type = "encoding.unsupported"', function (done) {606      var test = request(this.app).post('/')607      test.set('Content-Encoding', 'nulls')608      test.set('Content-Type', 'application/json')609      test.set('X-Error-Property', 'type')610      test.write(Buffer.from('000000000000', 'hex'))611      test.expect(415, 'encoding.unsupported', done)612    })613614    it('should 400 on malformed encoding', function (done) {615      var test = request(this.app).post('/')616      test.set('Content-Encoding', 'gzip')617      test.set('Content-Type', 'application/json')618      test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))619      test.expect(400, done)620    })621622    it('should 413 when inflated value exceeds limit', function (done) {623      // gzip'd data exceeds 1kb, but deflated below 1kb624      var test = request(this.app).post('/')625      test.set('Content-Encoding', 'gzip')626      test.set('Content-Type', 'application/json')627      test.write(Buffer.from('1f8b080000000000000bedc1010d000000c2a0f74f6d0f071400000000000000', 'hex'))628      test.write(Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex'))629      test.write(Buffer.from('0000000000000000004f0625b3b71650c30000', 'hex'))630      test.expect(413, done)631    })632  })633})634635function createApp (options) {636  var app = express()637638  app.use(express.json(options))639640  app.use(function (err, req, res, next) {641    res.status(err.status || 500)642    res.send(String(err[req.headers['x-error-property'] || 'message']))643  })644645  app.post('/', function (req, res) {646    res.json(req.body)647  })648649  return app650}651652function parseError (str) {653  try {654    JSON.parse(str); throw new SyntaxError('strict violation')655  } catch (e) {656    return e.message657  }658}659660function shouldContainInBody (str) {661  return function (res) {662    assert.ok(res.text.indexOf(str) !== -1,663      'expected \'' + res.text + '\' to contain \'' + str + '\'')664  }665}