-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Expand file tree
/
Copy pathhttp-server.test.mjs
More file actions
79 lines (67 loc) · 2.73 KB
/
Copy pathhttp-server.test.mjs
File metadata and controls
79 lines (67 loc) · 2.73 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
import assert from "node:assert/strict";
import { test } from "node:test";
import { readRequestBody, startInstanceServer } from "./http-server.mjs";
test("readRequestBody decodes UTF-8 after collecting every chunk", async () => {
const body = Buffer.from(JSON.stringify({ answer: "I can explain \ud83e\udde0 and \u6f22\u5b57." }));
const emojiStart = body.indexOf(Buffer.from("\ud83e\udde0"));
async function* chunks() {
yield body.subarray(0, emojiStart + 2);
yield body.subarray(emojiStart + 2);
}
assert.equal(await readRequestBody(chunks()), body.toString("utf8"));
});
test("readRequestBody rejects payloads over the byte limit", async () => {
async function* chunks() {
yield Buffer.alloc(3);
yield Buffer.alloc(2);
}
assert.equal(await readRequestBody(chunks(), 4), null);
});
test("readRequestBody accepts an 8,000-character UTF-8 answer", async () => {
const body = JSON.stringify({ type: "submit-answer", answer: "漢".repeat(8000) });
async function* chunks() {
yield Buffer.from(body);
}
assert.equal(await readRequestBody(chunks()), body);
});
test("instance APIs require their capability token", async (t) => {
const events = [];
const server = await startInstanceServer("test-instance", () => ({ view: "domains" }), (event) => {
events.push(event);
return { ok: true };
});
t.after(() => server.close());
const stateUrl = new URL(server.url);
stateUrl.pathname = "/state";
const unauthorizedStateUrl = new URL(stateUrl);
unauthorizedStateUrl.search = "";
assert.equal((await fetch(unauthorizedStateUrl)).status, 403);
unauthorizedStateUrl.searchParams.set("token", "漢".repeat(43));
assert.equal((await fetch(unauthorizedStateUrl)).status, 403);
assert.deepEqual(await (await fetch(stateUrl)).json(), { view: "domains" });
const eventsUrl = new URL(server.url);
eventsUrl.pathname = "/events";
eventsUrl.search = "";
assert.equal((await fetch(eventsUrl)).status, 403);
const eventUrl = new URL(server.url);
eventUrl.pathname = "/event";
const unauthorizedEventUrl = new URL(eventUrl);
unauthorizedEventUrl.search = "";
assert.equal(
(await fetch(unauthorizedEventUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "compile-report" }),
})).status,
403,
);
assert.equal(
(await fetch(eventUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "compile-report" }),
})).status,
202,
);
assert.deepEqual(events, [{ type: "compile-report" }]);
});