-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_test.ts
71 lines (62 loc) · 2.27 KB
/
server_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
import {
assertEquals, assertNotEquals,
} from "https://deno.land/std@0.92.0/testing/asserts.ts";
import { delay } from "https://deno.land/std@0.92.0/async/delay.ts";
import {
WebSocket,
WebSocketEvent,
} from "https://deno.land/std@0.92.0/ws/mod.ts";
import { serve, WebSocketServer } from "./server.ts";
const { test } = Deno;
// serve
test("that `serve` returns a server", async () => {
const port = 8123;
const server = serve({ port });
await server.close();
});
// server
test("that a `WebSocketServer` receives events from a client", async () => {
async function saveIterationResults(
items: { socket: WebSocket; event: WebSocketEvent; }[],
server: WebSocketServer
) {
for await (const wsEvent of server) {
items.push(wsEvent);
}
}
const port = 8123;
const server = serve({ port });
const results: { socket: WebSocket; event: WebSocketEvent; }[] = [];
saveIterationResults(results, server);
const msgsPerClient = 3;
const client1 = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise(resolve => client1.addEventListener('open', resolve))
const client2 = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise(resolve => client2.addEventListener('open', resolve))
client1.send("client 1");
await delay(10);
client2.send("client 2");
await delay(10);
client1.send(new Uint8Array([1, 2, 3]));
await delay(10);
client2.send(new Uint8Array([4, 5, 6]));
await delay(10);
client1.close(3001, "done");
await delay(10);
client2.close(3002, "done");
await delay(10);
assertEquals(server.sockets.size, 0, "sockets have not been untracked");
assertEquals(results.length, 2 * msgsPerClient, "not all events were read");
assertEquals(results[0].socket, results[2].socket, "first sockets");
assertEquals(results[0].socket, results[4].socket);
assertEquals(results[1].socket, results[3].socket);
assertEquals(results[1].socket, results[5].socket);
assertNotEquals(results[0].socket, results[1].socket);
assertEquals(results[0].event, "client 1");
assertEquals(results[1].event, "client 2");
assertEquals(results[2].event, new Uint8Array([1, 2, 3]));
assertEquals(results[3].event, new Uint8Array([4, 5, 6]));
assertEquals(results[4].event, { code: 3001, reason: "done" });
assertEquals(results[5].event, { code: 3002, reason: "done" });
await server.close();
});