Skip to content

Commit 632e489

Browse files
committed
Test multipart body more thoroughly
1 parent accc3c8 commit 632e489

File tree

2 files changed

+13
-18
lines changed

2 files changed

+13
-18
lines changed

src/wisp/simulate.gleam

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ pub fn multipart_body(
186186
values values: List(#(String, String)),
187187
files files: List(#(String, FileUpload)),
188188
) -> Request {
189-
let boundary = generate_boundary()
189+
let boundary = crypto.strong_random_bytes(16) |> bit_array.base16_encode
190190
let body_data = build_multipart_body(values, files, boundary)
191191
let body = wisp.create_canned_connection(body_data, default_secret_key_base)
192192

@@ -198,12 +198,6 @@ pub fn multipart_body(
198198
)
199199
}
200200

201-
fn generate_boundary() -> String {
202-
let random_bytes = crypto.strong_random_bytes(8)
203-
let boundary_suffix = bit_array.base16_encode(random_bytes)
204-
"boundary" <> boundary_suffix
205-
}
206-
207201
fn build_multipart_body(
208202
form_values: List(#(String, String)),
209203
files: List(#(String, FileUpload)),

test/wisp/simulate_test.gleam

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import gleam/bit_array
21
import gleam/http
32
import gleam/http/response
43
import gleam/json
@@ -248,15 +247,17 @@ pub fn multipart_generation_validation_test() {
248247
simulate.browser_request(http.Post, "/upload")
249248
|> simulate.multipart_body([#("name", "test")], [#("uploaded-file", file)])
250249

251-
let content_type = list.key_find(request.headers, "content-type")
252-
assert case content_type {
253-
Ok(ct) -> string.starts_with(ct, "multipart/form-data; boundary=")
254-
Error(_) -> False
255-
}
250+
let assert Ok("multipart/form-data; boundary=" <> boundary) =
251+
list.key_find(request.headers, "content-type")
256252

257-
let body_result = wisp.read_body_bits(request)
258-
assert case body_result {
259-
Ok(bits) -> bit_array.byte_size(bits) > 50
260-
Error(_) -> False
261-
}
253+
let assert Ok(body) = wisp.read_body_bits(request)
254+
let expected_body =
255+
"--"
256+
<> boundary
257+
<> "\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\ntest\r\n--"
258+
<> boundary
259+
<> "\r\nContent-Disposition: form-data; name=\"uploaded-file\"; filename=\"test.txt\"\r\nContent-Type: text/plain\r\n\r\nHello, world!\r\n--"
260+
<> boundary
261+
<> "--\r\n"
262+
assert body == <<expected_body:utf8>>
262263
}

0 commit comments

Comments
 (0)