Skip to content
Myr

http-response-bodies.ts

This file

Path

test/http-response-bodies.ts

147 lines · 5.2 KiB · TypeScript

Last changed by

More testsSindre Sorhusbefore adoptioncd1dba0

History of this file

Take it

More testsSindre Sorhusbefore adoptioncd1dba0

lines 1–147why, one step back
1import {gzipSync, deflateSync, brotliCompressSync} from 'node:zlib';
2import test from 'ava';3import ky, {HTTPError} from '../source/index.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';56const document = {message: 'café 日本語 🌍', detail: 'Repeated content '.repeat(100)};78// Keep chunk boundaries deterministic: HTTP transports may coalesce separate writes.9const byteStream = (bytes: Uint8Array) => {10 let offset = 0;11 return new ReadableStream<Uint8Array>({12 pull(controller) {13 if (offset === bytes.length) {14 controller.close();15 return;16 }1718 controller.enqueue(bytes.slice(offset, ++offset));19 },20 });21};2223for (const [encoding, compress] of [24 ['gzip', gzipSync],25 ['deflate', deflateSync],26 ['br', brotliCompressSync],27] as const) {28 test(`${encoding} JSON responses expose decoded bytes to download progress`, async t => {29 const server = await createHttpTestServer(t);30 const text = JSON.stringify(document);31 const compressed = compress(Buffer.from(text));32 server.get('/', (_request, response) => {33 response.set({'content-type': 'application/json', 'content-encoding': encoding, 'content-length': String(compressed.length)});34 response.end(compressed);35 });36 const chunks: Uint8Array[] = [];37 const parsed = await ky(server.url, {38 onDownloadProgress(_progress, chunk) {39 chunks.push(chunk);40 },41 }).json();4243 t.deepEqual(parsed, document);44 t.true(chunks.length > 0);45 t.is(Buffer.concat(chunks).toString(), text);46 });4748 test(`${encoding} error responses populate decoded JSON data`, async t => {49 const server = await createHttpTestServer(t);50 const compressed = compress(Buffer.from(JSON.stringify(document)));51 server.get('/', (_request, response) => {52 response.status(422).set({'content-type': 'application/problem+json', 'content-encoding': encoding});53 response.end(compressed);54 });55 const error = await t.throwsAsync(ky(server.url, {retry: 0}), {instanceOf: HTTPError});5657 t.deepEqual(error.data, document);58 t.is(error.response.status, 422);59 t.true(error.response.bodyUsed);60 });61}6263for (const status of [200, 422]) {64 test(`JSON with a split UTF-8 BOM and multibyte characters is decoded at status ${status}`, async t => {65 const body = {message: 'é 日本語 🌍'};66 const options = {67 retry: 0,68 fetch: async () => new Response(byteStream(Buffer.from(`\uFEFF${JSON.stringify(body)}`)), {69 status,70 headers: {'content-type': 'application/json'},71 }),72 };73 if (status === 200) {74 t.deepEqual(await ky('https://example.com', options).json(), body);75 } else {76 const error = await t.throwsAsync(ky('https://example.com', options), {instanceOf: HTTPError});77 t.deepEqual(error.data, body);78 }79 });80}8182for (const {title, contentType, bytes, expected} of [83 {84 title: 'UTF-16LE code units and surrogate pairs split between bytes', contentType: 'text/plain; charset=utf-16le', bytes: Buffer.from('é 🌍', 'utf16le'), expected: 'é 🌍',85 },86 {87 title: 'quoted case-insensitive charset labels', contentType: 'text/plain; ChArSeT="WiNdOwS-1252"', bytes: Uint8Array.from([0x80, 0x20, 0xE9]), expected: '€ é',88 },89 {90 title: 'unknown charset fallback', contentType: 'text/plain; charset=unknown-encoding', bytes: Buffer.from('日本語 🌍'), expected: '日本語 🌍',91 },92 {93 title: 'incomplete trailing UTF-8 sequences', contentType: 'text/plain; charset=utf-8', bytes: Uint8Array.from([0x61, 0xE2, 0x82]), expected: 'a\uFFFD',94 },95]) {96 test(`error text decodes ${title}`, async t => {97 const error = await t.throwsAsync(ky('https://example.com', {98 retry: 0,99 fetch: async () => new Response(byteStream(bytes), {status: 400, headers: {'content-type': contentType}}),100 }), {instanceOf: HTTPError});101102 t.is(error.data, expected);103 });104}105106for (const status of [200, 422]) {107 test(`custom JSON parser receives decoded text and response metadata once at status ${status}`, async t => {108 const server = await createHttpTestServer(t);109 const text = JSON.stringify({message: '日本語 🌍'});110 server.get('/', (_request, response) => {111 response.status(status).set({'content-type': 'application/json', 'content-encoding': 'gzip', 'x-parser-test': 'decoded'});112 response.end(gzipSync(Buffer.from(text)));113 });114 let calls = 0;115 const request = ky(server.url, {116 retry: 0,117 parseJson(decodedText, {request, response}) {118 calls++;119 t.is(decodedText, text);120 t.is(request.url, `${server.url}/`);121 t.is(response.url, `${server.url}/`);122 t.is(response.status, status);123 t.is(response.headers.get('x-parser-test'), 'decoded');124 return {parsed: JSON.parse(decodedText)};125 },126 });127 const expected = {parsed: {message: '日本語 🌍'}};128 if (status === 200) {129 t.deepEqual(await request.json(), expected);130 } else {131 const error = await t.throwsAsync(request, {instanceOf: HTTPError});132 t.deepEqual(error.data, expected);133 }134135 t.is(calls, 1);136 });137}138139test('error text at the exact 10 MiB limit is retained', async t => {140 const text = 'a'.repeat(10 * 1024 * 1024);141 const error = await t.throwsAsync(ky('https://example.com', {142 retry: 0,143 fetch: async () => new Response(text, {status: 400, headers: {'content-type': 'text/plain'}}),144 }), {instanceOf: HTTPError});145146 t.is(error.data, text);147});