-
Notifications
You must be signed in to change notification settings - Fork 235
/
context.test.ts
398 lines (374 loc) · 11.4 KB
/
context.test.ts
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// Copyright 2018-2024 the oak authors. All rights reserved. MIT license.
// deno-lint-ignore-file
import { assertEquals, assertStrictEquals, assertThrows } from "./deps_test.ts";
import type { Application, State } from "./application.ts";
import { Context } from "./context.ts";
import { assert, errors, SecureCookieMap, Status } from "./deps.ts";
import { NativeRequest } from "./http_server_native_request.ts";
import type {} from "./http_server_native.ts";
import { Request as OakRequest } from "./request.ts";
import { Response as OakResponse } from "./response.ts";
import type { UpgradeWebSocketFn, UpgradeWebSocketOptions } from "./types.ts";
import { cloneState } from "./utils/clone_state.ts";
import { isNode } from "./utils/type_guards.ts";
import { createPromiseWithResolvers } from "./utils/create_promise_with_resolvers.ts";
function createMockApp<S extends State = Record<string, any>>(
state = {} as S,
): Application<S> {
let listeners: any[] = [];
return {
state,
listeners,
dispatchEvent() {},
addEventListener(event: string) {
listeners.push(event);
},
[Symbol.for("Deno.customInspect")]() {
return `MockApplication {}`;
},
[Symbol.for("nodejs.util.inspect.custom")](
depth: number,
options: any,
inspect: (value: unknown, options?: unknown) => string,
) {
if (depth < 0) {
return options.stylize(`[MockApplication]`, "special");
}
const newOptions = Object.assign({}, options, {
depth: options.depth === null ? null : options.depth - 1,
});
return `${options.stylize("MockApplication", "special")} ${
inspect({}, newOptions)
}`;
},
} as any;
}
interface MockNativeOptions {
url?: string;
requestInit?: RequestInit;
upgradeThrow?: boolean;
upgradeUndefined?: boolean;
}
let respondWithStack: (Response | Promise<Response>)[] = [];
let upgradeWebSocketStack: [Request, UpgradeWebSocketOptions | undefined][] =
[];
const mockWebSocket = {} as WebSocket;
const mockResponse = {} as Response;
function createMockNativeRequest(
{
url = "http://localhost/",
requestInit = { headers: [["host", "localhost"]] },
upgradeThrow = true,
upgradeUndefined = false,
}: MockNativeOptions = {},
) {
respondWithStack = [];
upgradeWebSocketStack = [];
const request = new Request(url, requestInit);
const upgradeWebSocket: UpgradeWebSocketFn | undefined = upgradeUndefined
? undefined
: (request, options) => {
if (upgradeThrow) {
throw new TypeError("Cannot upgrade connection.");
}
upgradeWebSocketStack.push([request, options]);
return { response: mockResponse, socket: mockWebSocket };
};
const nativeRequest = new NativeRequest(request, { upgradeWebSocket });
const { promise, resolve } = createPromiseWithResolvers<Response>();
respondWithStack.push(promise);
nativeRequest.response.then((response) => resolve(response));
return nativeRequest;
}
Deno.test({
name: "context",
fn() {
const app = createMockApp();
const serverRequest = createMockNativeRequest();
const context = new Context(app, serverRequest, cloneState(app.state));
assert(context instanceof Context);
assertEquals(context.state, app.state);
assertStrictEquals(context.app, app);
assert(context.cookies instanceof SecureCookieMap);
assert(context.request instanceof OakRequest);
assert(context.request.source instanceof Request);
assert(context.response instanceof OakResponse);
},
});
Deno.test({
name: "context.assert()",
fn() {
const context: Context = new Context(
createMockApp(),
createMockNativeRequest(),
{},
);
assertThrows(
() => {
let loggedIn: string | undefined;
context.assert(loggedIn, 401, "Unauthorized");
},
errors.Unauthorized,
"Unauthorized",
);
},
});
Deno.test({
name: "context.assert() headers",
fn() {
const context: Context = new Context(
createMockApp(),
createMockNativeRequest(),
{},
);
assertThrows(
() => {
let loggedIn: string | undefined;
context.assert(loggedIn, 401, "Unauthorized", {
headers: new Headers({
"WWW-Authenticate":
'Bearer realm="oak-tests",error="invalid_token"',
}),
});
},
errors.Unauthorized,
"Unauthorized",
);
},
});
Deno.test({
name: "context.assert() expose",
fn() {
const context: Context = new Context(
createMockApp(),
createMockNativeRequest(),
{},
);
assertThrows(
() => {
let loggedIn: string | undefined;
context.assert(loggedIn, 401, "Unauthorized", {
expose: true,
});
},
errors.Unauthorized,
"Unauthorized",
);
},
});
Deno.test({
name: "context.assert() no redundant status",
fn() {
const context: Context = new Context(
createMockApp(),
createMockNativeRequest(),
{},
);
assertThrows(
() => {
let loggedIn: string | undefined;
context.assert(loggedIn, 401, "Unauthorized", {
status: Status.Unauthorized,
});
},
TypeError,
"Cannot set property status of Error which has only a getter",
);
},
});
Deno.test({
name: "context.throw()",
fn() {
const context = new Context(createMockApp(), createMockNativeRequest(), {});
assertThrows(
() => {
context.throw(404, "foobar");
},
errors.NotFound,
"foobar",
);
},
});
Deno.test({
name: "context.send() default path",
async fn() {
const context = new Context(
createMockApp(),
createMockNativeRequest({ url: "http://localhost/test.html" }),
{},
);
const fixture = await Deno.readFile("./fixtures/test.html");
await context.send({ root: "./fixtures", maxbuffer: 0 });
const response = await context.response.toDomResponse();
const ab = await response.arrayBuffer();
assertEquals(new Uint8Array(ab), fixture);
assertEquals(context.response.type, ".html");
assert(context.response.headers.get("last-modified") != null);
assertEquals(context.response.headers.get("cache-control"), "max-age=0");
context.response.destroy();
},
});
Deno.test({
name: "context.send() specified path",
async fn() {
const context = new Context(createMockApp(), createMockNativeRequest(), {});
const fixture = await Deno.readFile("./fixtures/test.html");
await context.send({
path: "/test.html",
root: "./fixtures",
maxbuffer: 0,
});
const response = await context.response.toDomResponse();
const ab = await response.arrayBuffer();
assertEquals(new Uint8Array(ab), fixture);
assertEquals(context.response.type, ".html");
assert(context.response.headers.get("last-modified") != null);
assertEquals(context.response.headers.get("cache-control"), "max-age=0");
context.response.destroy();
},
});
Deno.test({
name: "context.upgrade()",
async fn() {
const context = new Context(
createMockApp(),
createMockNativeRequest({
url: "http://localhost/",
requestInit: {
headers: [
["upgrade", "websocket"],
["sec-websocket-key", "abc"],
["host", "localhost"],
],
},
upgradeThrow: false,
}),
{},
);
assert(context.socket === undefined);
const ws = context.upgrade();
assert(ws);
assertStrictEquals(context.socket, ws);
assertStrictEquals(ws, mockWebSocket);
assertEquals(context.respond, false);
assertEquals(respondWithStack.length, 1);
assertStrictEquals(await respondWithStack[0], mockResponse);
assertEquals(upgradeWebSocketStack.length, 1);
assertEquals((context.app as any).listeners, ["close"]);
},
});
Deno.test({
name: "context.upgrade() - not supported",
async fn() {
const context = new Context(
createMockApp(),
createMockNativeRequest({
url: "http://localhost/",
requestInit: {
headers: [
["upgrade", "websocket"],
["sec-websocket-key", "abc"],
["host", "localhost"],
],
},
upgradeUndefined: true,
}),
{},
);
assert(context.socket === undefined);
assertThrows(
() => {
context.upgrade();
},
TypeError,
"Upgrading web sockets not supported.",
);
assert(context.socket === undefined);
assertEquals(context.respond, true);
},
});
Deno.test({
name: "context.upgrade() failure does not set socket/respond",
async fn() {
const context = new Context(createMockApp(), createMockNativeRequest(), {});
assert(context.socket === undefined);
assertThrows(() => {
context.upgrade();
});
assert(context.socket === undefined);
assertEquals(context.respond, true);
},
});
Deno.test({
name: "context.isUpgradable true",
async fn() {
const context = new Context(
createMockApp(),
createMockNativeRequest({
url: "http://localhost/",
requestInit: {
headers: [
["upgrade", "websocket"],
["sec-websocket-key", "abc"],
["host", "localhost"],
],
},
}),
{},
);
assertEquals(context.isUpgradable, true);
},
});
Deno.test({
name: "context.isUpgradable false",
async fn() {
const context = new Context(
createMockApp(),
createMockNativeRequest({
url: "http://localhost/",
requestInit: {
headers: [
["upgrade", "websocket"],
],
},
}),
{},
);
assertEquals(context.isUpgradable, false);
},
});
Deno.test({
name: "context.sendEvents()",
async fn() {
const context = new Context(createMockApp(), createMockNativeRequest(), {});
const sse = await context.sendEvents();
assertEquals((context.app as any).listeners, ["close"]);
sse.dispatchComment(`hello world`);
await sse.close();
},
});
Deno.test({
name: "context create secure",
fn() {
const context = new Context(
createMockApp(),
createMockNativeRequest(),
{},
{ secure: true },
);
assertEquals(context.request.secure, true);
},
});
Deno.test({
name: "Context - inspecting",
fn() {
const app = createMockApp();
const req = createMockNativeRequest();
assertEquals(
Deno.inspect(new Context(app, req, {}), { depth: 1 }),
isNode()
? `Context {\n app: [MockApplication],\n cookies: [SecureCookieMap],\n isUpgradable: false,\n respond: true,\n request: [Request],\n response: [Response],\n socket: undefined,\n state: {}\n}`
: `Context {\n app: MockApplication {},\n cookies: SecureCookieMap [],\n isUpgradable: false,\n respond: true,\n request: Request {\n body: Body { has: false, used: false },\n hasBody: false,\n headers: Headers { host: "localhost" },\n ip: "",\n ips: [],\n method: "GET",\n secure: false,\n url: "http://localhost/",\n userAgent: UserAgent {\n browser: { name: undefined, version: undefined, major: undefined },\n cpu: { architecture: undefined },\n device: { model: undefined, type: undefined, vendor: undefined },\n engine: { name: undefined, version: undefined },\n os: { name: undefined, version: undefined },\n ua: ""\n}\n},\n response: Response {\n body: undefined,\n headers: Headers {},\n status: 404,\n type: undefined,\n writable: true\n},\n socket: undefined,\n state: {}\n}`,
);
},
});