Merge remote-tracking branch 'origin/master' into plugin-minimap

This commit is contained in:
Danielv123 committed 2026-01-27 17:45:23 +01:00
commit 979d961618
131 files changed
+6585 -2515

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
"use strict";
const assert = require("assert").strict;
/**
* Generate a flat array of tests from a matrix of inputs.
*
* @template {any[][]} T
* @param {T} arrays - A list of arrays representing the different values for each argument
* @returns {Array<{ [K in keyof T]: T[K][number] }>}
* An array of tuples, each containing one value from each input array.
*/
function testMatrix(...arrays) {
return arrays.reduce((acc, curr) => acc.flatMap(a => curr.map(b => [...a, b])), [[]]);
}
/**
* Test that a class is round trip json serialisable across multiple test cases.
*
* @template {any[]} T - Constructor arguments
* @param {{new(...args: T): object}} Class - The class which has toJSON and fromJSON methods.
* @param {T[]} tests - The tests inputs to pass to the class constructor.
*/
function testRoundTripJsonSerialisable(Class, tests) {
for (const test of tests) {
const original = new Class(...test);
const serialised = JSON.stringify(original);
const reconstructed = Class.fromJSON(JSON.parse(serialised));
assert.deepEqual(reconstructed, original, JSON.stringify(test));
}
}
module.exports = {
testMatrix,
testRoundTripJsonSerialisable,
};
+107 -2
View File
@@ -1,9 +1,14 @@
"use strict";
const path = require("node:path");
const assert = require("assert").strict;
const { Controller, HostInfo, InstanceInfo } = require("@clusterio/controller");
const { ControllerConfig, Address, RequestError, InstanceConfig, SystemInfo, Role } = require("@clusterio/lib");
const { EventEmitter } = require("stream");
const {
ControllerConfig, Address, RequestError,
InstanceConfig, SystemInfo, Role, ModPack,
} = require("@clusterio/lib");
class MockEvent {}
class MockInstanceConfig extends EventEmitter {
@@ -27,8 +32,10 @@ describe("controller/src/Controller", function() {
describe("class Controller", function() {
/** @type {Controller} */
let controller, mockInstanceConfig;
const controllerVersion = require("@clusterio/controller/package.json").version;
before(async function() {
controller = new Controller({}, [], new ControllerConfig("controller"));
const controllerConfig = new ControllerConfig("controller", { "controller.version": controllerVersion });
controller = new Controller({}, [], controllerConfig);
mockInstanceConfig = new MockInstanceConfig(new Map([
["instance.id", 100], ["instance.name", "test"], ["factorio.settings", []],
]));
@@ -233,6 +240,62 @@ describe("controller/src/Controller", function() {
assert(instanceInfo.updatedAtMs === 0, "updatedAtMs incremented");
});
});
describe(".checkRestartRequired()", function() {
beforeEach(function() {
// Would not be needed if controller setup was beforeEach
controller.config.restartRequired = false;
controller.config.set("controller.version", controllerVersion);
controller.config.set("global_chat.load_plugin", true);
controller.pluginInfos[0] = {
name: "global_chat",
requirePath: path.dirname(require.resolve("@clusterio/controller/package.json")),
version: controllerVersion,
};
});
it("returns false when no changes are present", async function() {
controller.pluginInfos[0].webEntrypoint = true;
controller.pluginInfos[0].controllerEntrypoint = true;
const result = await controller.checkRestartRequired();
assert.equal(result, false);
assert.equal(controller.config.restartRequired, false);
});
it("returns false when an unloaded plugin version changes", async function() {
controller.pluginInfos[0].version = "0.0.0";
controller.pluginInfos[0].webEntrypoint = true;
controller.pluginInfos[0].controllerEntrypoint = true;
controller.config.set("global_chat.load_plugin", false);
controller.config.restartRequired = false; // Setting load_plugin requires a restart
const result = await controller.checkRestartRequired();
assert.equal(result, false);
assert.equal(controller.config.restartRequired, false);
});
it("returns true when the config flag is set", async function() {
controller.config.restartRequired = true;
const result = await controller.checkRestartRequired();
assert.equal(result, true);
assert.equal(controller.config.restartRequired, true);
});
it("returns true when clusterio version changes", async function() {
controller.config.set("controller.version", "0.0.0");
const result = await controller.checkRestartRequired();
assert.equal(result, true);
assert.equal(controller.config.restartRequired, true);
});
it("returns true when a controller plugin version changes", async function() {
controller.pluginInfos[0].version = "0.0.0";
controller.pluginInfos[0].controllerEntrypoint = true;
const result = await controller.checkRestartRequired();
assert.equal(result, true);
assert.equal(controller.config.restartRequired, true);
});
it("returns true when a web plugin version changes", async function() {
controller.pluginInfos[0].version = "0.0.0";
controller.pluginInfos[0].webEntrypoint = true;
const result = await controller.checkRestartRequired();
assert.equal(result, true);
assert.equal(controller.config.restartRequired, true);
});
});
});
describe("migrations", function() {
describe("SystemInfo", function() {
@@ -314,6 +377,48 @@ describe("controller/src/Controller", function() {
]);
});
});
describe("ModPack", function() {
it("migrates builtin mod versions to X.Y.Z", function() {
const modPacks = Controller.migrateModPacks([{
id: 0,
name: "name",
factorio_version: "2.0",
mods: [
{ name: "base", version: "2.0" },
{ name: "my-mod", version: "1.0.0" },
],
}]);
assert.deepEqual(modPacks, [{
id: 0,
name: "name",
factorio_version: "2.0",
mods: [
{ name: "base", version: "2.0.0" },
{ name: "my-mod", version: "1.0.0" },
],
}]);
});
it("does nothing for upto date data", function() {
const modPack = ModPack.fromJSON({
id: 0,
name: "name",
factorio_version: "2.0",
mods: [
{ name: "base", version: "2.0.0" },
{ name: "my-mod", version: "1.0.0" },
],
});
const jsonString = JSON.stringify(modPack);
const modPackJson = JSON.parse(jsonString);
const modPackJsonCopy = JSON.parse(jsonString);
const result = Controller.migrateModPacks([
modPackJson, modPackJson, modPackJson,
]);
assert.deepEqual(result, [
modPackJsonCopy, modPackJsonCopy, modPackJsonCopy,
]);
});
});
describe("Role", function() {
it("migrates renamed permissions", function() { // Alpha 17
const result = Controller.migrateRoles([
+13
View File
@@ -74,6 +74,19 @@ describe("controller/src/routes", function() {
assert.equal(await responses[1].text(), "test content");
});
});
describe("/api/cluster-name", function() {
let endpoint;
beforeEach(function() {
endpoint = `http://localhost:${port}/api/cluster-name`;
});
it("should return the cluster name from config", async function() {
controller.mockConfigEntries.set("controller.name", "Test Cluster");
let response = await fetch(endpoint);
assert.equal(response.status, 200);
let data = await response.json();
assert.deepEqual(data, { name: "Test Cluster" });
});
});
describe("/api/upload-save", function() {
let endpoint;
beforeEach(function() {
File diff suppressed because it is too large. Load diff
+59
View File
@@ -6,6 +6,7 @@ const lib = require("@clusterio/lib");
const Host = require("@clusterio/host/dist/node/src/Host").default;
const Instance = require("@clusterio/host/dist/node/src/Instance").default;
const { _discoverInstances } = require("@clusterio/host/dist/node/src/Host");
const { HostConnector } = require("@clusterio/host/dist/node/host");
describe("Host testing", function() {
describe("discoverInstances()", function() {
@@ -115,5 +116,63 @@ describe("Host testing", function() {
]);
});
});
describe(".checkRestartRequired()", function() {
let host;
beforeEach(function() {
// This can be used more generally, but i did not want to interfere with handleSyncUserListsEvent
const hostVersion = require("@clusterio/host/package.json").version;
const pluginInfos = [{
name: "global_chat",
requirePath: path.dirname(require.resolve("@clusterio/host/package.json")),
version: hostVersion,
}];
const hostConfig = new lib.HostConfig("host", { "host.version": hostVersion });
const hostConnector = new HostConnector(hostConfig, undefined, pluginInfos);
host = new Host(hostConnector, hostConfig, undefined, pluginInfos);
});
it("returns false when no changes are present", async function() {
host.pluginInfos[0].hostEntrypoint = true;
host.pluginInfos[0].instanceEntrypoint = true;
const result = await host.checkRestartRequired();
assert.equal(result, false);
assert.equal(host.config.restartRequired, false);
});
it("returns false when an unloaded plugin version changes", async function() {
host.pluginInfos[0].version = "0.0.0";
host.pluginInfos[0].hostEntrypoint = true;
host.pluginInfos[0].instanceEntrypoint = true;
host.config.set("global_chat.load_plugin", false);
host.config.restartRequired = false; // Setting load_plugin requires a restart
const result = await host.checkRestartRequired();
assert.equal(result, false);
assert.equal(host.config.restartRequired, false);
});
it("returns true when the config flag is set", async function() {
host.config.restartRequired = true;
const result = await host.checkRestartRequired();
assert.equal(result, true);
assert.equal(host.config.restartRequired, true);
});
it("returns true when clusterio version changes", async function() {
host.config.set("host.version", "0.0.0");
const result = await host.checkRestartRequired();
assert.equal(result, true);
assert.equal(host.config.restartRequired, true);
});
it("returns true when a host plugin version changes", async function() {
host.pluginInfos[0].version = "0.0.0";
host.pluginInfos[0].hostEntrypoint = true;
const result = await host.checkRestartRequired();
assert.equal(result, true);
assert.equal(host.config.restartRequired, true);
});
it("returns true when an instance plugin version changes", async function() {
host.pluginInfos[0].version = "0.0.0";
host.pluginInfos[0].instanceEntrypoint = true;
const result = await host.checkRestartRequired();
assert.equal(result, true);
assert.equal(host.config.restartRequired, true);
});
});
});
});
+141 -5
View File
@@ -13,8 +13,8 @@ const { wait } = lib;
const testStrings = require("../lib/factorio/test_strings");
const {
TestControl, TestControlConnector, url, controlToken, slowTest,
exec, execCtl, execCtlProcess, execHost, sendRcon, getControl,
spawnNode, instancesDir, factorioDir,
execCtl, execCtlProcess, execController, execHost, sendRcon, getControl,
spawnNode, instancesDir, factorioDir, databaseDir, controllerConfigPath,
} = require("./index");
@@ -109,16 +109,59 @@ describe("Integration of Clusterio", function() {
describe("clusteriocontroller", function() {
describe("bootstrap generate-user-token", function() {
it("work for existing user", async function() {
await exec("node ../../packages/controller bootstrap generate-user-token test");
await execController("bootstrap generate-user-token test");
});
it("fails if user does not exist", async function() {
await assert.rejects(
exec("node ../../packages/controller bootstrap generate-user-token invalid")
execController("bootstrap generate-user-token invalid")
);
});
});
describe("bootstrap create-admin", function() {
it("should refuse to modify the database files when locked", async function() {
await assert.rejects(
execController("bootstrap create-admin BootstrapAdminTest")
);
});
it("should modify the database files when locked if bypass option is given", async function() {
const lockFilePath = `${controllerConfigPath}.lock`;
await fs.copyFile(lockFilePath, "temp.lock");
try {
await execController("bootstrap create-admin BootstrapAdminTest2 --bypass-lock-file");
} finally {
await fs.move("temp.lock", lockFilePath); // Replace the lockfile after it is deleted
}
const json = await fs.readJSON(path.join(databaseDir, "users.json"));
assert.equal(Object.values(json).some(user => user.name === "BootstrapAdminTest2"), true);
});
});
describe("config", function() {
it("can read the config file", async function() {
await execController("config list");
});
it("should refuse to modify the config file while locked", async function() {
await assert.rejects(
execController("config set controller.name ConfigEditTest")
);
});
it("should modify the config file while locked if bypass option is given", async function() {
const lockFilePath = `${controllerConfigPath}.lock`;
await fs.copyFile(lockFilePath, "temp.lock");
try {
await execController("config set controller.name ConfigEditTest2 --bypass-lock-file");
} finally {
await fs.move("temp.lock", lockFilePath); // Replace the lockfile after it is deleted
}
const json = await fs.readJSON(path.join(controllerConfigPath));
assert.equal(json["controller.name"], "ConfigEditTest2");
});
});
describe("run", function() {
it("should handle resume of an active connection", async function() {
slowTest(this);
@@ -143,6 +186,38 @@ describe("Integration of Clusterio", function() {
await events.once(connectorB, "resume");
await connectorB.close(1000, "");
});
it("should refuse to start a second process while locked", async function() {
await assert.rejects(execController("run"));
});
it("should start a second process while locked if bypass option is given", async function() {
slowTest(this);
const lockFilePath = `${controllerConfigPath}.lock`;
await fs.copyFile(lockFilePath, "temp.lock");
try {
await execController("run --bypass-lock-file");
} catch (err) {
assert.equal(/Error: Server listening failed/.test(err.stderr), true);
}
await fs.move("temp.lock", lockFilePath); // Replace the lockfile after it is deleted
});
it("should refuse to start when no users are loaded", async function() {
const dir = path.join("temp", "test", "empty_controller");
await fs.emptyDir(dir);
await assert.rejects(execController("run", { cwd: dir }));
});
it("should start when no users are loaded if bypass option given", async function() {
slowTest(this);
const dir = path.join("temp", "test", "empty_controller");
await fs.emptyDir(dir);
const child = await spawnNode(
"altController",
"../../../packages/controller run --no-check-user-count",
/Started controller/,
{ cwd: dir },
);
assert.ok(child.kill());
assert.equal(child.killed, true);
});
});
describe("queryLogRequestHandler", function() {
@@ -245,6 +320,67 @@ describe("Integration of Clusterio", function() {
await stopAltHost(hostProcess);
}
});
describe("config", function() {
it("can read the config file", async function() {
await execHost("config list");
});
it("should refuse to modify the config file while locked", async function() {
slowTest(this);
let hostProcess; // Alt host used since the process could get killed
const config = "alt-host-config.json";
try {
hostProcess = await startAltHost();
await assert.rejects(
execHost(`--config ${config} config set host.name ConfigEditTest`)
);
} finally {
await stopAltHost(hostProcess);
}
});
it("should modify the config file while locked if bypass option is given", async function() {
slowTest(this);
let hostProcess; // Alt host used since the process could get killed
const config = "alt-host-config.json";
try {
hostProcess = await startAltHost();
await execHost(`--config ${config} config set host.name ConfigEditTest2 --bypass-lock-file`);
} finally {
await stopAltHost(hostProcess);
}
const json = await fs.readJSON(path.join("temp", "test", config));
assert.equal(json["host.name"], "ConfigEditTest2");
});
});
describe("run", function() {
it("should refuse to start a second process while locked", async function() {
slowTest(this);
let hostProcess; // Alt host used since the process could get killed
const config = "alt-host-config.json";
try {
hostProcess = await startAltHost();
await assert.rejects(
execHost(`--config ${config} run`)
);
} finally {
await stopAltHost(hostProcess);
}
});
it("should start a second process while locked if bypass option is given", async function() {
slowTest(this);
let hostProcessA, hostProcessB; // Alt host used since the process could get killed
const config = "alt-host-config.json";
try {
hostProcessA = await startAltHost();
hostProcessB = await spawnNode(
"alt-host-b:", `../../packages/host run --config ${config} --bypass-lock-file`, /Started host/
);
} finally {
await stopAltHost(hostProcessA);
await stopAltHost(hostProcessB);
}
});
});
});
describe("clusterioctl", function() {
@@ -951,7 +1087,7 @@ describe("Integration of Clusterio", function() {
await execCtl("instance start 44");
const instance = (await getInstances()).get(44);
const isV2 = lib.integerFactorioVersion(instance.factorioVersion) > lib.integerFactorioVersion("2.0.0");
const isV2 = lib.integerPartialVersion(instance.factorioVersion) > lib.integerPartialVersion("2.0");
const exchangeString = (isV2 ? testStrings.modified_v2 : testStrings.modified).replace(/[\n\r]+/g, "");
const args = `base/freeplay --seed 1234 --map-exchange-string "${exchangeString}"`;
await execCtl("instance stop 44");
+26 -15
View File
@@ -119,15 +119,14 @@ class TestHostConnector extends lib.WebSocketClientConnector {
}
}
// Mark that this test takes a lot of time, or depeneds on a test
// that takes a lot of time.
// Mark that this test takes a lot of time, or depends on a test that takes a lot of time.
function slowTest(test) {
if (process.env.FAST_TEST) {
test.skip();
}
test.timeout(20000);
test.timeout(30000);
}
async function get(urlPath) {
@@ -176,29 +175,31 @@ let controllerConfigPath = path.join("temp", "test", "config-controller.json");
let hostConfigPath = path.join("temp", "test", "config-host.json");
let controlConfigPath = path.join("temp", "test", "config-control.json");
async function exec(command, options = {}) {
function exec(command, options = {}) {
// Uncomment to show commands run in tests
// console.log(command);
options = { cwd: path.join("temp", "test"), ...options };
return await util.promisify(child_process.exec)(command, options);
return util.promisify(child_process.exec)(command, options);
}
async function execController(...args) {
function execController(...args) {
args[0] = `node --enable-source-maps ../../packages/controller ${args[0]}`;
return await exec(...args);
return exec(...args);
}
async function execHost(...args) {
function execHost(...args) {
args[0] = `node --enable-source-maps ../../packages/host ${args[0]}`;
return await exec(...args);
return exec(...args);
}
async function execCtlProcess(...args) {
function execCtlProcess(...args) {
args[0] = `node --enable-source-maps ../../packages/ctl ${args[0]}`;
return await exec(...args);
return exec(...args);
}
let inExecCtl = false;
async function execCtl(command) {
inExecCtl = true;
process.chdir("temp/test");
try {
const initArgs = await initializeCtl(command, control.plugins, true);
@@ -211,9 +212,17 @@ async function execCtl(command) {
await targetCommand.run(initArgs.args, control);
} finally {
process.chdir("../..");
inExecCtl = false;
}
}
afterEach(function() {
if (inExecCtl) {
// This is needed in case a test times out and never runs the finally block
process.chdir("../..");
}
});
async function sendRcon(instanceId, command) {
return await control.sendTo({ instanceId }, new lib.InstanceSendRconRequest(command));
}
@@ -222,7 +231,8 @@ function getControl() {
return control;
}
function spawn(name, cmd, waitFor) {
/** @returns {Promise<child_process.ChildProcess>} */
function spawn(name, cmd, waitFor, options = {}) {
const silent = process.env.SILENT_TEST;
const bootstrap = !controllerProcess || !hostProcess;
@@ -235,7 +245,7 @@ function spawn(name, cmd, waitFor) {
return new Promise((resolve, reject) => {
log(cmd);
let parts = cmd.split(" ");
let process = child_process.spawn(parts[0], parts.slice(1), { cwd: path.join("temp", "test") });
let process = child_process.spawn(parts[0], parts.slice(1), { cwd: path.join("temp", "test"), ...options });
let stdout = new LineSplitter({ readableObjectMode: true });
let stderr = new LineSplitter({ readableObjectMode: true });
let onDataOut = line => {
@@ -259,8 +269,8 @@ function spawn(name, cmd, waitFor) {
});
}
async function spawnNode(name, cmd, waitFor) {
return await spawn(name, `node --enable-source-maps ${cmd}`, waitFor);
function spawnNode(name, cmd, waitFor, options) {
return spawn(name, `node --enable-source-maps ${cmd}`, waitFor, options);
}
before(async function() {
@@ -388,6 +398,7 @@ module.exports = {
TestControl,
TestControlConnector,
TestHostConnector,
execController,
execCtlProcess,
slowTest,
get,
+30 -11
View File
@@ -2,12 +2,14 @@
const assert = require("assert").strict;
const lib = require("@clusterio/lib");
const { testMatrix } = require("../common");
const {
slowTest, exec, execCtl, execCtlProcess, sendRcon, getControl,
} = require("./index");
const instId = 48;
const instName = "Integration";
const instSetConfig = `instance config set ${instName}`;
const instAltId = 49;
const instAltName = "IntegrationAlt";
@@ -53,7 +55,6 @@ describe("Clusterio Instance", function() {
// Exclude alt test instance from start-all to prevent interference
await execCtl(`instance config set ${instAltName} instance.exclude_from_start_all true`);
await execCtl(`instance start ${instAltName}`);
await sendRcon(instAltId, "/sc disable achievements");
});
after(async function() {
this.timeout(20000);
@@ -62,25 +63,42 @@ describe("Clusterio Instance", function() {
await execCtl(`instance stop ${instAltName}`);
await execCtl(`instance delete ${instAltName}`);
});
for (const savePatchingEnabled of [true, false]) {
describe(`Integration ${savePatchingEnabled ? "with" : "without"} save patching`, function() {
for (const [savePatchingEnabled, scriptCommandsEnabled] of testMatrix([true, false], [true, false])) {
const strSavePatching = `save patching: ${savePatchingEnabled ? "Enabled" : "Disabled"}`;
const strScriptCommands = `script commands: ${scriptCommandsEnabled ? "Enabled" : "Disabled"}`;
async function allowSendingScriptCommands() {
if (!scriptCommandsEnabled) {
// Enable command to prevent "Attempted to use script command when disabled"
// This works because we only disable achievements on startup, this will break if we make it live update
await execCtl(`${instSetConfig} factorio.enable_script_commands true`);
}
}
describe(`Integration - ${strSavePatching}, ${strScriptCommands}`, function() {
before(async function() {
this.timeout(20000);
// Create and start a patched save
await execCtl(`instance config set ${instName} factorio.enable_save_patching ${savePatchingEnabled}`);
await execCtl(`instance save create ${instName} ${savePatchingEnabled ? "patched" : "unpatched"}`);
await execCtl(`instance start ${instName} --save ${savePatchingEnabled ? "patched" : "unpatched"}.zip`);
await sendRcon(instId, "/sc disable achievements");
await execCtl(`${instSetConfig} factorio.enable_save_patching ${savePatchingEnabled}`);
await execCtl(`${instSetConfig} factorio.enable_script_commands ${scriptCommandsEnabled}`);
await execCtl(`instance save create ${instName}`);
await execCtl(`instance start ${instName}`);
});
after(async function() {
// Stop the instance
await execCtl(`instance stop ${instName}`);
});
describe("player event", function() {
describe("Disable achievements", function() {
it("should only disable achievements when script commands are enabled", async function() {
await allowSendingScriptCommands();
const res = await sendRcon(instId, "/sc rcon.print('Disabled')");
assert.equal(res === "Disabled\n", scriptCommandsEnabled);
});
});
describe("Player events", function() {
if (savePatchingEnabled) {
// IPC expects save patching to be enabled
it("should do nothing for an unknown type", async function() {
await assert.rejects(getUser("DoesNotExist"), "User should not exist");
await allowSendingScriptCommands();
await sendRcon(instId,
`/sc ${requireApi} api.send_json("player_event",` +
"{ type='invalid type', name='DoesNotExist' })"
@@ -88,6 +106,7 @@ describe("Clusterio Instance", function() {
await assert.rejects(getUser("DoesNotExist"), "User was created");
});
it("should respond to a player join and leave event", async function() {
await allowSendingScriptCommands();
await sendRcon(instId,
`/sc ${requireApi} api.send_json("player_event",` +
"{ type='join', name='JoiningPlayer' })"
@@ -103,7 +122,7 @@ describe("Clusterio Instance", function() {
});
}
it("should respond to a player ban and unban event", async function() {
await execCtl(`instance config set ${instName} factorio.sync_banlist bidirectional`);
await execCtl(`${instSetConfig} factorio.sync_banlist bidirectional`);
await sendRcon(instId, "/ban BannedPlayer");
await lib.wait(15); // Propagation time, 10ms worked for me, so i made it 15ms
const userBanned = await getUser("BannedPlayer");
@@ -120,7 +139,7 @@ describe("Clusterio Instance", function() {
});
it("should respond to a player promote and demote event", async function() {
// Because there is no admin list command this test will be different to the other two
await execCtl(`instance config set ${instName} factorio.sync_adminlist bidirectional`);
await execCtl(`${instSetConfig} factorio.sync_adminlist bidirectional`);
await sendRcon(instId, "/promote AdminPlayer");
await lib.wait(15); // Propagation time, 10ms worked for me, so i made it 15ms
const userPromote = await getUser("AdminPlayer");
@@ -142,7 +161,7 @@ describe("Clusterio Instance", function() {
);
});
it("should respond to a player whitelist add and remove event", async function() {
await execCtl(`instance config set ${instName} factorio.sync_whitelist bidirectional`);
await execCtl(`${instSetConfig} factorio.sync_whitelist bidirectional`);
await sendRcon(instId, "/whitelist add WhitelistPlayer");
await lib.wait(30); // Propagation time, had issues with 15ms in ci so i made it 30ms
const userAdded = await getUser("WhitelistPlayer");
+133
View File
@@ -0,0 +1,133 @@
/* eslint-disable node/no-sync */
"use strict";
const assert = require("assert").strict;
const fs = require("fs-extra");
const path = require("path");
const { LockFile } = require("@clusterio/lib");
const baseDir = path.join("temp", "test", "lock_file");
describe("class LockFile", function () {
/** @type {string} */
let filePath;
/** @type {LockFile} */
let lock;
before(async function () {
await fs.ensureDir(baseDir);
});
beforeEach(function() {
filePath = path.join(baseDir, `${Date.now()}-${Math.random()}.lock`);
lock = new LockFile(filePath);
});
afterEach(async function () {
await fs.unlink(filePath).catch(() => {});
});
describe("acquire()", function () {
it("should create the lock file when acquiring", async function () {
await lock.acquire();
assert.ok(fs.existsSync(filePath));
});
it("should throw LockFileBusyError if called when not idle", async function () {
await lock.acquire();
await assert.rejects(lock.acquire(), { name: "LockFileBusyError" });
});
it("should remove stale lock file and acquire it", async function () {
await fs.writeFile(filePath, "999999\n"); // stale lock
await lock.acquire();
assert.ok(fs.existsSync(filePath));
});
it("should throw if existing lock file is not stale", async function () {
await fs.writeFile(filePath, `${process.pid}\n`);
await assert.rejects(lock.acquire(), { name: "LockFileExistsError" });
});
});
describe("release()", function () {
it("should remove the lock file when releasing", async function () {
await lock.acquire();
await lock.release();
assert.ok(!fs.existsSync(filePath));
});
it("should throw LockFileBusyError if called when not acquired", async function () {
await assert.rejects(lock.release(), { name: "LockFileBusyError" });
});
});
describe("isHeld()", function () {
it("should return true only when lock file contains current PID", async function () {
await lock.acquire();
const held = await lock.isHeld();
assert.equal(held, true);
});
it("should return false when lock file does not exist", async function () {
const held = await lock.isHeld();
assert.equal(held, false);
});
it("should return false if lock file contains different PID", async function () {
await fs.writeFile(filePath, "999999\n"); // simulate another process
const held = await lock.isHeld();
assert.equal(held, false);
});
it("should return false if lock file was deleted while held", async function() {
await lock.acquire();
await fs.unlink(filePath);
const held = await lock.isHeld();
assert.equal(held, false);
});
});
describe("isStale()", function () {
it("should return true if lock file does not exist", async function () {
const stale = await lock.isStale();
assert.equal(stale, true);
});
it("should return true for invalid PID in lock file", async function () {
await fs.writeFile(filePath, "abc\n"); // non-numeric PID
const stale = await lock.isStale();
assert.equal(stale, true);
});
it("should return true for non-existent process PID", async function () {
await fs.writeFile(filePath, "999999\n"); // assume PID does not exist
const stale = await lock.isStale();
assert.equal(stale, true);
});
it("should return false for current process PID", async function () {
await fs.writeFile(filePath, `${process.pid}\n`);
const stale = await lock.isStale();
assert.equal(stale, false);
});
});
describe("attach/detach exit handlers", function () {
it("should attach exit handler on acquire and detach on release", async function () {
await lock.acquire();
const listenersBefore = process.listeners("exit").slice();
assert.ok(listenersBefore.includes(lock.handleExitSync));
await lock.release();
const listenersAfter = process.listeners("exit").slice();
assert.ok(!listenersAfter.includes(lock.handleExitSync));
});
});
describe("handleExitSync()", function () {
it("should not throw if file already removed", function () {
assert.doesNotThrow(() => lock.handleExitSync()); // simulate non-existent file
});
});
});
+108 -102
View File
@@ -7,7 +7,7 @@ const JSZip = require("jszip"); // Added for creating mock zips
// Capture native fetch before any potential mocks are applied
const nativeFetch = global.fetch;
const { ModStore, ModInfo } = require("@clusterio/lib"); // Adjust path based on compiled output
const { ModStore, ModInfo, ModVersionEquality } = require("@clusterio/lib"); // Adjust path based on compiled output
const MODS_DIR = path.join("temp", "test", "mod_store", "mods");
const CACHE_FILE = path.join(MODS_DIR, "mod-info-cache.json");
@@ -148,7 +148,7 @@ describe("lib/ModStore", function () {
assert.equal(modInfo.name, modName);
assert.equal(modInfo.version, modVersion);
// Check if the dependency was updated (indicating re-read)
assert(modInfo.dependencies.includes("? updated-dep"));
assert(modInfo.dependencySpecifications.includes("? updated-dep"));
});
it("should handle corrupted zip files gracefully", async function () {
@@ -271,7 +271,7 @@ describe("lib/ModStore", function () {
});
// Helper to create the mock fetch function for the Factorio Mod Portal API
function createMockPortalApiFetch(modsToDownloadMap, fetchCallsArray = null) {
function createMockPortalApiFetch(modsToDownload, fetchCallsArray = null) {
return async (url, options) => {
const urlString = url.toString();
if (fetchCallsArray) {
@@ -285,11 +285,12 @@ describe("lib/ModStore", function () {
requestedModNames = (body.get("namelist") || "").split(",").filter(Boolean);
}
const results = requestedModNames.map(name => {
const requestedVersion = modsToDownloadMap.get(name);
if (!requestedVersion) {
const requestedMod = modsToDownload.find(mod => mod.name === name);
if (!requestedMod) {
// Use assert or throw for clearer test failure messages
assert.fail(`[Test Mock ERROR] Mock fetch received unexpected mod name: ${name}`);
}
const requestedVersion = requestedMod.version.version;
return {
name: name,
latest_release: {
@@ -309,7 +310,7 @@ describe("lib/ModStore", function () {
}
it("should download and add a single mod", async function () {
const modsToDownload = new Map([["download-mod-1", "1.1.0"]]);
const modsToDownload = [{ name: "download-mod-1", version: ModVersionEquality.fromString("1.1.0") }];
// Define fetch mock specific to this test
global.fetch = createMockPortalApiFetch(modsToDownload);
@@ -327,10 +328,10 @@ describe("lib/ModStore", function () {
});
it("should download multiple mods", async function () {
const modsToDownload = new Map([
["multi-mod-a", "1.0.0"],
["multi-mod-b", "2.0.0"],
]);
const modsToDownload = [
{ name: "multi-mod-a", version: ModVersionEquality.fromString("1.0.0") },
{ name: "multi-mod-b", version: ModVersionEquality.fromString("2.0.0") },
];
// Define fetch mock specific to this test
global.fetch = createMockPortalApiFetch(modsToDownload);
@@ -343,43 +344,34 @@ describe("lib/ModStore", function () {
assert(await fs.pathExists(path.join(MODS_DIR, "multi-mod-a_1.0.0.zip")));
assert(await fs.pathExists(path.join(MODS_DIR, "multi-mod-b_2.0.0.zip")));
});
it("should throw when no releases available", async function () {
const modsToDownload = [{ name: "download-mod-1", version: ModVersionEquality.fromString("1.1.0") }];
it("should skip already downloaded mods", async function () {
const existingModName = "existing-mod";
const existingModVersion = "1.0.0";
const existingFilename = `${existingModName}_${existingModVersion}.zip`;
await createMockModZip(path.join(MODS_DIR, existingFilename), existingModName, existingModVersion);
modStore = await ModStore.fromDirectory(MODS_DIR);
assert.equal(modStore.files.size, 1);
// Define fetch mock specific to this test
global.fetch = async (url, options) => {
const urlString = url.toString();
if (urlString.startsWith("https://mods.factorio.com/api/mods") && options?.method === "POST") {
const body = options.body;
let requestedModNames = [];
if (body instanceof URLSearchParams) {
requestedModNames = (body.get("namelist") || "").split(",").filter(Boolean);
}
const results = requestedModNames.map(name => ({ name: name }));
return { ok: true, status: 200, json: async () => ({ results: results, pagination: {} }) };
}
// Fallback for unhandled fetches in this test
return { ok: false, status: 404, statusText: `Test Mock 404: ${urlString}` };
};
const modsToDownload = new Map([
[existingModName, existingModVersion], // Already present
["new-mod", "0.5.0"], // New mod
]);
let fetchCalls = [];
// Define fetch mock specific to this test (wraps original for tracking)
global.fetch = createMockPortalApiFetch(modsToDownload, fetchCalls);
await modStore.downloadMods(modsToDownload, username, token, factorioVersion);
assert.equal(modStore.files.size, 2, "Should have 2 mods total");
assert(modStore.files.has(existingFilename));
assert(modStore.files.has("new-mod_0.5.0.zip"));
assert(await fs.pathExists(path.join(MODS_DIR, "new-mod_0.5.0.zip")));
const postCall = fetchCalls.find(call => call.options?.method === "POST");
assert(postCall, "POST call to API should have happened");
const requestedMods = (postCall.options.body.get("namelist") || "").split(",");
assert.deepEqual(requestedMods, ["new-mod"], "Only new-mod should be in the namelist");
await assert.rejects(modStore.downloadMods(modsToDownload, username, token, factorioVersion));
});
it("should skip built-in mods", async function () {
const modsToDownload = new Map([
["base", "1.1.0"], // Built-in
["core", "1.1.0"], // Built-in
["another-new-mod", "1.0.0"], // Not built-in
]);
const modsToDownload = [
{ name: "base", version: ModVersionEquality.fromString("1.1.0") }, // Built-in
{ name: "core", version: ModVersionEquality.fromString("1.1.0") }, // Built-in
{ name: "another-new-mod", version: ModVersionEquality.fromString("1.0.0") }, // Not built-in
];
let fetchCalls = [];
// Define fetch mock specific to this test
@@ -396,51 +388,8 @@ describe("lib/ModStore", function () {
assert.deepEqual(requestedMods, ["another-new-mod"], "Only non-builtin mod should be in the namelist");
});
it("should handle Factorio version formatting (e.g., 1.1.100 -> 1.1)", async function () {
const modsToDownload = new Map([["version-test-mod", "1.0.0"]]);
let capturedApiUrl = null;
// Define fetch mock specific to this test
const testFetch = async (url, options) => {
const urlString = url.toString();
if (urlString.startsWith("https://mods.factorio.com/api/mods") && options?.method === "POST") {
capturedApiUrl = urlString; // Capture URL
const body = options.body;
let requestedModNames = [];
if (body instanceof URLSearchParams) {
requestedModNames = (body.get("namelist") || "").split(",").filter(Boolean);
}
const results = requestedModNames.map(name => {
const requestedVersion = modsToDownload.get(name);
if (!requestedVersion) {
throw new Error(`[Test Mock ERROR] No version for ${name}`);
}
return {
name: name,
latest_release: {
download_url: `/download/${name}/${requestedVersion}`,
file_name: `${name}_${requestedVersion}.zip`,
info_json: { factorio_version: factorioVersion },
version: requestedVersion,
sha1: `sha1_${name}_${requestedVersion}`,
},
};
});
return { ok: true, status: 200, json: async () => ({ results: results, pagination: {} }) };
}
return { ok: false, status: 404, statusText: `Test Mock 404: ${urlString}` };
};
global.fetch = testFetch;
await modStore.downloadMods(modsToDownload, username, token, "1.1.100"); // Use full version
assert(capturedApiUrl, "Fetch to API mods should have been called");
const apiUrlParams = new URL(capturedApiUrl).searchParams;
assert.equal(apiUrlParams.get("version"), "1.1", "Factorio version should be truncated in API call");
});
it("should handle API error during mod info fetch", async function () {
const modsToDownload = new Map([["api-error-mod", "1.0.0"]]);
const modsToDownload = [{ name: "api-error-mod", version: ModVersionEquality.fromString("1.0.0") }];
// Define fetch mock specific to this test (simulates API error)
global.fetch = async (url, options) => {
@@ -463,11 +412,11 @@ describe("lib/ModStore", function () {
});
it("should handle download error for a specific mod", async function () {
const modsToDownload = new Map([
["good-mod", "1.0.0"], // This one should succeed
["bad-download-mod", "1.0.0"], // This one will fail
["another-good-mod", "1.0.0"], // This one should also succeed
]);
const modsToDownload = [
{ name: "good-mod", version: ModVersionEquality.fromString("1.0.0") }, // Success
{ name: "bad-download-mod", version: ModVersionEquality.fromString("1.0.0") }, // Fail
{ name: "another-good-mod", version: ModVersionEquality.fromString("1.0.0") }, // Success
];
// Mock ModStore.downloadFile to fail for the specific mod
const originalDSF = ModStore.downloadFile;
@@ -496,10 +445,11 @@ describe("lib/ModStore", function () {
requestedModNames = (body.get("namelist") || "").split(",").filter(Boolean);
}
const results = requestedModNames.map(name => {
const requestedVersion = modsToDownload.get(name);
if (!requestedVersion) {
const requestedMod = modsToDownload.find(mod => mod.name === name);
if (!requestedMod) {
throw new Error(`[Test Mock ERROR] No version for ${name}`);
}
const requestedVersion = requestedMod.version.version;
return {
name: name,
latest_release: {
@@ -526,12 +476,12 @@ describe("lib/ModStore", function () {
});
it("should download mods in chunks", async function () {
const modsToDownload = new Map([
["chunk-mod-1", "1.0.0"],
["chunk-mod-2", "1.0.0"],
["chunk-mod-3", "1.0.0"],
["chunk-mod-4", "1.0.0"],
]);
const modsToDownload = [
{ name: "chunk-mod-1", version: ModVersionEquality.fromString("1.0.0") },
{ name: "chunk-mod-2", version: ModVersionEquality.fromString("1.0.0") },
{ name: "chunk-mod-3", version: ModVersionEquality.fromString("1.0.0") },
{ name: "chunk-mod-4", version: ModVersionEquality.fromString("1.0.0") },
];
let postCalls = 0;
// Define fetch mock specific to this test
@@ -545,10 +495,11 @@ describe("lib/ModStore", function () {
requestedModNames = (body.get("namelist") || "").split(",").filter(Boolean);
}
const results = requestedModNames.map(name => {
const requestedVersion = modsToDownload.get(name);
if (!requestedVersion) {
const requestedMod = modsToDownload.find(mod => mod.name === name);
if (!requestedMod) {
throw new Error(`[Test Mock ERROR] No version for ${name}`);
}
const requestedVersion = requestedMod.version.version;
return {
name: name,
latest_release: {
@@ -570,7 +521,7 @@ describe("lib/ModStore", function () {
// Assuming chunkSize is 500, 4 mods should be 1 chunk/POST call
assert.equal(postCalls, 1, "Should make 1 POST call for 4 mods");
assert.equal(modStore.files.size, modsToDownload.size, "All chunked mods should be downloaded");
assert.equal(modStore.files.size, modsToDownload.length, "All chunked mods should be downloaded");
assert(modStore.files.has("chunk-mod-1_1.0.0.zip"));
assert(modStore.files.has("chunk-mod-4_1.0.0.zip"));
});
@@ -843,6 +794,40 @@ describe("lib/ModStore", function () {
});
});
describe("fetchModReleases (static)", function() {
// Keep track of the original fetch for the live test
let originalFetch;
before(function() {
originalFetch = global.fetch;
});
after(function() {
global.fetch = originalFetch; // Restore original fetch after this suite
});
it("should fetch from the correct api url (mock)", async function() {
global.fetch = async function(url) {
assert.equal(url, "https://mods.factorio.com/api/mods/my-mod/full");
return { ok: true, status: 200, json: async () => ({ name: "my-mod" }) };
};
const result = await ModStore.fetchModReleases("my-mod");
assert.equal(result.name, "my-mod");
});
it("should throw an error when the fetch fails (mock)", async function() {
global.fetch = async function(url) {
assert.equal(url, "https://mods.factorio.com/api/mods/my-mod/full");
return { ok: false, status: 400, json: async () => ({ name: "my-mod" }) };
};
await assert.rejects(ModStore.fetchModReleases("my-mod"));
});
it("should fetch from the correct api url (live)", async function() {
global.fetch = nativeFetch;
const result = await ModStore.fetchModReleases("clusterio_lib");
assert(result.releases && result.releases.length > 1, "Failed to fetch releases");
});
});
// === Instance Methods ===
describe("Instance Methods", function () {
let modStore;
@@ -1004,5 +989,26 @@ describe("lib/ModStore", function () {
assert.equal(eventModInfo, modInfo, "Event should pass the added ModInfo");
});
});
describe("filterInstalled", function() {
it("should filter out installed mods", function() {
const mods = [
{ name: testMod1Name, version: ModVersionEquality.fromString(testMod1Version) },
{ name: "not-installed", version: ModVersionEquality.fromString("1.0.0") },
];
assert.deepEqual(modStore.filterInstalled(mods, false), [
{ name: "not-installed", version: ModVersionEquality.fromString("1.0.0") },
]);
});
it("should filter out uninstalled mods", function() {
const mods = [
{ name: testMod1Name, version: ModVersionEquality.fromString(testMod1Version) },
{ name: "not-installed", version: ModVersionEquality.fromString("1.0.0") },
];
assert.deepEqual(modStore.filterInstalled(mods, true), [
{ name: testMod1Name, version: ModVersionEquality.fromString(testMod1Version) },
]);
});
});
});
});
+127
View File
@@ -0,0 +1,127 @@
const assert = require("assert").strict;
const { ValueCache, wait } = require("@clusterio/lib");
describe("ValueCache", function () {
describe("constructor", function () {
it("constructs with a fetch function", function() {
const fetcher = async () => 42;
const cache = new ValueCache(fetcher);
assert.ok(cache);
});
});
describe("get", function() {
it("throws TypeError for negative maxAgeMs", async function() {
const fetcher = async () => 42;
const cache = new ValueCache(fetcher);
assert.throws(() => cache.get(-1), err => {
assert.equal(err instanceof TypeError, true);
assert.match(String(err.message), /maxAgeMs/);
return true;
});
});
it("uses a default of 0 for maxAgeMs", async function() {
let callCount = 0;
const fetcher = async () => {
callCount += 1;
return callCount;
};
const cache = new ValueCache(fetcher);
const v1 = await cache.get();
const v2 = await cache.get();
assert.equal(v1, 1);
assert.equal(v2, 2);
assert.equal(callCount, 2);
});
it("returns cached value when within maxAgeMs", async function() {
let callCount = 0;
const fetcher = async () => {
callCount += 1;
return callCount;
};
const cache = new ValueCache(fetcher);
const v1 = await cache.get(1000);
const v2 = await cache.get(1000);
assert.equal(v1, 1);
assert.equal(v2, 1);
assert.equal(callCount, 1);
});
it("refreshes the cache when older than maxAgeMs", async function() {
let callCount = 0;
const fetcher = async () => {
callCount += 1;
return callCount;
};
const cache = new ValueCache(fetcher);
const v1 = await cache.get(50);
const v2 = await cache.get(1000); // Use cached value
await wait(100);
const v3 = await cache.get(50); // Stale after 100ms wait
const v4 = await cache.get(1000); // Use cached value
assert.equal(v1, 1);
assert.equal(v2, 1);
assert.equal(v3, 2);
assert.equal(v4, 2);
assert.equal(callCount, 2);
});
it("shares in-flight fetch between concurrent callers", async function() {
let callCount = 0;
let resolveFetcher;
const fetcher = () => (
new Promise(resolve => {
callCount += 1;
resolveFetcher = resolve;
})
);
const cache = new ValueCache(fetcher);
const p1 = cache.get(1000);
const p2 = cache.get(1000);
assert.equal(callCount, 1);
resolveFetcher(42);
const [v1, v2] = await Promise.all([p1, p2]);
assert.equal(v1, 42);
assert.equal(v2, 42);
assert.equal(callCount, 1);
});
it("propagates errors from the fetcher and clears ongoing fetch", async function() {
let callCount = 0;
const error = new Error("fetch failed");
const fetcher = async () => {
callCount += 1;
throw error;
};
const cache = new ValueCache(fetcher);
await assert.rejects(cache.get(), err => {
assert.equal(err, error);
return true;
});
assert.equal(callCount, 1);
// After a failure, a new attempt to fetch should be made
await assert.rejects(cache.get(), err => {
assert.equal(err, error);
return true;
});
assert.equal(callCount, 2);
});
});
});
+245 -2
View File
@@ -5,10 +5,226 @@ const path = require("path");
const lib = require("@clusterio/lib");
const libBuildMod = require("@clusterio/lib/build_mod");
const { ModInfo } = lib;
const { ModInfo, ModDependency } = lib;
const { testMatrix, testRoundTripJsonSerialisable } = require("../../common");
describe("lib/data/ModInfo", function() {
describe("class ModDependency", function() {
describe(".getTypeFromPrefix()", function() {
it("should not throw for valid prefixes", function() {
assert.equal(ModDependency.getTypeFromPrefix("!"), "incompatible");
assert.equal(ModDependency.getTypeFromPrefix("?"), "optional");
assert.equal(ModDependency.getTypeFromPrefix("(?)"), "hidden");
assert.equal(ModDependency.getTypeFromPrefix("~"), "unordered");
assert.equal(ModDependency.getTypeFromPrefix(""), "required");
});
it("should throw for unknown prefixes", function() {
assert.throws(() => ModDependency.getTypeFromPrefix("invalid"));
});
});
describe("constructor", function() {
it("should accept specifications of name only", function() {
const dependency = new ModDependency("my-mod");
assert.equal(dependency.name, "my-mod");
assert.equal(dependency.type, "required");
assert.equal(dependency.version, undefined);
});
it("should accept specifications of name and prefix", function() {
const dependency = new ModDependency("? my-mod");
assert.equal(dependency.name, "my-mod");
assert.equal(dependency.type, "optional");
assert.equal(dependency.version, undefined);
});
it("should accept specifications of name and version", function() {
const dependency = new ModDependency("my-mod >= 1.2.3");
assert.equal(dependency.name, "my-mod");
assert.equal(dependency.type, "required");
assert.notEqual(dependency.version, undefined);
assert.equal(dependency.version.equality, ">=");
assert.equal(dependency.version.integerVersion, lib.integerFullVersion("1.2.3"));
});
it("should accept specifications of name, prefix and version", function() {
const dependency = new ModDependency("? my-mod >= 1.2.3");
assert.equal(dependency.name, "my-mod");
assert.equal(dependency.type, "optional");
assert.notEqual(dependency.version, undefined);
assert.equal(dependency.version.equality, ">=");
assert.equal(dependency.version.integerVersion, lib.integerFullVersion("1.2.3"));
});
it("should throw if no version equality is given", function() {
assert.throws(() => new ModDependency("my-mod 1.2.3"));
assert.throws(() => new ModDependency("? my-mod 1.2.3"));
});
it("should throw if invalid specification given", function() {
assert.throws(() => new ModDependency("? ? my-mod = 1.2.3"));
});
it("should throw if name contains spaces", function() {
// Apparently there are some legacy mods which include spaces
// Such as https://mods.factorio.com/mod/Explosive%20Excavation
this.skip();
assert.throws(() => new ModDependency("my mod"));
assert.throws(() => new ModDependency("? my mod"));
assert.throws(() => new ModDependency("? my mod >= 1.2.3"));
});
it("should not error when the name contains spaces", function() {
const dependencyReq = new ModDependency("my mod");
assert.equal(dependencyReq.name, "my mod");
assert.equal(dependencyReq.type, "required");
const dependencyOpt = new ModDependency("? my mod");
assert.equal(dependencyOpt.name, "my mod");
assert.equal(dependencyOpt.type, "optional");
const dependencyVer = new ModDependency("my mod >= 1.2.3");
assert.equal(dependencyVer.name, "my mod");
assert.equal(dependencyVer.type, "required");
assert.equal(dependencyVer.version.version, "1.2.3");
const dependencyOptVer = new ModDependency("? my mod >= 1.2.3");
assert.equal(dependencyOptVer.name, "my mod");
assert.equal(dependencyOptVer.type, "optional");
assert.equal(dependencyOptVer.version.version, "1.2.3");
});
it("should be round trip json serialisable", function() {
testRoundTripJsonSerialisable(ModDependency, testMatrix(
["my-mod", "? my-mod", "! my-mod", "my-mod > 1.0.0", "~ my-mod <= 2.0.0"], // Specification
));
});
});
describe("checkUnsatisfiedReason()", function() {
const mods = [
ModInfo.fromJSON({ name: "my-mod", version: "1.0.0" }),
];
it("should be undefined for incompatible being missing", function() {
const dependency = new ModDependency("! not-present");
assert.equal(dependency.checkUnsatisfiedReason(mods), undefined);
});
it("should give reason for incompatible being present", function() {
const dependency = new ModDependency("! my-mod");
assert.equal(dependency.checkUnsatisfiedReason(mods), "incompatible");
});
it("should undefined for optional / hidden being missing", function() {
const dependencyOptional = new ModDependency("? not-present");
assert.equal(dependencyOptional.checkUnsatisfiedReason(mods), undefined);
const dependencyHidden = new ModDependency("(?) not-present");
assert.equal(dependencyHidden.checkUnsatisfiedReason(mods), undefined);
});
it("should undefined for optional / hidden being present", function() {
const dependencyOptional = new ModDependency("? my-mod");
assert.equal(dependencyOptional.checkUnsatisfiedReason(mods), undefined);
const dependencyHidden = new ModDependency("(?) my-mod");
assert.equal(dependencyHidden.checkUnsatisfiedReason(mods), undefined);
});
it("should give reason for optional / hidden being present but wrong version", function() {
const dependencyOptional = new ModDependency("? my-mod > 2.0.0");
assert.equal(dependencyOptional.checkUnsatisfiedReason(mods), "wrong_version");
const dependencyHidden = new ModDependency("(?) my-mod > 2.0.0");
assert.equal(dependencyHidden.checkUnsatisfiedReason(mods), "wrong_version");
});
it("should undefined for unordered / required being present", function() {
const dependencyOptional = new ModDependency("~ my-mod");
assert.equal(dependencyOptional.checkUnsatisfiedReason(mods), undefined);
const dependencyHidden = new ModDependency("my-mod");
assert.equal(dependencyHidden.checkUnsatisfiedReason(mods), undefined);
});
it("should give reason for unordered / required being present but wrong version", function() {
const dependencyOptional = new ModDependency("~ my-mod > 2.0.0");
assert.equal(dependencyOptional.checkUnsatisfiedReason(mods), "wrong_version");
const dependencyHidden = new ModDependency("my-mod > 2.0.0");
assert.equal(dependencyHidden.checkUnsatisfiedReason(mods), "wrong_version");
});
it("should give reason for unordered / required being missing", function() {
const dependencyOptional = new ModDependency("~ not-present");
assert.equal(dependencyOptional.checkUnsatisfiedReason(mods), "missing_dependency");
const dependencyHidden = new ModDependency("not-present");
assert.equal(dependencyHidden.checkUnsatisfiedReason(mods), "missing_dependency");
});
});
describe("isSatisfied()", function() {
const mods = [
ModInfo.fromJSON({ name: "my-mod", version: "1.0.0" }),
];
it("should pass for incompatible being missing", function() {
const dependency = new ModDependency("! not-present");
assert.equal(dependency.isSatisfied(mods), true);
});
it("should fail for incompatible being present", function() {
const dependency = new ModDependency("! my-mod");
assert.equal(dependency.isSatisfied(mods), false);
});
it("should pass for optional / hidden being missing", function() {
const dependencyOptional = new ModDependency("? not-present");
assert.equal(dependencyOptional.isSatisfied(mods), true);
const dependencyHidden = new ModDependency("(?) not-present");
assert.equal(dependencyHidden.isSatisfied(mods), true);
});
it("should pass for optional / hidden being present", function() {
const dependencyOptional = new ModDependency("? my-mod");
assert.equal(dependencyOptional.isSatisfied(mods), true);
const dependencyHidden = new ModDependency("(?) my-mod");
assert.equal(dependencyHidden.isSatisfied(mods), true);
});
it("should fail for optional / hidden being present but wrong version", function() {
const dependencyOptional = new ModDependency("? my-mod > 2.0.0");
assert.equal(dependencyOptional.isSatisfied(mods), false);
const dependencyHidden = new ModDependency("(?) my-mod > 2.0.0");
assert.equal(dependencyHidden.isSatisfied(mods), false);
});
it("should pass for unordered / required being present", function() {
const dependencyOptional = new ModDependency("~ my-mod");
assert.equal(dependencyOptional.isSatisfied(mods), true);
const dependencyHidden = new ModDependency("my-mod");
assert.equal(dependencyHidden.isSatisfied(mods), true);
});
it("should fail for unordered / required being present but wrong version", function() {
const dependencyOptional = new ModDependency("~ my-mod > 2.0.0");
assert.equal(dependencyOptional.isSatisfied(mods), false);
const dependencyHidden = new ModDependency("my-mod > 2.0.0");
assert.equal(dependencyHidden.isSatisfied(mods), false);
});
it("should fail for unordered / required being missing", function() {
const dependencyOptional = new ModDependency("~ not-present");
assert.equal(dependencyOptional.isSatisfied(mods), false);
const dependencyHidden = new ModDependency("not-present");
assert.equal(dependencyHidden.isSatisfied(mods), false);
});
});
describe("incompatible", function() {
it("should return true iff the type is incompatible", function() {
const dependencyIncompatible = new ModDependency("! my-mod");
assert.equal(dependencyIncompatible.incompatible, true);
for (const test of ["my-mod", "? my-mod", "(?) my-mod", "~ my-mod"]) {
const dependency = new ModDependency(test);
assert.equal(dependency.incompatible, false, test);
}
});
});
describe("required", function() {
it("should return true iff the dependency is required", function() {
for (const test of ["my-mod", "~ my-mod"]) {
const dependency = new ModDependency(test);
assert.equal(dependency.required, true, test);
}
for (const test of ["! my-mod", "? my-mod", "(?) my-mod"]) {
const dependency = new ModDependency(test);
assert.equal(dependency.required, false, test);
}
});
});
describe("optional", function() {
it("should return true iff the dependency is optional", function() {
for (const test of ["? my-mod", "(?) my-mod"]) {
const dependency = new ModDependency(test);
assert.equal(dependency.optional, true, test);
}
for (const test of ["! my-mod", "my-mod", "~ my-mod"]) {
const dependency = new ModDependency(test);
assert.equal(dependency.optional, false, test);
}
});
});
});
describe("class ModInfo", function() {
it("should round trip serialize", function() {
const validate = lib.compile(ModInfo.jsonSchema);
@@ -70,7 +286,16 @@ describe("lib/data/ModInfo", function() {
factorioMods.sort((a, b) => a.integerFactorioVersion - b.integerFactorioVersion);
assert.deepEqual(factorioMods.map(mod => mod.factorioVersion), sortedVersions);
});
it("should provide the original string specifications for dependencies", function() {
const mod = ModInfo.fromJSON({ dependencies: ["UltraMod", "SuperLib >= 1.00", "! bad-mod"] });
assert.deepEqual(mod.dependencySpecifications, ["UltraMod", "SuperLib >= 1.00", "! bad-mod"]);
});
it("should parse the provided dependency specifications", function() {
const mod = ModInfo.fromJSON({ dependencies: ["UltraMod", "SuperLib >= 1.00", "! bad-mod"] });
assert.deepEqual(mod.dependencies,
["UltraMod", "SuperLib >= 1.00", "! bad-mod"].map(dep => new ModDependency(dep))
);
});
it("should load from a mod zip file", async function() {
await libBuildMod.build({
build: true,
@@ -100,5 +325,23 @@ describe("lib/data/ModInfo", function() {
})
);
});
describe("checkDependencySatisfaction()", function() {
it("should return undefined when satisfied", function() {
const mod = ModInfo.fromJSON({ dependencies: ["! a", "b = 1.0.0", "? c = 2.0.0"] });
assert.equal(mod.checkDependencySatisfaction([{ name: "b", version: "1.0.0" }]), undefined);
});
it("should return incompatible when there is an incompatibility", function() {
const mod = ModInfo.fromJSON({ dependencies: ["! a", "b = 1.0.0", "? c = 2.0.0"] });
assert.equal(mod.checkDependencySatisfaction([{ name: "a", version: "1.0.0" }]), "incompatible");
});
it("should return missing dependency when missing but no incompatibly", function() {
const mod = ModInfo.fromJSON({ dependencies: ["! a", "b = 1.0.0", "? c = 2.0.0"] });
assert.equal(mod.checkDependencySatisfaction([{ name: "c", version: "1.0.0" }]), "missing_dependency");
});
it("should return wrong version when wrong but not missing or incompatible", function() {
const mod = ModInfo.fromJSON({ dependencies: ["! a", "b = 1.0.0", "? c = 2.0.0"] });
assert.equal(mod.checkDependencySatisfaction([{ name: "b", version: "2.0.0" }]), "wrong_version");
});
});
});
});
+5 -5
View File
@@ -397,16 +397,16 @@ describe("lib/data/ModPack", function() {
it("should work with versions before 2.0", function() {
const builtinMods = ModPack.getBuiltinMods("1.1");
assert.deepEqual(builtinMods, [
{ name: "base", enabled: true, version: "1.1" },
{ name: "base", enabled: true, version: "1.1.0" },
]);
});
it("should work with versions after 2.0", function() {
const builtinMods = ModPack.getBuiltinMods("2.0");
assert.deepEqual(builtinMods, [
{ name: "base", enabled: true, version: "2.0" },
{ name: "elevated-rails", enabled: false, version: "2.0" },
{ name: "quality", enabled: false, version: "2.0" },
{ name: "space-age", enabled: false, version: "2.0" },
{ name: "base", enabled: true, version: "2.0.0" },
{ name: "elevated-rails", enabled: false, version: "2.0.0" },
{ name: "quality", enabled: false, version: "2.0.0" },
{ name: "space-age", enabled: false, version: "2.0.0" },
]);
});
});
+515
View File
@@ -0,0 +1,515 @@
"use strict";
const assert = require("assert").strict;
const lib = require("@clusterio/lib");
const { testMatrix, testRoundTripJsonSerialisable } = require("../../common");
describe("lib/data/version", function() {
describe("isVersionEquality()", function() {
it("should correctly validate input strings", function() {
const valid = ["<", "<=", "=", ">=", ">"];
for (const test of valid) {
assert.equal(lib.isVersionEquality(test), true, test);
}
const invalid = ["==", "!=", "<>", ""];
for (const test of invalid) {
assert.equal(lib.isVersionEquality(test), false, test);
}
});
});
describe("isApiVersion()", function() {
it("should correctly validate input strings", function() {
const valid = ["0.13", "0.14", "0.15", "0.16", "0.17", "0.18", "1.0", "1.1", "2.0"];
for (const test of valid) {
assert.equal(lib.isApiVersion(test), true, test);
}
const invalid = ["0.12", "0.19", "1.2", "2.1", "1.0.0", "1.0.0.0", "0", "", "latest"];
for (const test of invalid) {
assert.equal(lib.isApiVersion(test), false, test);
}
});
});
describe("normaliseApiVersion()", function() {
it("should normalise accepted versions", function() {
assert.equal(lib.normaliseApiVersion("0.13"), "0.13");
assert.equal(lib.normaliseApiVersion("0.13.0"), "0.13");
assert.equal(lib.normaliseApiVersion("0.13.1"), "0.13");
assert.equal(lib.normaliseApiVersion("1.1"), "1.1");
assert.equal(lib.normaliseApiVersion("1.1.0"), "1.1");
assert.equal(lib.normaliseApiVersion("1.1.1"), "1.1");
assert.equal(lib.normaliseApiVersion("2.0"), "2.0");
assert.equal(lib.normaliseApiVersion("2.0.0"), "2.0");
assert.equal(lib.normaliseApiVersion("2.0.1"), "2.0");
assert.equal(lib.normaliseApiVersion("1.0.0.0"), "1.0");
});
it("should throw for invalid versions", function() {
const invalid = ["0.12", "0", "", "latest"];
for (const test of invalid) {
assert.throws(() => lib.normaliseApiVersion(test), undefined, test);
}
});
});
describe("isFullVersion()", function() {
it("should correctly validate input strings", function() {
const valid = ["0.12.0", "0.13.1", "0.17.99", "00.000.0001", "1.1.110"];
for (const test of valid) {
assert.equal(lib.isFullVersion(test), true, test);
}
const invalid = ["0.12", "0.19", "1.0", "1.0.0.0", "0", "", "latest"];
for (const test of invalid) {
assert.equal(lib.isFullVersion(test), false, test);
}
});
});
describe("integerFullVersion()", function() {
it("should sort versions lexicographically", function() {
let unsortedVersions = ["1.0.0", "1.1.0", "0.1.0", "3.0.0", "1.2.0", "0.3.1", "0.3.3", "2.1.1", "0.0.1"];
let sortedVersions = ["0.0.1", "0.1.0", "0.3.1", "0.3.3", "1.0.0", "1.1.0", "1.2.0", "2.1.1", "3.0.0"];
unsortedVersions.sort((a, b) => lib.integerFullVersion(a) - lib.integerFullVersion(b));
assert.deepEqual(unsortedVersions, sortedVersions);
});
});
describe("normaliseFullVersion()", function() {
it("should normalise accepted versions", function() {
assert.equal(lib.normaliseFullVersion("0.13"), "0.13.0");
assert.equal(lib.normaliseFullVersion("0.13.0"), "0.13.0");
assert.equal(lib.normaliseFullVersion("0.13.1"), "0.13.1");
assert.equal(lib.normaliseFullVersion("1.1"), "1.1.0");
assert.equal(lib.normaliseFullVersion("1.1.0"), "1.1.0");
assert.equal(lib.normaliseFullVersion("1.1.1"), "1.1.1");
assert.equal(lib.normaliseFullVersion("2.0"), "2.0.0");
assert.equal(lib.normaliseFullVersion("2.0.0"), "2.0.0");
assert.equal(lib.normaliseFullVersion("2.0.1"), "2.0.1");
});
});
describe("isPartialVersion()", function() {
it("should correctly validate input strings", function() {
const valid = [
"0.13", "0.14", "0.15", "0.16", "0.17", "0.18", "1.0", "1.1", "2.0",
"0.12.0", "0.13.1", "0.17.99", "00.000.0001", "1.1.110",
];
for (const test of valid) {
assert.equal(lib.isPartialVersion(test), true, test);
}
const invalid = ["1.0.0.0", "0", "", "latest"];
for (const test of invalid) {
assert.equal(lib.isPartialVersion(test), false, test);
}
});
});
describe("integerPartialVersion()", function() {
it("should sort versions lexicographically", function() {
let unsortedVersions = ["1.0", "1.1", "0.1", "3.0", "1.2", "0.3", "2.1"];
let sortedVersions = ["0.1", "0.3", "1.0", "1.1", "1.2", "2.1", "3.0"];
unsortedVersions.sort((a, b) => lib.integerPartialVersion(a) - lib.integerPartialVersion(b));
assert.deepEqual(unsortedVersions, sortedVersions);
});
});
describe("isTargetVersion()", function() {
it("should correctly validate input strings", function() {
const valid = [
"0.13", "0.14", "0.15", "0.16", "0.17", "0.18", "1.0", "1.1", "2.0",
"0.12.0", "0.13.1", "0.17.99", "00.000.0001", "1.1.110", "latest",
];
for (const test of valid) {
assert.equal(lib.isTargetVersion(test), true, test);
}
const invalid = ["1.0.0.0", "0", ""];
for (const test of invalid) {
assert.equal(lib.isTargetVersion(test), false, test);
}
});
});
describe("class ModVersionEquality", function() {
const tests = testMatrix(
["<", "<=", "=", ">=", ">"],
["0.18", "1.0", "1.0.0", "1.1.1"],
);
describe("constructor", function() {
it("should be round trip json serialisable", function() {
testRoundTripJsonSerialisable(lib.ModVersionEquality, tests);
});
it("should be constructible", function() {
for (const [eq, ver] of tests) {
const test = `${eq} ${ver}`;
const version = new lib.ModVersionEquality(eq, ver);
assert.equal(version.equality, eq, test);
assert.equal(version.version, ver, test);
assert.equal(version.integerVersion, lib.integerPartialVersion(ver), test);
}
});
it("should throw when given an invalid equality", function() {
assert.throws(() => new lib.ModVersionEquality("==", "1.0.0"));
});
it("should throw when given an invalid version", function() {
assert.throws(() => new lib.ModVersionEquality("=", "1.0.0.0"));
});
});
describe("testIntegerVersion()", function() {
it("should test for less than", function() {
const version = new lib.ModVersionEquality("<", "0.0.100");
assert.equal(version.testIntegerVersion(90), true);
assert.equal(version.testIntegerVersion(100), false);
assert.equal(version.testIntegerVersion(110), false);
});
it("should test for less than equal", function() {
const version = new lib.ModVersionEquality("<=", "0.0.100");
assert.equal(version.testIntegerVersion(90), true);
assert.equal(version.testIntegerVersion(100), true);
assert.equal(version.testIntegerVersion(110), false);
});
it("should test for equal", function() {
const version = new lib.ModVersionEquality("=", "0.0.100");
assert.equal(version.testIntegerVersion(90), false);
assert.equal(version.testIntegerVersion(100), true);
assert.equal(version.testIntegerVersion(110), false);
});
it("should test for greater than equal", function() {
const version = new lib.ModVersionEquality(">=", "0.0.100");
assert.equal(version.testIntegerVersion(90), false);
assert.equal(version.testIntegerVersion(100), true);
assert.equal(version.testIntegerVersion(110), true);
});
it("should test for greater than", function() {
const version = new lib.ModVersionEquality(">", "0.0.100");
assert.equal(version.testIntegerVersion(90), false);
assert.equal(version.testIntegerVersion(100), false);
assert.equal(version.testIntegerVersion(110), true);
});
it("should throw if the equality is invalid (unreachable)", function() {
const version = new lib.ModVersionEquality(">", "0.0.100");
version.equality = "==";
assert.throws(() => version.testIntegerVersion(100));
});
});
describe("testVersion()", function() {
it("should test for less than", function() {
const version = new lib.ModVersionEquality("<", "1.1.1");
assert.equal(version.testVersion("1.0"), true);
assert.equal(version.testVersion("1.1"), true);
assert.equal(version.testVersion("1.1.1"), false);
assert.equal(version.testVersion("1.1.2"), false);
assert.equal(version.testVersion("1.2"), false);
});
it("should test for less than equal", function() {
const version = new lib.ModVersionEquality("<=", "1.1.1");
assert.equal(version.testVersion("1.0"), true);
assert.equal(version.testVersion("1.1"), true);
assert.equal(version.testVersion("1.1.1"), true);
assert.equal(version.testVersion("1.1.2"), false);
assert.equal(version.testVersion("1.2"), false);
});
it("should test for equal", function() {
const version = new lib.ModVersionEquality("=", "1.1.1");
assert.equal(version.testVersion("1.0"), false);
assert.equal(version.testVersion("1.1"), false);
assert.equal(version.testVersion("1.1.1"), true);
assert.equal(version.testVersion("1.1.2"), false);
assert.equal(version.testVersion("1.2"), false);
});
it("should test for greater than equal", function() {
const version = new lib.ModVersionEquality(">=", "1.1.1");
assert.equal(version.testVersion("1.0"), false);
assert.equal(version.testVersion("1.1"), false);
assert.equal(version.testVersion("1.1.1"), true);
assert.equal(version.testVersion("1.1.2"), true);
assert.equal(version.testVersion("1.2"), true);
});
it("should test for greater than", function() {
const version = new lib.ModVersionEquality(">", "1.1.1");
assert.equal(version.testVersion("1.0"), false);
assert.equal(version.testVersion("1.1"), false);
assert.equal(version.testVersion("1.1.1"), false);
assert.equal(version.testVersion("1.1.2"), true);
assert.equal(version.testVersion("1.2"), true);
});
it("should throw if the equality is invalid (unreachable)", function() {
const version = new lib.ModVersionEquality(">", "1.1.1");
version.equality = "==";
assert.throws(() => version.testInteger("1.0.0"));
});
});
describe("toString()", function() {
it("should be convertible to string", function() {
for (const [eq, ver] of tests) {
const expected = `${eq} ${ver}`;
const version = new lib.ModVersionEquality(eq, ver);
assert.equal(version.toString(), expected);
}
});
});
describe("fromString()", function() {
it("should be constructable from string", function() {
for (const [eq, ver] of tests) {
const test = `${eq} ${ver}`;
const version = lib.ModVersionEquality.fromString(test);
assert.equal(version.equality, eq, test);
assert.equal(version.version, ver, test);
assert.equal(version.integerVersion, lib.integerPartialVersion(ver), test);
}
});
it("should error for invalid equalities", function() {
const equalities = ["==", "!=", "<>", ""];
for (const eq of equalities) {
const test = `${eq} 1.0.0`;
assert.throws(() => lib.ModVersionEquality.fromString(test), undefined, test);
}
});
it("should error for invalid versions", function() {
const versions = ["1.0.0.0", "0", "", "latest"];
for (const ver of versions) {
const test = `= ${ver}`;
assert.throws(() => lib.ModVersionEquality.fromString(test), undefined, test);
}
});
});
describe("fromParts()", function() {
it("should be constructable from parts", function() {
for (const [eq, ver] of tests) {
const test = `${eq} ${ver}`;
const version = lib.ModVersionEquality.fromParts(eq, ver);
assert.equal(version.equality, eq, test);
assert.equal(version.version, ver, test);
assert.equal(version.integerVersion, lib.integerPartialVersion(ver), test);
}
});
it("should error for invalid equalities", function() {
const equalities = ["==", "!=", "<>", ""];
for (const eq of equalities) {
assert.throws(() => lib.ModVersionEquality.fromParts(eq, "1.0.0"), undefined, eq);
}
});
it("should error for invalid versions", function() {
const versions = ["1.0.0.0", "0", "", "latest"];
for (const ver of versions) {
assert.throws(() => lib.ModVersionEquality.fromParts("=", ver), undefined, ver);
}
});
});
});
describe("class ModVersionRange", function() {
describe("constructor", function() {
it("should be constructable", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.minVersion.equality, ">=");
assert.equal(range.minVersion.version, "1.0.0");
assert.equal(range.maxVersion.equality, "<");
assert.equal(range.maxVersion.version, "2.0.0");
});
it("should be default constructable", function() {
const range = new lib.ModVersionRange();
assert.equal(range.minVersion.equality, ">=");
assert.equal(range.minVersion.version, "0.0.0");
assert.equal(range.maxVersion.equality, "<=");
assert.equal(range.maxVersion.version, "65535.65535.65535");
});
it("should throw if invalid equality is given for min version", function() {
assert.throws(() => new lib.ModVersionRange(
new lib.ModVersionEquality("<", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
));
assert.throws(() => new lib.ModVersionRange(
new lib.ModVersionEquality("<=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
));
});
it("should throw if invalid equality is given for max version", function() {
assert.throws(() => new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality(">", "2.0.0"),
));
assert.throws(() => new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality(">=", "2.0.0"),
));
});
});
describe("valid", function() {
it("should be true for valid ranges", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.valid, true);
const defaultRange = new lib.ModVersionRange();
assert.equal(defaultRange.valid, true);
});
it("should be false for invalid ranges", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "2.0.0"),
new lib.ModVersionEquality("<", "1.0.0"),
);
assert.equal(range.valid, false);
const rangeImpossible = new lib.ModVersionRange(
new lib.ModVersionEquality("=", "1.0.0"),
new lib.ModVersionEquality("=", "2.0.0"),
);
assert.equal(rangeImpossible.valid, false);
});
});
describe("invalidate()", function() {
it("should result in the range becoming invalid", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
range.invalidate();
assert.equal(range.valid, false);
const defaultRange = new lib.ModVersionRange();
defaultRange.invalidate();
assert.equal(defaultRange.valid, false);
});
});
describe("testIntegerVersion()", function() {
it("should return true when in range", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "0.0.100"),
new lib.ModVersionEquality("<", "0.0.200"),
);
assert.equal(range.testIntegerVersion(100), true);
assert.equal(range.testIntegerVersion(199), true);
});
it("should return false when out of range", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "0.0.100"),
new lib.ModVersionEquality("<", "0.0.200"),
);
assert.equal(range.testIntegerVersion(99), false);
assert.equal(range.testIntegerVersion(200), false);
});
it("should handle exact matches", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality("=", "0.0.100"),
new lib.ModVersionEquality("=", "0.0.100"),
);
assert.equal(range.testIntegerVersion(99), false);
assert.equal(range.testIntegerVersion(100), true);
assert.equal(range.testIntegerVersion(101), false);
});
});
describe("testVersion()", function() {
it("should return true when in range", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.testVersion("1.0.0"), true);
assert.equal(range.testVersion("1.9.9"), true);
});
it("should return false when out of range", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.testVersion("0.9.9"), false);
assert.equal(range.testVersion("2.0.0"), false);
});
it("should handle exact matches", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality("=", "1.0.0"),
new lib.ModVersionEquality("=", "1.0.0"),
);
assert.equal(range.testVersion("0.9.9"), false);
assert.equal(range.testVersion("1.0.0"), true);
assert.equal(range.testVersion("1.0.1"), false);
});
});
describe("combineVersion()", function() {
it("should handle merge with less than", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.testVersion("1.1"), true);
assert.equal(range.testVersion("1.5"), true);
range.combineVersion(new lib.ModVersionEquality("<", "1.2"));
assert.equal(range.testVersion("1.1"), true);
assert.equal(range.testVersion("1.5"), false);
assert.equal(range.valid, true);
range.combineVersion(new lib.ModVersionEquality("<", "0.5"));
assert.equal(range.valid, false);
});
it("should handle merge with less than equal", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.testVersion("1.2"), true);
assert.equal(range.testVersion("1.5"), true);
range.combineVersion(new lib.ModVersionEquality("<=", "1.2"));
assert.equal(range.testVersion("1.2"), true);
assert.equal(range.testVersion("1.5"), false);
assert.equal(range.valid, true);
range.combineVersion(new lib.ModVersionEquality("<=", "0.5"));
assert.equal(range.valid, false);
});
it("should handle merge with equal", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.testVersion("1.2"), true);
assert.equal(range.testVersion("1.5"), true);
range.combineVersion(new lib.ModVersionEquality("=", "1.2"));
assert.equal(range.testVersion("1.2"), true);
assert.equal(range.testVersion("1.5"), false);
assert.equal(range.valid, true);
range.combineVersion(new lib.ModVersionEquality("=", "0.5"));
assert.equal(range.valid, false);
});
it("should handle merge with greater than equal", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.testVersion("1.1"), true);
assert.equal(range.testVersion("1.5"), true);
range.combineVersion(new lib.ModVersionEquality(">=", "1.2"));
assert.equal(range.testVersion("1.1"), false);
assert.equal(range.testVersion("1.5"), true);
assert.equal(range.valid, true);
range.combineVersion(new lib.ModVersionEquality(">=", "2.5"));
assert.equal(range.valid, false);
});
it("should handle merge with greater than", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
assert.equal(range.testVersion("1.2"), true);
assert.equal(range.testVersion("1.5"), true);
range.combineVersion(new lib.ModVersionEquality(">", "1.2"));
assert.equal(range.testVersion("1.2"), false);
assert.equal(range.testVersion("1.5"), true);
assert.equal(range.valid, true);
range.combineVersion(new lib.ModVersionEquality(">", "2.5"));
assert.equal(range.valid, false);
});
it("should throw if the equality is invalid (unreachable)", function() {
const range = new lib.ModVersionRange(
new lib.ModVersionEquality(">=", "1.0.0"),
new lib.ModVersionEquality("<", "2.0.0"),
);
const version = new lib.ModVersionEquality(">", "1.2");
version.equality = "==";
assert.throws(() => range.combineVersion(version));
});
});
});
});
+134
View File
@@ -0,0 +1,134 @@
const assert = require("assert").strict;
const { readFile } = require("fs-extra");
const { fetchFactorioVersions } = require("@clusterio/lib");
const { slowTest } = require("../../integration");
describe("FactorioVersions", function() {
describe("fetchFactorioVersions", function() {
const originalFetch = global.fetch;
beforeEach(() => {
global.fetch = undefined;
});
afterEach(() => {
global.fetch = originalFetch;
});
function mockFetch(html) {
const mockResponse = {
ok: true,
status: 200,
statusText: "OK",
text: async () => html,
};
global.fetch = async () => mockResponse;
}
it("fetches and parsed versions with stable / experimental flags", async function() {
mockFetch(`
<html>
<body>
<a class="
slot-button-inline
version-button-experimental
" href="/download/archive/2.0.73">
2.0.73
</a>
</body>
<body>
<a class="
slot-button-inline
version-button-stable
" href="/download/archive/2.0.72">
2.0.72
</a>
</body>
</html>
`);
const versions = await fetchFactorioVersions();
assert.deepEqual(versions, [
{
stable: false,
version: "2.0.73",
headlessUrl: "www.factorio.com/get-download/2.0.73/headless/linux64",
},
{
stable: true,
version: "2.0.72",
headlessUrl: "www.factorio.com/get-download/2.0.72/headless/linux64",
},
]);
});
it("deduplicates versions by last occurrence", async function() {
mockFetch(`
<html>
<body>
<a class="
slot-button-inline
version-button-experimental
" href="/download/archive/2.0.73">
2.0.73
</a>
</body>
<body>
<a class="
slot-button-inline
version-button-stable
" href="/download/archive/2.0.73">
2.0.73
</a>
</body>
</html>
`);
const versions = await fetchFactorioVersions();
assert.deepEqual(versions, [
{
stable: true,
version: "2.0.73",
headlessUrl: "www.factorio.com/get-download/2.0.73/headless/linux64",
},
]);
});
it("thorws on HTTP error status", async function() {
const mockResponse = {
ok: false,
status: 500,
statusText: "Server Error",
text: async () => "",
};
global.fetch = async () => mockResponse;
await assert.rejects(fetchFactorioVersions(), /HTTP 500 Server Error/);
});
it("thorws on network error status", async function() {
global.fetch = async () => {
throw new Error("Network Error");
};
await assert.rejects(fetchFactorioVersions(), /Network Error/);
});
it("parses versions from saved html file", async function() {
mockFetch(await readFile("test/file/html/factorio-download-archive.html"));
const versions = await fetchFactorioVersions();
assert.equal(versions.length, 105);
assert.equal(versions.filter(v => v.stable).length, 48);
assert.equal(versions.filter(v => !v.stable).length, 57);
});
it("parses versions from live api", async function() {
slowTest(this);
global.fetch = originalFetch;
const versions = await fetchFactorioVersions();
assert.ok(versions.length >= 105);
assert.ok(versions.filter(v => v.stable).length >= 48);
assert.ok(versions.filter(v => !v.stable).length >= 57);
});
});
});
+4 -3
View File
@@ -5,7 +5,6 @@ const path = require("path");
const lib = require("@clusterio/lib");
const { BaseControllerPlugin } = require("@clusterio/controller");
const { escapeRegExp } = lib;
describe("lib/plugin_loader", function() {
@@ -34,7 +33,10 @@ describe("lib/plugin_loader", function() {
});
it("should ignore missing plugins", async function() {
const result = await lib.loadPluginInfos(new Map([["missing", missingPlugin]]), []);
const result = await lib.loadPluginInfos(new Map([
["missing", path.resolve(missingPlugin)],
["no_index", path.resolve(baseDir)],
]), []);
assert.deepEqual(result, []);
});
it("should load test plugin", async function() {
@@ -46,7 +48,6 @@ describe("lib/plugin_loader", function() {
it("should reject on broken plugin", async function() {
let brokenMessage;
try {
require(path.resolve(brokenPlugin));
} catch (err) {
brokenMessage = err.message;
+21 -5
View File
@@ -347,11 +347,13 @@ describe("lib/subscriptions", function() {
subscriptions.broadcast(new RegisteredEvent(), "foo");
await onceConnectorSend(0);
assert.equal(getLink(0).connector.sentMessages.length, before0 + 1);
assert.equal(getLink(1).connector.sentMessages.length, before1);
subscriptions.broadcast(new RegisteredEvent(), "bar");
await onceConnectorSend(1);
assert.equal(getLink(0).connector.sentMessages.length, before0 + 1);
assert.equal(getLink(1).connector.sentMessages.length, before1 + 1);
const beforeBaz0 = getLink(0).connector.sentMessages.length;
const beforeBaz1 = getLink(1).connector.sentMessages.length;
@@ -371,12 +373,18 @@ describe("lib/subscriptions", function() {
getLink(1), reqBaz, connectorSetupDate[1].dst, connectorSetupDate[1].src
);
const before0 = getLink(0).connector.sentMessages.length;
const before1 = getLink(1).connector.sentMessages.length;
subscriptions.broadcast(new RegisteredEvent(), "foo");
await onceConnectorSend(0);
assertNoEvent(1);
assert.equal(getLink(0).connector.sentMessages.length, before0 + 1);
assert.equal(getLink(1).connector.sentMessages.length, before1);
subscriptions.broadcast(new RegisteredEvent(), "baz");
await Promise.all([onceConnectorSend(0), onceConnectorSend(1)]);
assert.equal(getLink(0).connector.sentMessages.length, before0 + 2);
assert.equal(getLink(1).connector.sentMessages.length, before1 + 1);
});
it("should merge multiple filter subscriptions for the same subscriber", async function() {
@@ -389,14 +397,19 @@ describe("lib/subscriptions", function() {
getLink(0), reqBar, connectorSetupDate[0].dst, connectorSetupDate[0].src
);
const before0 = getLink(0).connector.sentMessages.length;
subscriptions.broadcast(new RegisteredEvent(), "alpha");
await onceConnectorSend(0);
const before = getLink(0).connector.sentMessages.length;
assert.equal(getLink(0).connector.sentMessages.length, before0 + 1);
subscriptions.broadcast(new RegisteredEvent(), "beta");
await onceConnectorSend(0);
assert.equal(getLink(0).connector.sentMessages.length, before0 + 2);
subscriptions.broadcast(new RegisteredEvent(), "gamma");
await new Promise(resolve => setImmediate(resolve));
assert.equal(getLink(0).connector.sentMessages.length, before + 1);
assert.equal(getLink(0).connector.sentMessages.length, before0 + 2);
});
it("should reset to all when subscribing with no filters after having filters", async function() {
@@ -424,12 +437,15 @@ describe("lib/subscriptions", function() {
getLink(0), unsubFoo, connectorSetupDate[0].dst, connectorSetupDate[0].src
);
const before0 = getLink(0).connector.sentMessages.length;
subscriptions.broadcast(new RegisteredEvent(), "foo");
await new Promise(resolve => setImmediate(resolve));
const before = getLink(0).connector.sentMessages.length;
assert.equal(getLink(0).connector.sentMessages.length, before0);
subscriptions.broadcast(new RegisteredEvent(), "bar");
await onceConnectorSend(0);
assert.equal(getLink(0).connector.sentMessages.length, before + 1);
assert.equal(getLink(0).connector.sentMessages.length, before0 + 1);
});
it("should remove entire subscription when last filter is unsubscribed", async function() {
+40
View File
@@ -34,4 +34,44 @@ describe("messages/controller", function() {
);
});
});
describe("External", function() {
it("runs", async function() {
let callCount = 0;
const versions = [
{ version: "1.2.3", stable: true, headlessUrl: "path/to/download" },
{ version: "1.2.4", stable: false, headlessUrl: "path/to/download" },
];
// Mock the cache to avoid needless fetches
controller.factorioVersions = new lib.ValueCache(async () => {
callCount += 1;
return versions;
});
// First call should result in a fetch
const versions1 = await controlConnection.handleFactorioVersionsRequest(
new lib.FactorioVersionsRequest()
);
assert.deepEqual(versions1, versions);
assert.equal(callCount, 1);
// Second call should not fetch due to default maxAgeMs being greater than 0
const versions2 = await controlConnection.handleFactorioVersionsRequest(
new lib.FactorioVersionsRequest()
);
assert.deepEqual(versions2, versions);
assert.equal(callCount, 1);
// Setting maxAgeMs to 0 should result in a new fetch
const versions3 = await controlConnection.handleFactorioVersionsRequest(
new lib.FactorioVersionsRequest(0)
);
assert.deepEqual(versions3, versions);
assert.equal(callCount, 2);
});
});
});
+462
View File
@@ -0,0 +1,462 @@
"use strict";
const assert = require("assert").strict;
const lib = require("@clusterio/lib");
const { ModDependencyResolveRequest, ModDependency, ModInfo } = lib;
const { testMatrix, testRoundTripJsonSerialisable } = require("../common");
const { Controller, ControlConnection, ControllerUser } = require("@clusterio/controller");
const { slowTest } = require("../integration");
describe("messages/mod", function() {
/** @type {Controller} */
let controller;
/** @type {ControlConnection} */
let controlConnection;
/** @type {Map<string, lib.ModInfo>} */
let ModReleases = new Map();
/**
* @param {string} name
* @param {string} version
* @param {string} factorioVersion
* @param {string[]} dependencies
*/
function setPortalModRelease(name, version, factorioVersion, dependencies) {
ModReleases.set(name, {
name: name,
releases: [{
version: version,
info_json: {
factorio_version: factorioVersion,
dependencies: ["base", ...dependencies],
},
}],
});
}
const _ModStore_fetchModReleases = lib.ModStore.fetchModReleases;
after(function() {
lib.ModStore.fetchModReleases = _ModStore_fetchModReleases;
});
beforeEach(function() {
ModReleases = new Map();
lib.ModStore.fetchModReleases = function(modName) {
const mod = ModReleases.get(modName);
if (mod) {
return mod;
}
throw new Error("Mock 404");
};
const controllerConfig = new lib.ControllerConfig("controller");
const connection = new lib.VirtualConnector(
lib.Address.fromShorthand("controller"),
lib.Address.fromShorthand({ controlId: 1 }),
);
controller = new Controller(lib.logger, [], controllerConfig);
const user = new ControllerUser(controller.userManager, undefined, "test");
controlConnection = new ControlConnection({ version: "2.0.0" }, connection, controller, user, 1);
});
describe("ModDependencyResolveRequest", function() {
describe("static", function() {
const factorioVersions = ["1.0", "1.1", "2.0"];
const tests = testMatrix(
[ // mods
[],
[new ModDependency("foo")],
[new ModDependency("? foo"), new ModDependency("bar > 2.0.5")],
],
factorioVersions, // factorioVersion
[undefined, true, false],
);
it("should be round trip json serialisable", function() {
testRoundTripJsonSerialisable(ModDependencyResolveRequest, tests);
});
it("should be construable", function() {
for (const [mods, factorioVersion, checkForUpdates] of tests) {
const request = new ModDependencyResolveRequest(mods, factorioVersion, checkForUpdates);
assert.equal(request.factorioVersion, factorioVersion);
assert.equal(request.checkForUpdates, checkForUpdates ?? false);
assert.equal(request.mods, mods);
}
});
it("should be constructed from a ModPack", function() {
for (const factorioVersion of factorioVersions) {
const mods = [
{ name: "foo", version: "1.0.0", enabled: true },
{ name: "bar", version: "2.0.0", enabled: false },
];
const modPack = lib.ModPack.fromJSON({ mods: mods, factorio_version: factorioVersion });
const request = ModDependencyResolveRequest.fromModPack(modPack);
assert.equal(request.factorioVersion, factorioVersion, factorioVersion);
assert.equal(request.mods.length, modPack.mods.size, factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "foo"), new ModDependency("foo = 1.0.0"), factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "bar"), new ModDependency("bar = 2.0.0"), factorioVersion);
}
});
it("should be constructed from a ModPack (enabled only)", function() {
for (const factorioVersion of factorioVersions) {
const mods = [
{ name: "foo", version: "1.0.0", enabled: true },
{ name: "bar", version: "2.0.0", enabled: false },
];
const modPack = lib.ModPack.fromJSON({ mods: mods, factorio_version: factorioVersion });
const request = ModDependencyResolveRequest.fromModPackEnabled(modPack);
assert.equal(request.factorioVersion, factorioVersion);
assert.equal(
request.mods.length, [...modPack.mods.values()].filter(m => m.enabled).length, factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "foo"), new ModDependency("foo = 1.0.0"), factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "bar"), undefined, factorioVersion);
}
});
it("should be constructed from a ModPack (check for updates)", function() {
for (const factorioVersion of factorioVersions) {
const mods = [
{ name: "foo", version: "1.0.0", enabled: true },
{ name: "bar", version: "2.0.0", enabled: false },
];
const modPack = lib.ModPack.fromJSON({ mods: mods, factorio_version: factorioVersion });
const request = ModDependencyResolveRequest.fromModPack(modPack, true);
assert.equal(request.factorioVersion, factorioVersion, factorioVersion);
assert.equal(request.mods.length, modPack.mods.size, factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "foo"), new ModDependency("foo >= 1.0.0"), factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "bar"), new ModDependency("bar >= 2.0.0"), factorioVersion);
}
});
it("should be constructed from a ModPack (enabled only) (check for updates)", function() {
for (const factorioVersion of factorioVersions) {
const mods = [
{ name: "foo", version: "1.0.0", enabled: true },
{ name: "bar", version: "2.0.0", enabled: false },
];
const modPack = lib.ModPack.fromJSON({ mods: mods, factorio_version: factorioVersion });
const request = ModDependencyResolveRequest.fromModPackEnabled(modPack, true);
assert.equal(request.factorioVersion, factorioVersion);
assert.equal(
request.mods.length, [...modPack.mods.values()].filter(m => m.enabled).length, factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "foo"), new ModDependency("foo >= 1.0.0"), factorioVersion);
assert.deepEqual(
request.mods.find(m => m.name === "bar"), undefined, factorioVersion);
}
});
});
describe("response", function() {
const tests = testMatrix(
[ // dependencies
[],
[
ModInfo.fromJSON({ name: "foo", version: "1.0.0" }),
],
[
ModInfo.fromJSON({ name: "foo", version: "1.0.0" }),
ModInfo.fromJSON({ name: "bar", version: "2.0.0" }),
],
],
[[], ["foo-i"], ["foo-i", "bar-i"]], // incompatible
[[], ["foo-m"], ["foo-m", "bar-m"]], // missing
);
it("should be round trip json serialisable", function() {
testRoundTripJsonSerialisable(ModDependencyResolveRequest.Response, tests);
});
it("should be construable", function() {
for (const [dependencies, incompatible, missing] of tests) {
const test = JSON.stringify([dependencies, missing, incompatible]);
const request = new ModDependencyResolveRequest.Response(dependencies, incompatible, missing);
assert.deepEqual(request.dependencies, dependencies, test);
assert.deepEqual(request.incompatible, incompatible, test);
assert.deepEqual(request.missing, missing, test);
}
});
});
describe("handle", function() {
const factorioVersions = ["1.0", "1.1", "2.0"];
it("resolves dependencies", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo", "bar < 2.0.0", "? baz"]);
setPortalModRelease("foo", "1.0.0", factorioVersion, ["foo-dep"]);
setPortalModRelease("foo-dep", "1.0.0", factorioVersion, []);
setPortalModRelease("bar", "1.0.0", factorioVersion, []);
setPortalModRelease("baz", "1.0.0", factorioVersion, []);
setPortalModRelease("root-2", "1.0.0", factorioVersion, ["foo", "bar-2"]);
setPortalModRelease("bar-2", "1.0.0", factorioVersion, []);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest(
[new ModDependency("root"), new ModDependency("root-2")],
factorioVersion,
)
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, []);
const expectedIds = [
"root_1.0.0", "foo_1.0.0", "foo-dep_1.0.0", "bar_1.0.0",
"root-2_1.0.0", "bar-2_1.0.0",
];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("highlights dependencies with no suitable version", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["bar < 2.0.0"]);
setPortalModRelease("bar", "2.0.0", factorioVersion, []);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, ["base", "bar"]);
assert.deepEqual(result.incompatible, []);
assert.equal(result.dependencies.length, 1);
assert.equal(result.dependencies[0].id, "root_1.0.0");
}
});
it("highlights dependencies with no releases", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo"]);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, ["base", "foo"]);
assert.deepEqual(result.incompatible, []);
assert.equal(result.dependencies.length, 1);
assert.equal(result.dependencies[0].id, "root_1.0.0");
}
});
it("highlights dependencies which are incompatible", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo", "! foo-dep"]);
setPortalModRelease("foo", "1.0.0", factorioVersion, ["foo-dep"]);
setPortalModRelease("foo-dep", "1.0.0", factorioVersion, []);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, ["foo-dep"]);
const expectedIds = ["root_1.0.0", "foo_1.0.0", "foo-dep_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("highlights dependencies with conflicting versions", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo", "bar"]);
setPortalModRelease("foo", "1.0.0", factorioVersion, ["dep > 2.0.0"]);
setPortalModRelease("bar", "1.0.0", factorioVersion, ["dep < 1.5.0"]);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, ["dep"]);
const expectedIds = ["root_1.0.0", "foo_1.0.0", "bar_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("highlights incompatible builtin mods", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo"]);
setPortalModRelease("foo", "1.0.0", factorioVersion, ["! base"]);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, []);
assert.deepEqual(result.incompatible, ["base"]);
const expectedIds = ["root_1.0.0", "foo_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("does not ignore optional dependencies when required by another", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo", "? baz"]);
setPortalModRelease("foo", "1.0.0", factorioVersion, ["baz"]);
setPortalModRelease("baz", "1.0.0", factorioVersion, []);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, []);
const expectedIds = ["root_1.0.0", "foo_1.0.0", "baz_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("prefers the locally installed version if matching", async function() {
controller.modStore.addMod(lib.ModInfo.fromJSON({ name: "foo", version: "1.0.0" }));
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo"]);
setPortalModRelease("foo", "2.0.0", factorioVersion, []);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, []);
const expectedIds = ["root_1.0.0", "foo_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("prefers the mod portal version when checking for updates", async function() {
controller.modStore.addMod(lib.ModInfo.fromJSON({ name: "foo", version: "1.0.0" }));
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo"]);
setPortalModRelease("foo", "2.0.0", factorioVersion, []);
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion, true)
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, []);
const expectedIds = ["root_1.0.0", "foo_2.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("prefers the latest mod portal version when using the mod portal", async function() {
for (const factorioVersion of factorioVersions) {
setPortalModRelease("root", "1.0.0", factorioVersion, ["foo", "bar < 2.0.0"]);
ModReleases.set("foo", {
name: "foo",
releases: [{
version: "1.0.0", info_json: { factorio_version: factorioVersion, dependencies: [] },
}, {
version: "2.0.0", info_json: { factorio_version: factorioVersion, dependencies: [] },
}],
});
ModReleases.set("bar", {
name: "bar",
releases: [{
version: "1.0.0", info_json: { factorio_version: factorioVersion, dependencies: [] },
}, {
version: "1.5.0", info_json: { factorio_version: factorioVersion, dependencies: [] },
}, {
version: "2.0.0", info_json: { factorio_version: factorioVersion, dependencies: [] },
}],
});
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, []);
const expectedIds = ["root_1.0.0", "foo_2.0.0", "bar_1.5.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length);
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
}
});
it("rejects when a network error occurs", async function() {
lib.ModStore.fetchModReleases = function() {
throw new Error("Mock network error");
};
for (const factorioVersion of factorioVersions) {
await assert.rejects(controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
));
}
});
it("resolves dependencies (live)", async function() {
this.timeout(60000); // Increase timeout to 60 seconds for live API call
lib.ModStore.fetchModReleases = _ModStore_fetchModReleases;
const result = await controlConnection.handleModDependencyResolveRequest(
new lib.ModDependencyResolveRequest([new ModDependency("pymodpack = 3.0.0")], "2.0")
);
assert.deepEqual(result.missing, ["base"]);
assert.deepEqual(result.incompatible, ["space-age"]);
const expectedNames = [ // Can't use ids as the versions may change
"pymodpack", "pypostprocessing", "pyalternativeenergy", "pyalternativeenergygraphics",
"pyalienlife", "pyalienlifegraphics", "pyalienlifegraphics2", "pyalienlifegraphics3",
"pycoalprocessing", "pycoalprocessinggraphics", "pyfusionenergy", "pyfusionenergygraphics",
"pypetroleumhandling", "pypetroleumhandlinggraphics", "pyrawores", "pyraworesgraphics",
"pyhightech", "pyhightechgraphics", "pyindustry", "pyindustrygraphics",
];
const depNames = new Set(result.dependencies.map(mod => mod.name));
assert.equal(depNames.size, expectedNames.length);
for (const modName of expectedNames) {
assert(depNames.has(modName), `Missing ${modName}`);
}
});
});
});
});