-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.ts
66 lines (57 loc) · 2.07 KB
/
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
import mqtt from "mqtt";
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { randomWords } from "@nordicsemiconductor/random-words";
import { ipv4, ipv6 } from "./ip";
const hostname = process.env.HOSTNAME ?? "localhost";
const ipv = process.env.IPV ?? "ipv4";
const rejectUnauthorized = process.env.VALIDATE_TLS_CERT !== "0";
console.log(`hostname:`, JSON.stringify(hostname));
console.log(`ipv:`, JSON.stringify(ipv));
console.log(`rejectUnauthorized:`, JSON.stringify(rejectUnauthorized));
const addr =
ipv === "ipv6" ? `[${await ipv6(hostname)}]` : await ipv4(hostname);
describe("MQTT server", async () => {
await Promise.all(
[`mqtt:https://${addr}:1883`, `mqtts:https://${addr}:8883`].map((endpoint) =>
describe(endpoint, async () => {
test("the MQTT server should allow to publish and subscribe", async () => {
const msg = `Hello World (${Date.now()})!`;
const topic = randomWords().join("-");
const client = mqtt.connect(endpoint, {
rejectUnauthorized,
servername: hostname,
});
const received = await new Promise<string>((resolve, reject) => {
const t = setTimeout(() => {
reject(new Error(`Timeout!`));
client.end();
}, 5000);
client.on("message", (topic, message) => {
clearTimeout(t);
console.log(`<`, topic);
console.log(`<`, message.toString());
resolve(message.toString());
client.end();
});
console.log(`>`, topic);
console.log(`>`, msg);
client.on("connect", () => {
client.subscribe(topic, (err) => {
if (!err) {
client.publish(topic, msg);
}
});
});
client.on("error", (err) => {
clearTimeout(t);
console.error(err);
reject(err);
});
});
assert.equal(received, msg);
});
}),
),
);
});