-
Notifications
You must be signed in to change notification settings - Fork 0
/
receiver_test.ts
60 lines (52 loc) · 1.54 KB
/
receiver_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
import { assertEquals, delay, io, streams } from "./deps_test.ts";
import { Receiver } from "./receiver.ts";
const encoder = new TextEncoder();
class Channel implements Deno.Reader, Deno.Writer, Deno.Closer {
#buffer: io.Buffer;
#closed: boolean;
constructor() {
this.#buffer = new io.Buffer();
this.#closed = false;
}
async read(p: Uint8Array): Promise<number | null> {
while (true) {
const n = this.#buffer.readSync(p);
if (n == null) {
if (this.#closed) {
return null;
}
await delay(0);
continue;
}
return n;
}
}
write(p: Uint8Array): Promise<number> {
return this.#buffer.write(p);
}
close(): void {
this.#closed = true;
}
}
Deno.test("Receiver.recv()", async (t) => {
await t.step("receives data until the pattern is received", async () => {
const reader = new Channel();
const receiver = new Receiver(reader);
const producer = async () => {
await streams.writeAll(reader, encoder.encode("Hello world\n"));
await streams.writeAll(reader, encoder.encode("Hello world\n"));
await streams.writeAll(reader, encoder.encode("Hello world\n"));
await delay(100);
await streams.writeAll(reader, encoder.encode("john@debian$ "));
reader.close();
};
const consumer = async () => {
const received = await receiver.recv(/.+\$ $/);
assertEquals(
received,
"Hello world\nHello world\nHello world\njohn@debian$ ",
);
};
await Promise.all([producer(), consumer()]);
});
});