-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.test.ts
More file actions
212 lines (186 loc) · 6.81 KB
/
Copy pathhttp.test.ts
File metadata and controls
212 lines (186 loc) · 6.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { wrapError } from './coerce.ts';
import { equals, exists, matches, strict, test, throws, throwsAsync } from './assert.test.ts';
import {
cancelBody,
fetchOk,
fetchPass,
fetchThrow500,
HttpError,
jsonResponse,
method,
readBody,
readResponseError,
statusCodeFromError,
validDataPostRequest,
} from './http.ts';
// Local stand-in for httpbin.org’s /status/:code service, whose gateway
// intermittently returns 502 and makes these tests flaky. `fetch` still
// exercises a real HTTP exchange over a real socket, just deterministically.
// Every response carries a text/plain body; 3xx responses redirect to
// /status/200. `node:http` works under both the Deno and Node test runs.
const server = createServer((request, response) => {
const status = Number(/^\/status\/(\d+)$/.exec(request.url ?? '')?.[1] ?? '404');
response.writeHead(status, {
'content-type': 'text/plain',
...(status >= 300 && status < 400 ? { location: '/status/200' } : {}),
});
response.end(String(status));
});
await new Promise<void>((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
server.unref();
const BASE_TEST_HTTP_URL = `http://127.0.0.1:${(server.address() as AddressInfo).port}/status`;
const testGetRequest = new Request('file:///foo');
const testPutRequest = new Request('file:///foo', {
method: 'PUT',
});
const testJsonRequest = new Request('file:///foo', {
method: 'POST',
headers: new Headers({
'content-type': 'application/json',
}),
body: '{"foo":"bar"}',
});
const testJsonResponse = new Response('{"foo":"bar"}', {
headers: new Headers({
'content-type': 'application/json',
}),
});
const testJsonResponseInvalid = new Response('invalid json', {
headers: new Headers({
'content-type': 'application/json',
}),
});
const testFormRequest = new Request('file:///foo', {
method: 'POST',
headers: new Headers({
'content-type': 'form-data',
}),
body: new URLSearchParams({ foo: 'bar' }),
});
const testUrlSearchParamsResponse = new Response(
new URLSearchParams({ foo: 'bar' }),
);
const testFormDataResponse = new Response((() => {
const formData = new FormData();
formData.append('foo', 'bar');
return formData;
})());
const testTextRequest = new Request('file:///foo', {
method: 'POST',
headers: new Headers({
'content-type': 'text/plain',
}),
body: 'foo: bar',
});
const testTextResponse = new Response(
'foo: bar',
{
headers: new Headers({
'content-type': 'text/plain',
}),
},
);
const testBlobRequest = new Request('file:///foo', {
method: 'POST',
headers: new Headers({
'content-type': 'application/octet-stream',
}),
body: new Uint8Array([1, 2, 3, 4]),
});
const testBlobResponse = new Response(
new Uint8Array([1, 2, 3, 4]),
{
headers: new Headers({
'content-type': 'application/octet-stream',
}),
},
);
test('statusCodeFromError', () => {
strict(statusCodeFromError(new Error('foo')), 500);
strict(statusCodeFromError({}), undefined);
});
test('method', () => {
strict(method(['GET'])(testGetRequest), testGetRequest);
throws(() => method(['POST'])(testGetRequest), HttpError);
});
test('isFormOrJsonPostRequest', () => {
throws(() => validDataPostRequest(testGetRequest), HttpError);
throws(() => validDataPostRequest(testPutRequest), HttpError);
throws(() => validDataPostRequest(testTextRequest), HttpError);
throws(() => validDataPostRequest(testBlobRequest), HttpError);
strict(validDataPostRequest(testJsonRequest), testJsonRequest);
strict(validDataPostRequest(testFormRequest), testFormRequest);
});
test('readBody', async () => {
await throwsAsync(() => readBody({} as Response), TypeError);
await throwsAsync(() => readBody(testJsonResponseInvalid));
strict(await readBody(jsonResponse()), null);
strict(await readBody(testTextRequest), 'foo: bar');
strict(await readBody(testTextResponse), 'foo: bar');
equals(await readBody(testJsonRequest), { foo: 'bar' });
equals(await readBody(testJsonResponse), { foo: 'bar' });
equals(await readBody(testBlobRequest), new Uint8Array([1, 2, 3, 4]).buffer);
equals(await readBody(testBlobResponse), new Uint8Array([1, 2, 3, 4]).buffer);
equals(await readBody(testUrlSearchParamsResponse), { foo: 'bar' });
equals(await readBody(testFormDataResponse), { foo: 'bar' });
});
test('jsonResponse', async () => {
const original = jsonResponse({ foo: 'bar' });
equals(await original.json(), { foo: 'bar' });
const duplicate = jsonResponse(original);
strict(original, duplicate);
strict(jsonResponse().status, 204);
strict(jsonResponse(null).status, 204);
strict(jsonResponse(null, 200).status, 204);
strict(jsonResponse(false).status, 200);
strict(await jsonResponse(false).json(), false);
});
test('readResponseError', async () => {
const explicit = jsonResponse(new HttpError('not found', 404));
const explicitError = await readResponseError(explicit);
matches(explicitError, { message: 'not found', status: 404 });
const implicit = jsonResponse('', 404);
const implicitError = await readResponseError(implicit);
matches(implicitError, { status: 404 });
});
test('fetchOk', () =>
Promise.all([
fetchOk(`${BASE_TEST_HTTP_URL}/200`).then(cancelBody).then(exists),
fetchOk(`${BASE_TEST_HTTP_URL}/301`).then(cancelBody).then(exists),
throwsAsync(() => fetchOk(`${BASE_TEST_HTTP_URL}/301`, { redirect: 'manual' }), HttpError),
throwsAsync(() => fetchOk(`${BASE_TEST_HTTP_URL}/301`, { redirect: 'error' }), Error),
throwsAsync(() => fetchOk(`${BASE_TEST_HTTP_URL}/404`), HttpError),
throwsAsync(() => fetchOk(`${BASE_TEST_HTTP_URL}/500`), HttpError),
]).then(() => {}));
test('fetchPass', () =>
Promise.all([
fetchPass(200, `${BASE_TEST_HTTP_URL}/200`).then(readBody).then(exists),
fetchPass(200, `${BASE_TEST_HTTP_URL}/301`).then(readBody).then(exists),
fetchPass([200, 404], `${BASE_TEST_HTTP_URL}/404`).then(readBody).then(exists),
fetchPass(301, `${BASE_TEST_HTTP_URL}/301`, { redirect: 'manual' }).then(readBody).then(
exists,
),
throwsAsync(
() => fetchPass(200, `${BASE_TEST_HTTP_URL}/301`, { redirect: 'manual' }),
HttpError,
),
throwsAsync(
() => fetchPass(200, `${BASE_TEST_HTTP_URL}/301`, { redirect: 'error' }),
Error,
),
throwsAsync(() => fetchPass([200, 404], `${BASE_TEST_HTTP_URL}/403`), HttpError),
throwsAsync(() => fetchPass(200, `${BASE_TEST_HTTP_URL}/500`), HttpError),
]).then(() => {}));
test('fetchThrow500', () =>
Promise.all([
fetchThrow500(`${BASE_TEST_HTTP_URL}/200`).then(readBody).then(exists),
throwsAsync(() => fetchThrow500(`${BASE_TEST_HTTP_URL}/500`)),
]).then(() => {}));
test('HttpError', () => {
equals(wrapError(SyntaxError)('foo'), new SyntaxError('foo'));
equals(wrapError(HttpError)('foo'), new HttpError('foo'));
});