Alex2Node/test/helpers/loopback.js
David 8379a65d78 examples: one runnable file per recipe on the 2.0 API, the 1.x files in examples/legacy
Ten recipes: lamp, colour lamp, thermostat, blind, lock (deferred), contact
sensor (ChangeReport), scene, doorbell (raise), typed errors, and a plug as an
ES module. Each reads ALEX2MQTT_USERNAME, _PASSWORD and _ROOT_TOPIC and names
the ones that are missing. The nine examples of 1.5.2 move to examples/legacy
unchanged.

test/examples.test.js starts every file with node, its broker connection sent
to a broker on 127.0.0.1 (test/helpers/loopback.js), discovers the device,
sends directives and checks the answers. A legacy file is started and its
discovery compared with the answer the 1.5.2 build gave, recorded in
test/fixtures/legacy-examples.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 21:38:07 +00:00

16 lines
981 B
JavaScript

"use strict";
// Preloaded with node --require into an example that a test runs. An example connects to the broker of Alex2MQTT,
// the test has one on 127.0.0.1: every TCP connection of the process goes to LOOPBACK_PORT on 127.0.0.1, whatever
// host and port it names. Nothing of an example under test leaves the machine.
const net = require("node:net");
const port = Number(process.env.LOOPBACK_PORT);
if (!Number.isInteger(port) || port <= 0) throw new Error("LOOPBACK_PORT is not set: the port of the broker of the test");
const connect = net.Socket.prototype.connect;
net.Socket.prototype.connect = function toLoopback(...args) {
// connect(options, listener), connect(port, host, listener), or the two in an array as net.createConnection() passes them
const given = Array.isArray(args[0]) ? args[0] : args;
const listener = given.find((arg) => typeof arg === "function");
return connect.call(this, { host: "127.0.0.1", port }, ...(listener ? [listener] : []));
};