-
Notifications
You must be signed in to change notification settings - Fork 230
/
http_server_native_test.ts
110 lines (95 loc) · 2.65 KB
/
http_server_native_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
// Copyright 2018-2022 the oak authors. All rights reserved. MIT license.
import {
assertEquals,
assertInstanceOf,
assertStrictEquals,
unreachable,
} from "./test_deps.ts";
import { HttpServer } from "./http_server_native.ts";
import { NativeRequest } from "./http_server_native_request.ts";
import { Application } from "./application.ts";
import { isNode } from "./util.ts";
const { test } = Deno;
function createMockConn() {
return {
localAddr: { transport: "tcp", hostname: "localhost", port: 8000 },
remoteAddr: { transport: "tcp", hostname: "remote", port: 4567 },
rid: 1,
} as Deno.Conn;
}
test({
name: "NativeRequest",
ignore: isNode(),
async fn() {
const respondWithStack: Array<Response | Promise<Response>> = [];
const request = new Request("http://localhost:8000/", {
method: "POST",
body: `{"a":"b"}`,
});
const conn = createMockConn();
const nativeRequest = new NativeRequest(
{
request,
respondWith(v) {
respondWithStack.push(v);
return Promise.resolve();
},
},
{ conn },
);
assertEquals(nativeRequest.url, `/`);
assertEquals(respondWithStack.length, 1);
const response = new Response("hello deno");
nativeRequest.respond(response);
assertStrictEquals(await respondWithStack[0], response);
},
});
test({
name: "HttpServer closes gracefully after serving requests",
ignore: isNode(),
async fn() {
const app = new Application();
const listenOptions = { port: 4505 };
const server = new HttpServer(app, listenOptions);
server.listen();
const expectedBody = "test-body";
(async () => {
for await (const nativeRequest of server) {
nativeRequest.respond(new Response(expectedBody));
}
})();
try {
const response = await fetch(`http://localhost:${listenOptions.port}`);
assertEquals(await response.text(), expectedBody);
} catch {
unreachable();
} finally {
server.close();
}
},
});
test({
name:
"HttpServer manages errors from mis-use in the application handler gracefully",
ignore: isNode(),
async fn() {
const app = new Application();
const listenOptions = { port: 4506 };
const server = new HttpServer(app, listenOptions);
server.listen();
(async () => {
for await (const nativeRequest of server) {
// deno-lint-ignore no-explicit-any
nativeRequest.respond(null as any);
}
})();
try {
await fetch(`http://localhost:${listenOptions.port}`);
unreachable();
} catch (e) {
assertInstanceOf(e, TypeError);
} finally {
server.close();
}
},
});