Debian Codegraph @

formdata-polyfill/test/test-polyfill.html

raw
1 See console in devtool
2
3 <script>
4 globalThis.NativeFormData = FormData
5 globalThis.NativeFile = File
6 window.FormData = undefined
7 // Want to simulate the kind of error we get in
8 // old safari & ie when constructing a file
9 window.File = new Proxy(NativeFile, {
10 construct (target, args) {
11 throw new Error()
12 }
13 })
14 </script>
15 <script src="../formdata.min.js"></script>
16 <!-- <script src="../FormData.js"></script> -->
17 <script type="module">
18 import {formDataToBlob} from '../formdata-to-blob.js'
19
20 const Polyfill = globalThis.FormData
21
22 function catchErr(fn) {
23 try { fn() } catch (err) { return err }
24 }
25
26 for (const FormData of [NativeFormData, Polyfill]) {
27 function createFormData (...args) {
28 const fd = new FormData()
29 for (const arg of args) {
30 fd.append(...arg)
31 }
32 return fd
33 }
34
35 function createForm (str) {
36 var form = document.createElement('form')
37 form.innerHTML = str
38 return new FormData(form)
39 }
40
41 const impl = FormData === NativeFormData ? 'native' : 'polyfill'
42
43 {
44 const fd = new FormData()
45 const err = catchErr(() => fd.append('key'))
46 console.assert(err instanceof TypeError, 'should throw on few arguments')
47 }
48
49 // #120 escapes keys when encoding FormData
50 if (impl === 'polyfill') {
51 for (let [key, expected] of [['key\n', 'key%0D%0A'], ['key\r', 'key%0D%0A'], ['key"', 'key%22']]) {
52 const origFd = createFormData([key, 'value'])
53 const fd = await new Response(origFd._blob ? origFd._blob() : origFd).formData()
54 console.assert(fd.has(expected) === true)
55
56 const blob = formDataToBlob(origFd)
57 const fd2 = await new Response(blob).formData()
58 console.assert(fd2.has(expected) === true)
59 }
60 }
61
62 // #120 normalizes linebreaks
63 // {
64 // var fd = new FormData()
65 // fd.set('a', '\n')
66 // fd.set('b', '\r')
67 // fd.set('c', '\n\r')
68
69 // console.assert(fd.get('a') === '\n')
70 // console.assert(fd.get('b') === '\r')
71 // console.assert(fd.get('c') === '\n\r')
72
73 // new Response(formDataToBlob(fd)).formData().then(fd2 => {
74 // console.assert(fd2.get('a') === '\r\n')
75 // console.assert(fd2.get('b') === '\r\n')
76 // console.assert(fd2.get('c') === '\r\n\r\n')
77 // })
78 // }
79
80 // #78
81 {
82 const fd = createForm(`<input name=foo type=file>`)
83 console.assert(fd.has('foo') === true)
84 console.assert(fd.get('foo').type === 'application/octet-stream')
85 }
86
87 {
88 const fd = createFormData(['key', 'value1'])
89 console.assert(fd.get('key') === 'value1')
90 }
91
92 {
93 const fd = createFormData(['key', 'value2'], ['key', 'value1'])
94 console.assert(fd.get('key') === 'value2')
95 }
96
97 {
98 const fd = createFormData(['key', undefined])
99 console.assert(fd.get('key') === 'undefined')
100 }
101
102 {
103 const fd = createFormData(['key', undefined], ['key', 'value1'])
104 console.assert(fd.get('key') === 'undefined')
105 }
106
107 {
108 const fd = createFormData(['key', null])
109 console.assert(fd.get('key') === 'null')
110 }
111
112 {
113 const fd = createFormData(['key', null], ['key', 'value1'])
114 console.assert(fd.get('key') === 'null')
115 }
116
117 {
118 const fd = new FormData(document.createElement('form'))
119 fd.append('key', 'value1')
120 console.assert(fd.get('key') === 'value1')
121 }
122
123 {
124 const fd = new FormData(document.createElement('form'))
125 fd.append('key', 'value2')
126 fd.append('key', 'value1')
127 console.assert(fd.get('key') === 'value2')
128 }
129
130 {
131 const fd = new FormData(document.createElement('form'))
132 fd.append('key', undefined)
133 console.assert(fd.get('key') === 'undefined')
134 }
135
136 {
137 const fd = new FormData(document.createElement('form'))
138 fd.append('key', undefined)
139 fd.append('key', 'value1')
140 console.assert(fd.get('key') === 'undefined')
141 }
142
143 {
144 const fd = new FormData(document.createElement('form'))
145 fd.append('key', null)
146 console.assert(fd.get('key') === 'null')
147 }
148
149 {
150 const fd = new FormData(document.createElement('form'))
151 fd.append('key', null)
152 fd.append('key', 'value1')
153 console.assert(fd.get('key') === 'null')
154 }
155
156 {
157 const fd = createFormData(['key', new Blob(), 'blank.txt'])
158 const file = fd.get('key')
159 console.assert(file.name === 'blank.txt')
160 console.assert(file.type === '')
161 console.assert(file.size === 0)
162 if (impl === 'polyfill') {
163 // Chrome dose wrong...
164 console.assert(fd.get('key') === fd.get('key'), 'File should be same instances')
165 }
166 }
167
168 console.info('testing has() on ' + impl)
169
170 {
171 const fd = new FormData()
172 const err = catchErr(() => fd.has())
173 console.assert(err instanceof TypeError)
174 }
175
176 {
177 const fd = new FormData()
178 fd.append('n1', 'value')
179 console.assert(fd.has('n1') === true)
180 console.assert(fd.has('n2') === false)
181 fd.append('n2', 'value')
182 console.assert(fd.has('n1') === true)
183 console.assert(fd.has('n2') === true)
184 fd.append('n3', new Blob(['content']))
185 console.assert(fd.has('n3') === true)
186 }
187
188 console.info('testing entries() on ' + impl)
189
190 {
191 const fd = createFormData(
192 ['keyA', 'val1'],
193 ['keyA', 'val2'],
194 ['keyB', 'val3'],
195 ['keyA', 'val4']
196 )
197
198 const actualKeys = [...fd.keys()] + ''
199 const expectedKeys = ['keyA', 'keyA', 'keyB', 'keyA'] + ''
200 console.assert(actualKeys === expectedKeys, 'should return the keys as they are appended')
201
202 const actualValues = [...fd.values()] + ''
203 const expectedValues = ['val1', 'val2', 'val3', 'val4'] + ''
204 console.assert(actualValues === expectedValues, 'should return values as they are appended')
205
206 const actualEntries = [...fd] + ''
207 const expectedEntries = [
208 ['keyA', 'val1'],
209 ['keyA', 'val2'],
210 ['keyB', 'val3'],
211 ['keyA', 'val4']
212 ] + ''
213 console.assert(actualEntries === expectedEntries, 'should return the entres as they are appended')
214 }
215
216 console.info('testing set() on ' + impl)
217
218 {
219 const fd = new FormData()
220 const err = catchErr(() => fd.set())
221 console.assert(err instanceof TypeError, 'should throw on few arguments')
222 }
223
224 {
225 const fd = createFormData(
226 ['keyA', 'val1'],
227 ['keyA', 'val2'],
228 ['keyB', 'val3'],
229 ['keyA', 'val4']
230 )
231 fd.set('keyA', 'val3')
232 const actual = String([...fd])
233 const expected = String([['keyA', 'val3'], ['keyB', 'val3']])
234 const msg = 'Overwrite first matching key'
235 console.assert(actual === expected, msg)
236 }
237
238 {
239 const fd = createFormData(['keyB', 'val3'])
240 fd.set('keyA', 'val3')
241 const actual = String([...fd])
242 const expected = String([['keyB', 'val3'], ['keyA', 'val3']])
243 const msg = 'appends value when no matching'
244 console.assert(actual === expected, msg)
245 }
246
247 console.info('testing delete() on ' + impl)
248
249 {
250 const fd = new FormData()
251 const err = catchErr(() => fd.delete())
252 console.assert(err instanceof TypeError, 'should throw on few arguments')
253 }
254
255 {
256 var fd = new FormData()
257 fd.append('name', 'value')
258 console.assert(fd.has('name') === true, 'name should have been appended')
259 fd.delete('name')
260 console.assert(fd.has('name') === false, 'name should have been deleted')
261
262 fd.append('name', new Blob(['content']))
263 console.assert(fd.has('name') === true, 'it should have a name field')
264 fd.delete('name')
265 console.assert(fd.has('name') === false, 'name should have been deleted')
266
267 fd.append('n1', 'v1')
268 fd.append('n2', 'v2')
269 fd.append('n1', 'v3')
270 fd.delete('n1')
271 console.assert(fd.has('n1') === false, 'delete should remove all keys with n1')
272 console.assert(String([...fd]) === String([['n2', 'v2']]))
273 }
274
275 {
276 // #43
277 // Old ie don't have Symbol.toStringTag and the polyfill was
278 // therefore not able to change the
279 // `Object.prototype.toString.call` to return correct type of the polyfilled
280 // File constructor
281 const fd = createFormData(['key', new NativeFile([], 'doc.txt')])
282 const mockFile = fd.get('key')
283 console.assert(mockFile.name === 'doc.txt', 'Should return correct filename with File')
284 }
285
286 {
287 const fd = createFormData(['key', new Blob(), 'doc.txt'])
288 const mockFile = fd.get('key')
289 console.assert('doc.txt', mockFile.name, 'Should return correct filename with Blob filename')
290 }
291
292 {
293 const fd = createFormData(['key', new Blob()])
294 const mockFile = fd.get('key')
295 console.assert('blob' === mockFile.name, 'Default name should be Blob')
296 }
297
298 console.info('testing linebreaks() on ' + impl)
299 {
300 const form = document.createElement('form')
301 const textarea = document.createElement('textarea')
302 textarea.name = 'key'
303 form.append(textarea)
304
305 // Native FormData normalizes linefeeds in textareas to CRLF
306 // In order to be consistent the polyfill should do the same
307 {
308 textarea.value = '\n'
309 const fd = new FormData(form)
310 const value = fd.get('key')
311 console.assert('\r\n' === value, 'Should convert LF to CRLF for textareas')
312 }
313
314 {
315 textarea.value = '\r'
316 const fd = new FormData(form)
317 const value = fd.get('key')
318 console.assert('\r\n' === value, 'Should convert CR to CRLF for textareas')
319 }
320
321 {
322 textarea.value = 'a\n\ra\r\na\n\r\n\r\n\r\n\na\r\r'
323 const fd = new FormData(form)
324 const value = fd.get('key')
325 console.assert(
326 'a\r\n\r\na\r\na\r\n\r\n\r\n\r\n\r\na\r\n\r\n' === value,
327 'Should normalize mixed linefeeds to CRLF for textareas'
328 )
329 }
330
331 {
332 const fd = createFormData(['key', '\n'])
333 const value = fd.get('key')
334 console.assert('\n' === value, 'Should not convert LF to CRLF when provided by append')
335 }
336
337 {
338 const fd = createFormData(['key', '\r'])
339 const value = fd.get('key')
340 console.assert('\r' === value, 'Should not convert CR to CRLF when provided by append')
341 }
342 }
343
344 console.info('testing disabled() on ' + impl)
345
346 {
347 const fd = createForm(`<input disabled name=foo value=bar>`)
348 console.assert(fd.has('foo') === false, 'Should not include disabled inputs')
349 }
350
351 // #110
352 {
353 const fd = createForm(`<fieldset disabled><input name=foo value=bar></fieldset>`)
354 console.assert(fd.has('foo') === false, 'Should not include disabled fieldset inputs')
355 }
356
357 // #56
358 {
359 const fd = createForm(`
360 <select multiple name="example">
361 <option selected disabled value="foo">Please choose one</option>
362 </select>
363 `)
364
365 console.assert(
366 fd.has('example') === false,
367 'Select elements where the option is both selected and disabled should not be included'
368 )
369 }
370
371 // #45
372 {
373 const fd = createForm(`
374 <select multiple name="example">
375 <option selected value="volvo">Volvo</option>
376 <option selected value="saab">Saab</option>
377 <option value="mercedes">Mercedes</option>
378 <option value="audi">Audi</option>
379 </select>
380 `)
381
382 console.assert(
383 String([...fd]) === String([['example', 'volvo'], ['example', 'saab']]),
384 'Should return selected items'
385 )
386 }
387
388 // #62
389 {
390 const fd = createForm(`
391 <input type="text" name="username" value="bob">
392 <input type="submit" value="rename" name="action">
393 <input type="submit" value="find_n_delete" name="action">
394 `)
395
396 console.assert(
397 String([...fd]) === String([['username', 'bob']]),
398 'Should not add buttons to FormData'
399 )
400 }
401
402 // chrome dose wrong...
403 if (impl === 'polyfill') {
404 var fd = new FormData()
405 fd.set('a', 'a\na')
406 fd.set('b', 'b\rb')
407 fd.set('c', 'c\n\rc')
408
409 console.assert(fd.get('a') === 'a\na')
410 console.assert(fd.get('b') === 'b\rb')
411 console.assert(fd.get('c') === 'c\n\rc')
412
413 await new Response(fd._blob()).text().then(str => {
414 console.assert(str.includes('a\r\na'))
415 console.assert(str.includes('b\r\nb'))
416 console.assert(str.includes('c\r\n\r\nc'))
417 })
418 }
419
420 {
421 var fd = new FormData()
422 fd.set('a', 'a\na')
423 fd.set('b', 'b\rb')
424 fd.set('c', 'c\n\rc')
425
426 console.assert(fd.get('a') === 'a\na')
427 console.assert(fd.get('b') === 'b\rb')
428 console.assert(fd.get('c') === 'c\n\rc')
429
430 await new Response(formDataToBlob(fd)).text().then(str => {
431 console.assert(str.includes('a\r\na'))
432 console.assert(str.includes('b\r\nb'))
433 console.assert(str.includes('c\r\n\r\nc'))
434 })
435 }
436
437 // #86
438 {
439 const formData = createFormData(['key', 'value1'])
440 const xhr = new XMLHttpRequest()
441 xhr.open('POST', 'https://httpbin.org/post')
442 xhr.setRequestHeader('Content-Type', 'text/plain')
443 xhr.responseType = 'json'
444 xhr.onload = () => {
445 console.assert(
446 xhr.response.headers['Content-Type'] === 'text/plain',
447 'Shouldn not add Content-Type header if already present'
448 )
449 }
450 xhr.send(formData)
451 }
452
453 const kTestChars = "ABC~‾¥≈¤・・•∙·☼★星🌟星★☼·∙•・・¤≈¥‾~XYZ"
454
455 // formDataPostFileUploadTest - verifies multipart upload structure and
456 // numeric character reference replacement for filenames, field names,
457 // and field values using FormData and fetch().
458 //
459 // Uses /fetch/api/resources/echo-content.py to echo the upload
460 // POST (unlike in send-file-form-helper.js, here we expect all
461 // multipart/form-data request bodies to be UTF-8, so we don't need to
462 // escape controls and non-ASCII bytes).
463 //
464 // Fields in the parameter object:
465 //
466 // - fileNameSource: purely explanatory and gives a clue about which
467 // character encoding is the source for the non-7-bit-ASCII parts of
468 // the fileBaseName, or Unicode if no smaller-than-Unicode source
469 // contains all the characters. Used in the test name.
470 // - fileBaseName: the not-necessarily-just-7-bit-ASCII file basename
471 // used for the constructed test file. Used in the test name.
472 async function formDataPostFileUploadTest(fileBaseName, asBlob = false) {
473 if (impl !== 'polyfill') return
474 const formData = new FormData();
475 const file = new File([kTestChars], fileBaseName, { type: "text/plain" });
476
477 // Used to verify that the browser agrees with the test about
478 // field value replacement and encoding independently of file system
479 // idiosyncracies.
480 formData.append("filename", fileBaseName);
481
482 // Same, but with name and value reversed to ensure field names
483 // get the same treatment.
484 formData.append(fileBaseName, "filename");
485
486 formData.append("file", file, fileBaseName);
487
488 const formDataText = await (asBlob ? formDataToBlob(formData).text() : new Response(formData._blob()).text());
489 const formDataLines = formDataText.split("\r\n");
490 if (formDataLines.length && !formDataLines[formDataLines.length - 1]) {
491 formDataLines.length--
492 }
493 console.assert(formDataLines.length > 2, `${fileBaseName}: multipart form data must have at least 3 lines: ${
494 JSON.stringify(formDataText)
495 }`)
496
497 const boundary = formDataLines[0];
498 console.assert(
499 formDataLines[formDataLines.length - 1] === boundary + "--",
500 `${fileBaseName}: multipart form data must end with ${boundary}--: ${
501 JSON.stringify(formDataText)
502 }`,
503 );
504
505 const asValue = fileBaseName.replace(/\r\n?|\n/g, "\r\n");
506 const asName = asValue.replace(/[\r\n"]/g, encodeURIComponent);
507 const asFilename = fileBaseName.replace(/[\r\n"]/g, encodeURIComponent);
508 const expectedText = [
509 boundary,
510 'Content-Disposition: form-data; name="filename"',
511 "",
512 asValue,
513 boundary,
514 `Content-Disposition: form-data; name="${asName}"`,
515 "",
516 "filename",
517 boundary,
518 `Content-Disposition: form-data; name="file"; ` +
519 `filename="${asFilename}"`,
520 "Content-Type: text/plain",
521 "",
522 kTestChars,
523 boundary + "--",
524 ].join("\r\n")
525
526 console.assert(
527 formDataText.startsWith(expectedText),
528 `Unexpected multipart-shaped form data received:\n${formDataText}\nExpected:\n${expectedText}`,
529 )
530
531 if (!asBlob) return formDataPostFileUploadTest(fileBaseName, true)
532 }
533
534 console.log('Testing many names')
535 await formDataPostFileUploadTest("file-for-upload-in-form.txt")
536 await formDataPostFileUploadTest("file-for-upload-in-form-\uF7F0\uF793\uF783\uF7A0.txt")
537 await formDataPostFileUploadTest("file-for-upload-in-form-☺😂.txt")
538 await formDataPostFileUploadTest("file-for-upload-in-form-★星★.txt")
539 await formDataPostFileUploadTest("file-for-upload-in-form-☺😂.txt")
540 await formDataPostFileUploadTest(`file-for-upload-in-form-${kTestChars}.txt`)
541
542 await formDataPostFileUploadTest("file-for-upload-in-form.txt")
543 await formDataPostFileUploadTest("file-for-upload-in-form-NUL-[\0].txt")
544 await formDataPostFileUploadTest("file-for-upload-in-form-BS-[\b].txt")
545 await formDataPostFileUploadTest("file-for-upload-in-form-VT-[\v].txt")
546
547 // These have characters that undergo processing in name=,
548 // filename=, and/or value; formDataPostFileUploadTest postprocesses
549 // expectedEncodedBaseName for these internally.
550 await formDataPostFileUploadTest("file-for-upload-in-form-LF-[\n].txt")
551 await formDataPostFileUploadTest("file-for-upload-in-form-LF-CR-[\n\r].txt")
552 await formDataPostFileUploadTest("file-for-upload-in-form-CR-[\r].txt")
553 await formDataPostFileUploadTest("file-for-upload-in-form-CR-LF-[\r\n].txt")
554 await formDataPostFileUploadTest("file-for-upload-in-form-HT-[\t].txt")
555 await formDataPostFileUploadTest("file-for-upload-in-form-FF-[\f].txt")
556 await formDataPostFileUploadTest("file-for-upload-in-form-DEL-[\x7F].txt")
557
558 // The rest should be passed through unmodified:
559 await formDataPostFileUploadTest("file-for-upload-in-form-ESC-[\x1B].txt")
560 await formDataPostFileUploadTest("file-for-upload-in-form-SPACE-[ ].txt")
561
562
563 // These have characters that undergo processing in name=,
564 // filename=, and/or value; formDataPostFileUploadTest postprocesses
565 // expectedEncodedBaseName for these internally.
566 await formDataPostFileUploadTest("file-for-upload-in-form-QUOTATION-MARK-[\x22].txt")
567 await formDataPostFileUploadTest('"file-for-upload-in-form-double-quoted.txt"')
568 await formDataPostFileUploadTest("file-for-upload-in-form-REVERSE-SOLIDUS-[\\].txt")
569
570 // The rest should be passed through unmodified:
571 await formDataPostFileUploadTest("file-for-upload-in-form-EXCLAMATION-MARK-[!].txt")
572 await formDataPostFileUploadTest("file-for-upload-in-form-DOLLAR-SIGN-[$].txt")
573 await formDataPostFileUploadTest("file-for-upload-in-form-PERCENT-SIGN-[%].txt")
574 await formDataPostFileUploadTest("file-for-upload-in-form-AMPERSAND-[&].txt")
575 await formDataPostFileUploadTest("file-for-upload-in-form-APOSTROPHE-['].txt")
576 await formDataPostFileUploadTest("file-for-upload-in-form-LEFT-PARENTHESIS-[(].txt")
577 await formDataPostFileUploadTest("file-for-upload-in-form-RIGHT-PARENTHESIS-[)].txt")
578 await formDataPostFileUploadTest("file-for-upload-in-form-ASTERISK-[*].txt")
579 await formDataPostFileUploadTest("file-for-upload-in-form-PLUS-SIGN-[+].txt")
580 await formDataPostFileUploadTest("file-for-upload-in-form-COMMA-[,].txt")
581 await formDataPostFileUploadTest("file-for-upload-in-form-FULL-STOP-[.].txt")
582 await formDataPostFileUploadTest("file-for-upload-in-form-SOLIDUS-[/].txt")
583 await formDataPostFileUploadTest("file-for-upload-in-form-COLON-[:].txt")
584 await formDataPostFileUploadTest("file-for-upload-in-form-SEMICOLON-[;].txt")
585 await formDataPostFileUploadTest("file-for-upload-in-form-EQUALS-SIGN-[=].txt")
586 await formDataPostFileUploadTest("file-for-upload-in-form-QUESTION-MARK-[?].txt")
587 await formDataPostFileUploadTest("file-for-upload-in-form-CIRCUMFLEX-ACCENT-[^].txt")
588 await formDataPostFileUploadTest("file-for-upload-in-form-LEFT-SQUARE-BRACKET-[[].txt")
589 await formDataPostFileUploadTest("file-for-upload-in-form-RIGHT-SQUARE-BRACKET-[]].txt")
590 await formDataPostFileUploadTest("file-for-upload-in-form-LEFT-CURLY-BRACKET-[{].txt")
591 await formDataPostFileUploadTest("file-for-upload-in-form-VERTICAL-LINE-[|].txt")
592 await formDataPostFileUploadTest("file-for-upload-in-form-RIGHT-CURLY-BRACKET-[}].txt")
593 await formDataPostFileUploadTest("file-for-upload-in-form-TILDE-[~].txt")
594 await formDataPostFileUploadTest("'file-for-upload-in-form-single-quoted.txt'")
595 }
596 </script>