summaryrefslogtreecommitdiffstats
path: root/fastify-busboy/test/multipart-stream-pause.test.js
blob: 856cf7195479dacec6650c981d1b8369345c8e72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict'

const { inspect } = require('util')
const { test } = require('tap')

const Busboy = require('..')

const BOUNDARY = 'u2KxIV5yF1y+xUspOQCCZopaVgeV6Jxihv35XQJmuTx8X3sh'

function formDataSection (key, value) {
  return Buffer.from('\r\n--' + BOUNDARY +
                     '\r\nContent-Disposition: form-data; name="' +
                     key + '"\r\n\r\n' + value)
}
function formDataFile (key, filename, contentType) {
  return Buffer.concat([
    Buffer.from('\r\n--' + BOUNDARY + '\r\n'),
    Buffer.from('Content-Disposition: form-data; name="' +
                key + '"; filename="' + filename + '"\r\n'),
    Buffer.from('Content-Type: ' + contentType + '\r\n\r\n'),
    Buffer.allocUnsafe(100000)
  ])
}

test('multipart-stream-pause - processes stream correctly', t => {
  t.plan(6)
  const reqChunks = [
    Buffer.concat([
      formDataFile('file', 'file.bin', 'application/octet-stream'),
      formDataSection('foo', 'foo value')
    ]),
    formDataSection('bar', 'bar value'),
    Buffer.from('\r\n--' + BOUNDARY + '--\r\n')
  ]
  const busboy = new Busboy({
    headers: {
      'content-type': 'multipart/form-data; boundary=' + BOUNDARY
    }
  })
  let finishes = 0
  const results = []
  const expected = [
    ['file', 'file', 'file.bin', '7bit', 'application/octet-stream'],
    ['field', 'foo', 'foo value', false, false, '7bit', 'text/plain'],
    ['field', 'bar', 'bar value', false, false, '7bit', 'text/plain']
  ]

  busboy.on('field', function (key, val, keyTrunc, valTrunc, encoding, contype) {
    results.push(['field', key, val, keyTrunc, valTrunc, encoding, contype])
  })
  busboy.on('file', function (fieldname, stream, filename, encoding, mimeType) {
    results.push(['file', fieldname, filename, encoding, mimeType])
    // Simulate a pipe where the destination is pausing (perhaps due to waiting
    // for file system write to finish)
    setTimeout(function () {
      stream.resume()
    }, 10)
  })
  busboy.on('finish', function () {
    t.ok(finishes++ === 0, 'finish emitted multiple times')
    t.strictSame(results.length,
      expected.length,
      'Parsed result count mismatch. Saw ' +
          results.length +
          '. Expected: ' + expected.length)

    results.forEach(function (result, i) {
      t.strictSame(result,
        expected[i],
        'Result mismatch:\nParsed: ' + inspect(result) +
            '\nExpected: ' + inspect(expected[i]))
    })
    t.pass()
  }).on('error', function (err) {
    t.error(err)
  })

  reqChunks.forEach(function (buf) {
    busboy.write(buf)
  })
  busboy.end()
})