request-body-serialization.ts
This file
Path
test/request-body-serialization.ts
167 lines · 7.4 KiB · TypeScript
Last changed by
More testsSindre Sorhusbefore adoptioncd1dba0
History of this fileTake it
More testsSindre Sorhusbefore adoptioncd1dba0
lines 1–167why, one step back1import {buffer} from 'node:stream/consumers';2import test, {type ExecutionContext} from 'ava';3import ky from '../source/index.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';56type ReceivedBody = {7 bytes: number[];8 contentType?: string;9 contentLength: string;10};1112async function createBodyServer(t: ExecutionContext) {13 const server = await createHttpTestServer(t, {bodyParser: false});14 server.post('/', async (request, response) => {15 response.json({16 bytes: [...await buffer(request)],17 contentType: request.headers['content-type'],18 contentLength: request.headers['content-length'],19 });20 });21 return server;22}2324function assertBytes(t: ExecutionContext, received: ReceivedBody, expected: Uint8Array) {25 t.deepEqual(received.bytes, [...expected]);26 t.is(received.contentLength, String(expected.byteLength));27}2829// Fetch §5.2 extracts strings as UTF-8 bytes and infers their media type.30// https://fetch.spec.whatwg.org/#concept-bodyinit-extract31for (const [description, body] of [32 ['Unicode', 'é日本語🌍'],33 ['line endings', 'first\nsecond\rthird\r\nfourth'],34 ['empty string', ''],35]) {36 test(`string request body preserves ${description} and uses its byte length`, async t => {37 const server = await createBodyServer(t);38 const received = await ky.post(server.url, {body, retry: 0}).json<ReceivedBody>();39 assertBytes(t, received, Buffer.from(body!));40 t.is(received.contentType, 'text/plain;charset=UTF-8');41 });42}4344test('JSON serialization uses UTF-8 byte length including escaped characters', async t => {45 const server = await createBodyServer(t);46 const received = await ky.post(server.url, {json: {message: 'é🌍\n"'}, retry: 0}).json<ReceivedBody>();47 assertBytes(t, received, Buffer.from(String.raw`{"message":"é🌍\n\""}`));48 t.is(received.contentType, 'application/json');49});5051test('custom JSON serialization determines the actual bytes and content length', async t => {52 const server = await createBodyServer(t);53 let calls = 0;54 const received = await ky.post(server.url, {55 json: {value: 1},56 stringifyJson(value) {57 calls++;58 t.deepEqual(value, {value: 1});59 return '{ "custom": "日本語" }';60 },61 retry: 0,62 }).json<ReceivedBody>();63 assertBytes(t, received, Buffer.from('{ "custom": "日本語" }'));64 t.is(received.contentType, 'application/json');65 t.is(calls, 1);66});6768// Fetch copies BufferSource bytes, respecting a view's byte offset and byte length.69for (const kind of ['ArrayBuffer', 'Uint8Array subarray', 'DataView'] as const) {70 test(`binary request body preserves ${kind} bytes without inventing a media type`, async t => {71 const server = await createBodyServer(t);72 const bytes = new Uint8Array([99, 0, 128, 255, 100]);73 const body = kind === 'ArrayBuffer' ? bytes.buffer : (kind === 'DataView' ? new DataView(bytes.buffer, 1, 3) : bytes.subarray(1, 4));74 const received = await ky.post(server.url, {body, retry: 0}).json<ReceivedBody>();75 assertBytes(t, received, kind === 'ArrayBuffer' ? bytes : new Uint8Array([0, 128, 255]));76 t.is(received.contentType, undefined);77 });78}7980test('binary request body is copied before the caller mutates its buffer', async t => {81 const server = await createBodyServer(t);82 const body = new Uint8Array([0, 128, 255]);83 const response = ky.post(server.url, {body, retry: 0});84 body.fill(42);85 assertBytes(t, await response.json<ReceivedBody>(), new Uint8Array([0, 128, 255]));86});8788// URL §5.2 serializes ordered pairs, with spaces as + and literal + as %2B.89// https://url.spec.whatwg.org/#concept-urlencoded-serializer90for (const [description, entries, expected] of [91 ['spaces, plus signs, Unicode, and reserved characters', [['a b', 'a+b é🌍&=~']], 'a+b=a%2Bb+%C3%A9%F0%9F%8C%8D%26%3D%7E'],92 ['repeated names and empty values', [['tag', 'first'], ['tag', ''], ['tag', 'last'], ['', 'empty name']], 'tag=first&tag=&tag=last&=empty+name'],93 ['an empty entry list', [], ''],94] as const) {95 test(`URLSearchParams body preserves ${description}`, async t => {96 const server = await createBodyServer(t);97 const body = new URLSearchParams(entries.map(([name, value]) => [name, value]));98 const received = await ky.post(server.url, {body, retry: 0}).json<ReceivedBody>();99 assertBytes(t, received, Buffer.from(expected));100 t.is(received.contentType, 'application/x-www-form-urlencoded;charset=UTF-8');101 });102}103104for (const type of ['application/x-binary', '']) {105 test(`Blob body preserves binary bytes with ${type || 'no'} media type`, async t => {106 const server = await createBodyServer(t);107 const bytes = new Uint8Array([0, 13, 10, 128, 255]);108 const received = await ky.post(server.url, {body: new Blob([bytes], {type}), retry: 0}).json<ReceivedBody>();109 assertBytes(t, received, bytes);110 t.is(received.contentType, type || undefined);111 });112}113114test('sliced Blob body uses the slice bytes, size, and media type', async t => {115 const server = await createBodyServer(t);116 const body = new Blob([new Uint8Array([99, 0, 128, 255, 100])], {type: 'application/original'}).slice(1, 4, 'application/slice');117 const received = await ky.post(server.url, {body, retry: 0}).json<ReceivedBody>();118 assertBytes(t, received, new Uint8Array([0, 128, 255]));119 t.is(received.contentType, 'application/slice');120});121122test('explicit URLSearchParams content type does not change form encoding', async t => {123 const server = await createBodyServer(t);124 const received = await ky.post(server.url, {125 body: new URLSearchParams({message: 'a+b é'}),126 headers: {'content-type': 'application/custom'},127 retry: 0,128 }).json<ReceivedBody>();129 assertBytes(t, received, Buffer.from('message=a%2Bb+%C3%A9'));130 t.is(received.contentType, 'application/custom');131});132133// Fetch §5.2 uses multipart/form-data encoding for the FormData entry list.134// HTML §4.10.22.8 preserves duplicate fields and normalizes non-file line endings to CRLF.135// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm136// Parse the bytes actually received by the HTTP server using the transmitted boundary.137for (const description of ['duplicate fields', 'named binary file', 'field line endings'] as const) {138 test(`FormData serialization preserves ${description}`, async t => {139 const server = await createBodyServer(t);140 const body = new FormData();141 if (description === 'duplicate fields') {142 body.append('tag', 'é');143 body.append('tag', '');144 body.append('tag', '🌍');145 } else if (description === 'named binary file') {146 body.append('attachment', new Blob([new Uint8Array([0, 13, 10, 128, 255])], {type: 'application/octet-stream'}), 'sample.bin');147 } else {148 body.append('message', 'first\nsecond\rthird\r\nfourth');149 }150151 const received = await ky.post(server.url, {body, retry: 0}).json<ReceivedBody>();152 t.true(received.contentType!.startsWith('multipart/form-data; boundary='));153 t.is(received.contentLength, String(received.bytes.length));154 const parsed = await new Response(new Uint8Array(received.bytes), {headers: {'content-type': received.contentType!}}).formData();155 if (description === 'duplicate fields') {156 t.deepEqual([...parsed], [['tag', 'é'], ['tag', ''], ['tag', '🌍']]);157 } else if (description === 'named binary file') {158 t.deepEqual([...parsed.keys()], ['attachment']);159 const file = parsed.get('attachment') as File;160 t.is(file.name, 'sample.bin');161 t.is(file.type, 'application/octet-stream');162 t.deepEqual([...new Uint8Array(await file.arrayBuffer())], [0, 13, 10, 128, 255]);163 } else {164 t.deepEqual([...parsed], [['message', 'first\r\nsecond\r\nthird\r\nfourth']]);165 }166 });167}