mihomo-kit/tools/test-servers.js

53 lines
2.5 KiB
JavaScript
Executable File

#!/usr/bin/env node
// luci/servers.js against mihomo's own Go code: tests/links/<x>.expected.json is
// common/convert.ConvertsV2Ray of <x> (ws User-Agent set to servers.js's fixed one),
// tests/yaml/<x>.expected.json is go.yaml.in/yaml/v3 of <x>.yaml.
const fs = require("fs");
const path = require("path");
const s = require("../luci/servers.js");
const root = path.join(__dirname, "..", "tests");
const canon = (v) => Array.isArray(v) ? v.map(canon)
: v && typeof v == "object" ? Object.keys(v).sort().reduce((o, k) => (o[k] = canon(v[k]), o), {}) : v;
let fail = 0;
const check = (name, want, got) => {
const a = JSON.stringify(canon(want)), b = JSON.stringify(canon(got));
if (a === b)
return console.log("ok " + name);
fail = 1;
console.log("FAIL " + name + "\n want " + a + "\n got " + b);
};
for (const f of fs.readdirSync(path.join(root, "links"))) {
if (f.endsWith(".expected.json"))
continue;
const exp = path.join(root, "links", f.replace(/\.[^.]+$/, ".expected.json"));
check("links/" + f, JSON.parse(fs.readFileSync(exp, "utf8")),
s.parseLinks(fs.readFileSync(path.join(root, "links", f), "utf8")));
}
for (const f of fs.readdirSync(path.join(root, "yaml"))) {
if (!f.endsWith(".yaml"))
continue;
const want = JSON.parse(fs.readFileSync(path.join(root, "yaml", f.replace(/\.yaml$/, ".expected.json")), "utf8"));
const got = s.yamlLoad(fs.readFileSync(path.join(root, "yaml", f), "utf8"));
check("yaml/" + f, want, got);
// the editor shows yamlDump; it must read back the same
check("yaml/" + f + " (dump)", want, s.yamlLoad(s.yamlDump(got)));
}
// WireGuard / AmneziaWG .conf and AmneziaVPN keys (vpn://): parseText with the file name
// as the default name; tests/amnezia/<x>.expected.json is checked by hand and with
// `mihomo -t` (key.vpn and keys.txt: qCompress'd JSON as the AmneziaVPN client makes it)
for (const f of fs.readdirSync(path.join(root, "amnezia"))) {
if (f.endsWith(".expected.json"))
continue;
const exp = path.join(root, "amnezia", f.replace(/\.[^.]+$/, ".expected.json"));
check("amnezia/" + f, JSON.parse(fs.readFileSync(exp, "utf8")),
s.parseText(fs.readFileSync(path.join(root, "amnezia", f), "utf8"), f.replace(/\.[^.]+$/, "")));
}
// a stored line reads back the same, without dialer-proxy, with no "$" left
const p = { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}", "dialer-proxy": "Z" };
const line = s.toLine(p);
check("toLine", { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}" },
line.includes("$") || !line.startsWith('{"name":') ? null : JSON.parse(line));
process.exit(fail);