-
Notifications
You must be signed in to change notification settings - Fork 22
/
base-protocol.test.ts
76 lines (67 loc) · 2.44 KB
/
base-protocol.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
import { StringReader } from "https://deno.land/std@0.147.0/io/readers.ts";
import { Buffer } from "https://deno.land/std@0.147.0/io/buffer.ts";
import {
assertEquals,
assertRejects,
} from "https://deno.land/std@0.147.0/testing/asserts.ts";
import {
readBaseProtocolMessages,
writeBaseProtocolMessage,
} from "./base-protocol.ts";
Deno.test("base-protocol/readBaseProtocolMessages: Success", async () => {
const body = `{"hello": "world"}`;
const reader = new StringReader(
[`Content-Length: ${body.length}`, "", body].join("\r\n"),
);
const message = (await readBaseProtocolMessages(reader).next()).value;
assertEquals([...message.headers.entries()], [["content-length", "18"]]);
assertEquals(message.body, new TextEncoder().encode(body));
});
Deno.test("base-protocol/readBaseProtocolMessages: Throw an error on malformed header", () => {
const reader = new StringReader(
`{}`,
);
assertRejects(
() => readBaseProtocolMessages(reader).next(),
Deno.errors.InvalidData,
);
});
Deno.test("base-protocol/readBaseProtocolMessages: Throw an error on no content-length", () => {
const reader = new StringReader(
["Weird-Header: 3", "", "{}"].join("\r\n"),
);
assertRejects(
() => readBaseProtocolMessages(reader).next(),
Error,
"Header must provide a Content-Length property.",
);
});
Deno.test("base-protocol/readBaseProtocolMessages: Throw an error on content-length is not a number", () => {
const reader = new StringReader(
["Content-Length: a", "", "{}"].join("\r\n"),
);
assertRejects(
() => readBaseProtocolMessages(reader).next(),
Error,
"Content-Length value must be a number.",
);
});
Deno.test("base-protocol/writeBaseProtocolMessage: Success", async () => {
const messageBuffer = new Buffer();
const body = new TextEncoder().encode('{"hello": "world"}');
await writeBaseProtocolMessage(messageBuffer, body);
assertEquals(
new TextDecoder().decode(messageBuffer.bytes()),
`content-length: 18\r\n\r\n{"hello": "world"}`,
);
});
Deno.test("base-protocol/writeBaseProtocolMessage: Success with headers", async () => {
const messageBuffer = new Buffer();
const body = new TextEncoder().encode('{"hello": "world"}');
const headers = new Headers({ "header": "hi" });
await writeBaseProtocolMessage(messageBuffer, body, headers);
assertEquals(
new TextDecoder().decode(messageBuffer.bytes()),
`content-length: 18\r\nheader: hi\r\n\r\n{"hello": "world"}`,
);
});