1
1
'use strict'
2
2
3
+ const fs = require ( 'fs' )
3
4
const crypto = require ( 'crypto' )
4
5
const test = require ( 'tap' ) . test
5
6
const FormData = require ( 'form-data' )
@@ -49,7 +50,7 @@ test('should throw fileSize limitation error when consuming the stream', async f
49
50
method : 'POST'
50
51
}
51
52
52
- const randomFileBuffer = Buffer . alloc ( 600000 )
53
+ const randomFileBuffer = Buffer . alloc ( 600_000 )
53
54
crypto . randomFillSync ( randomFileBuffer )
54
55
55
56
const req = http . request ( opts )
@@ -67,6 +68,69 @@ test('should throw fileSize limitation error when consuming the stream', async f
67
68
}
68
69
} )
69
70
71
+ test ( 'should throw fileSize limitation error when consuming the stream MBs' , async function ( t ) {
72
+ t . plan ( 4 )
73
+
74
+ const fastify = Fastify ( )
75
+ t . teardown ( fastify . close . bind ( fastify ) )
76
+
77
+ fastify . register ( multipart , {
78
+ throwFileSizeLimit : true ,
79
+ limits : {
80
+ fileSize : 5_000_000 // 5MB
81
+ }
82
+ } )
83
+
84
+ fastify . post ( '/' , async function ( req , reply ) {
85
+ t . ok ( req . isMultipart ( ) )
86
+
87
+ const part = await req . file ( )
88
+ t . pass ( 'the file is not consumed yet' )
89
+
90
+ try {
91
+ await part . toBuffer ( )
92
+ t . fail ( 'it should throw' )
93
+ } catch ( error ) {
94
+ t . ok ( error )
95
+ reply . send ( error )
96
+ }
97
+ } )
98
+
99
+ await fastify . listen ( { port : 0 } )
100
+
101
+ // request
102
+ const form = new FormData ( )
103
+ const opts = {
104
+ hostname : '127.0.0.1' ,
105
+ port : fastify . server . address ( ) . port ,
106
+ path : '/' ,
107
+ headers : form . getHeaders ( ) ,
108
+ method : 'POST'
109
+ }
110
+
111
+ const randomFileBuffer = Buffer . alloc ( 15_000_000 )
112
+ crypto . randomFillSync ( randomFileBuffer )
113
+
114
+ const tmpFile = 'test/random-file'
115
+ fs . writeFileSync ( tmpFile , randomFileBuffer )
116
+
117
+ const req = http . request ( opts )
118
+ form . append ( 'upload' , fs . createReadStream ( tmpFile ) )
119
+
120
+ form . pipe ( req )
121
+
122
+ try {
123
+ const [ res ] = await once ( req , 'response' )
124
+ t . equal ( res . statusCode , 413 )
125
+ res . resume ( )
126
+ await once ( res , 'end' )
127
+
128
+ fs . unlinkSync ( tmpFile )
129
+ } catch ( error ) {
130
+ t . error ( error , 'request' )
131
+ }
132
+ } )
133
+
70
134
test ( 'should NOT throw fileSize limitation error when consuming the stream' , async function ( t ) {
71
135
t . plan ( 5 )
72
136
0 commit comments