Files
muSRFlow/tests/electron-bundled-runtime.test.js
T
salman a6981c494d Fix WSL runtime library paths and plotting dependencies
Pass ROOTSYS, MUSRFITPATH, LD_LIBRARY_PATH and the Linux executable path inside WSL for direct and shell-based launches. Preserve Windows-native tool environments and downloaded-data paths.

Include boost-devel in the WSL runtime and verify ROOT can parse the plotting header during packaging. Document the non-destructive dependency update for already imported runtimes.

Validated the Electron suite, all five bundled executables, shell-based msr2data, a real fit, and PNG generation inside the bundled filesystem.
2026-10-27 21:40:44 +01:00

459 lines
20 KiB
JavaScript

// Copyright (C) 2026 Zaher Salman
// SPDX-License-Identifier: GPL-3.0-or-later
// Bundled ROOT + musrfit runtime resolution. When a relocatable runtime is
// shipped under <resources>/runtime, muSRFlow must discover its bin directory,
// prefer it over the host installation (but still yield to a user-configured
// tools directory), and point ROOTSYS/MUSRFITPATH/LD_LIBRARY_PATH at it when
// spawning musrfit tools. Without the bundle everything falls back to the host.
const assert = require("assert");
const fs = require("fs");
const os = require("os");
const path = require("path");
const vm = require("vm");
const repoRoot = path.resolve(__dirname, "..");
const testRoot = fs.mkdtempSync(path.join(os.tmpdir(), "musrflow-runtime-"));
const emptyCwd = path.join(testRoot, "cwd");
const emptyHome = path.join(testRoot, "home");
fs.mkdirSync(emptyCwd, { recursive: true });
fs.mkdirSync(emptyHome, { recursive: true });
const runtimeRoot = path.join(testRoot, "resources", "runtime");
fs.mkdirSync(path.join(runtimeRoot, "bin"), { recursive: true });
fs.mkdirSync(path.join(runtimeRoot, "lib"), { recursive: true });
fs.writeFileSync(path.join(runtimeRoot, "bin", "musrfit"), "#!/bin/sh\n");
fs.writeFileSync(path.join(runtimeRoot, "bin", "musrt0"), "#!/bin/sh\n");
fs.writeFileSync(path.join(runtimeRoot, "bin", "dump_header"), "#!/bin/sh\n");
fs.writeFileSync(path.join(runtimeRoot, "lib", "libPMusr.so"), "");
fs.writeFileSync(path.join(runtimeRoot, "musrfit_startup.xml"),
"<musrfit>\n<data_path>" + emptyCwd + "</data_path>\n</musrfit>\n");
function localStoreFactory() {
const store = {};
return {
getItem: function(key) {
return Object.prototype.hasOwnProperty.call(store, key) ? store[key] : null;
},
setItem: function(key, value) { store[key] = String(value); },
removeItem: function(key) { delete store[key]; }
};
}
function buildSandbox(resourcesPath, envOverrides, platform) {
const sandbox = {
console: { log: function() {}, error: console.error, warn: console.warn },
document: { getElementById: function() { return null; } },
process: {
cwd: function() { return emptyCwd; },
platform: platform || "linux",
env: Object.assign({ HOME: emptyHome }, envOverrides || {}),
resourcesPath: resourcesPath
},
require: require,
window: {
electronIpcRenderer: { on: function() {}, send: function() {} },
nodeChildProcess: {},
nodeFs: fs,
nodePath: path,
localStorage: localStoreFactory()
}
};
sandbox.global = sandbox;
return sandbox;
}
function loadLibraries(sandbox) {
vm.runInNewContext(
fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"),
sandbox, { filename: "muSRFitlib.js" });
vm.runInNewContext(
fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8"),
sandbox, { filename: "muSRFitelec.js" });
}
const resourcesPath = path.join(testRoot, "resources");
// A runtime installed outside the app (the musrflow-runtime rpm or the portable
// muSRFlow-runtime AppImage, both defaulting to /opt/musrflow/runtime) is used
// when the app ships none. MUSRFLOW_RUNTIME_ROOT overrides the location.
const separateRuntimeRoot = path.join(testRoot, "opt-runtime");
fs.mkdirSync(path.join(separateRuntimeRoot, "bin"), { recursive: true });
fs.writeFileSync(path.join(separateRuntimeRoot, "bin", "musrfit"), "");
fs.writeFileSync(path.join(separateRuntimeRoot, "musrfit_startup.xml"), "<musrfit/>");
(function testSeparateRuntimeIsDetected() {
const noBundleResources = path.join(testRoot, "no-bundle-resources");
const sandbox = buildSandbox(noBundleResources, {
MUSRFLOW_RUNTIME_ROOT: separateRuntimeRoot
});
loadLibraries(sandbox);
assert.strictEqual(sandbox.bundledRuntimeRoot(), "");
assert.strictEqual(sandbox.systemRuntimeRoot(), separateRuntimeRoot);
assert.strictEqual(
sandbox.resolveLocalCommand("musrfit"),
path.join(separateRuntimeRoot, "bin", "musrfit"));
const env = sandbox.buildToolEnvironment();
assert.strictEqual(env.ROOTSYS, separateRuntimeRoot);
assert.strictEqual(env.MUSRFITPATH, separateRuntimeRoot);
assert.strictEqual(env.LD_LIBRARY_PATH.indexOf(path.join(separateRuntimeRoot, "lib")) === 0, true);
// The startup XML shipped with the separate runtime is the last resort.
assert.strictEqual(
sandbox.loadLocalPortableRunNaming(),
path.join(separateRuntimeRoot, "musrfit_startup.xml"));
})();
// With the bundle present the runtime bin must win over /usr/local/bin and the
// spawn environment must expose ROOTSYS, MUSRFITPATH, and LD_LIBRARY_PATH.
(function testBundledRuntimeIsPreferredAndExported() {
const sandbox = buildSandbox(resourcesPath, { LD_LIBRARY_PATH: "/host/lib" });
loadLibraries(sandbox);
assert.strictEqual(sandbox.bundledRuntimeRoot(), runtimeRoot);
assert.strictEqual(
sandbox.resolveLocalCommand("musrfit"),
path.join(runtimeRoot, "bin", "musrfit"));
assert.strictEqual(
sandbox.resolveLocalCommand("musrt0"),
path.join(runtimeRoot, "bin", "musrt0"));
// dump_header ships with the musrfit package and must come from the bundle
// too, since the host may have no musrfit installation at all.
assert.strictEqual(
sandbox.resolveLocalCommand("dump_header"),
path.join(runtimeRoot, "bin", "dump_header"));
assert.strictEqual(
sandbox.localCommandPathBias().indexOf(path.join(runtimeRoot, "bin") + ":") === 0,
true);
const env = sandbox.buildToolEnvironment();
assert.strictEqual(env.ROOTSYS, runtimeRoot);
assert.strictEqual(env.MUSRFITPATH, runtimeRoot);
assert.strictEqual(env.LD_LIBRARY_PATH,
path.join(runtimeRoot, "lib") + ":/host/lib");
assert.strictEqual(env.PATH.indexOf(path.join(runtimeRoot, "bin") + ":") === 0, true);
})();
// An explicit user-configured tools directory must still outrank the bundle,
// both for command resolution and for the PATH bias.
(function testConfiguredBinDirOutranksBundle() {
const tools = path.join(testRoot, "tools");
fs.mkdirSync(tools, { recursive: true });
fs.writeFileSync(path.join(tools, "musrfit"), "#!/bin/sh\n");
const sandbox = buildSandbox(resourcesPath, {});
loadLibraries(sandbox);
sandbox.window.localStorage.setItem("musrflow.binDir", tools);
assert.strictEqual(
sandbox.resolveLocalCommand("musrfit"),
path.join(tools, "musrfit"));
assert.strictEqual(
sandbox.localCommandPathBias().indexOf(tools + ":" + path.join(runtimeRoot, "bin") + ":") === 0,
true);
})();
// Without the bundle (no runtime/bin/musrfit) detection is off and the host
// environment is passed through unchanged.
(function testNoBundleFallsBackToHost() {
const plainResources = path.join(testRoot, "plain-resources");
fs.mkdirSync(plainResources, { recursive: true });
const sandbox = buildSandbox(plainResources, {});
loadLibraries(sandbox);
assert.strictEqual(sandbox.bundledRuntimeRoot(), "");
assert.strictEqual(sandbox.bundledRuntimeBinDir(), "");
const env = sandbox.buildToolEnvironment();
assert.strictEqual(env.ROOTSYS, undefined);
assert.strictEqual(env.MUSRFITPATH, undefined);
assert.strictEqual(env.LD_LIBRARY_PATH, undefined);
assert.strictEqual(env.PATH.indexOf(plainResources) === -1, true);
})();
// The startup XML shipped with the bundle is used as the last resort when no
// user, home, or working-directory startup file exists.
(function testBundledStartupXmlFallback() {
const sandbox = buildSandbox(resourcesPath, {});
loadLibraries(sandbox);
assert.strictEqual(
sandbox.loadLocalPortableRunNaming(),
path.join(runtimeRoot, "musrfit_startup.xml"));
})();
// Windows: the bundled Linux tools run through wsl.exe, with Windows path
// arguments translated to their /mnt/<drive>/... form. Host and
// Windows-native commands are left untouched.
(function testWslLaunchTranslationOnWindows() {
const sandbox = buildSandbox(resourcesPath, {}, "win32");
loadLibraries(sandbox);
assert.strictEqual(sandbox.isWslRuntimeHost(), true);
assert.strictEqual(sandbox.windowsPathToWsl("C:\\data\\run.msr"), "/mnt/c/data/run.msr");
assert.strictEqual(sandbox.windowsPathToWsl("D:/work/x"), "/mnt/d/work/x");
assert.strictEqual(sandbox.windowsPathToWsl("/already/posix"), "/already/posix");
assert.strictEqual(sandbox.windowsPathToWsl("-g"), "-g");
const bundleTool = path.join(runtimeRoot, "bin", "musrt0");
const launch = sandbox.prepareLocalLaunch(bundleTool, ["-g", "C:\\work\\job.msr"]);
assert.strictEqual(launch.command, "wsl.exe");
assert.strictEqual(launch.viaWsl, true);
const expectedWslArgs = [
"-d", "muSRFlow-runtime", "--", "env",
"ROOTSYS=/opt/musrfit-runtime",
"MUSRFITPATH=/opt/musrfit-runtime",
"LD_LIBRARY_PATH=/opt/musrfit-runtime/lib",
"PATH=/opt/musrfit-runtime/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"/opt/musrfit-runtime/bin/musrt0",
"-g", "/mnt/c/work/job.msr"
];
assert.deepStrictEqual(Array.from(launch.args), expectedWslArgs);
// A Windows-native tool (user-configured directory) is launched directly.
const nativeLaunch = sandbox.prepareLocalLaunch("C:\\tools\\musrfit.exe", ["-u", "4"]);
assert.strictEqual(nativeLaunch.command, "C:\\tools\\musrfit.exe");
assert.strictEqual(nativeLaunch.viaWsl, false);
assert.deepStrictEqual(Array.from(nativeLaunch.args), ["-u", "4"]);
// The msr2data shell-string path is rewritten too.
const commandString = bundleTool + " \"[1 2 3]\" _tmpl msr-1 global";
assert.strictEqual(
sandbox.prepareWslCommandString(commandString),
'wsl.exe ' + expectedWslArgs.slice(0, -2).map(arg => '"' + arg + '"').join(' ')
+ ' "[1 2 3]" _tmpl msr-1 global');
assert.strictEqual(
sandbox.prepareWslCommandString("C:\\tools\\msr2data.exe x"),
"C:\\tools\\msr2data.exe x");
})();
// The main-process WSL import uses the inherited environment. Fit/Plot must
// preserve that same Windows search path when constructing their child env,
// including its usual mixed-case Path key and semicolon-separated entries.
(function testWindowsToolEnvironmentPreservesExecutableSearchPath() {
const windowsPath = String.raw`C:\Windows\System32;C:\Windows;C:\Program Files\WSL`;
for (const pathKey of ['Path', 'PATH', 'pAtH']) {
const sandbox = buildSandbox(resourcesPath, { [pathKey]: windowsPath }, 'win32');
loadLibraries(sandbox);
const originalEnvironment = Object.assign({}, sandbox.process.env);
const env = sandbox.buildToolEnvironment();
assert.strictEqual(env.ROOTSYS, undefined, 'Do not export Windows bundle paths as Linux ROOTSYS');
assert.strictEqual(env.MUSRFITPATH, undefined);
assert.strictEqual(env.LD_LIBRARY_PATH, undefined);
assert.strictEqual(env.PATH, windowsPath,
'Fit/Plot must keep Windows directories intact for wsl.exe lookup (' + pathKey + ')');
assert.deepStrictEqual(Object.keys(env).filter(key => key.toUpperCase() === 'PATH'), ['PATH']);
assert.deepStrictEqual(sandbox.process.env, originalEnvironment);
assert(!env.PATH.includes('/usr/bin'), 'Linux search paths do not belong in the Windows host PATH');
assert(!env.PATH.includes(runtimeRoot), 'The Linux runtime markers must not shadow Windows programs');
const nativeTools = String.raw`D:\Scientific tools\musrfit\bin`;
sandbox.getConfiguredBinDir = function() {
return nativeTools;
};
assert.strictEqual(sandbox.buildToolEnvironment().PATH, nativeTools + ';' + windowsPath);
}
// A plain object can contain both spellings, even though Windows itself
// treats them as one variable. Match Node's precedence and emit one key.
const sandbox = buildSandbox(resourcesPath, { Path: 'ignored', PATH: windowsPath }, 'win32');
loadLibraries(sandbox);
const env = sandbox.buildToolEnvironment();
assert.strictEqual(env.PATH, windowsPath);
assert.deepStrictEqual(Object.keys(env).filter(key => key.toUpperCase() === 'PATH'), ['PATH']);
})();
// On a Linux host the WSL translation is inert even when the bundle is present.
(function testWslTranslationInertOnLinux() {
const sandbox = buildSandbox(resourcesPath, {}, "linux");
loadLibraries(sandbox);
assert.strictEqual(sandbox.isWslRuntimeHost(), false);
const bundleTool = path.join(runtimeRoot, "bin", "musrfit");
const launch = sandbox.prepareLocalLaunch(bundleTool, ["-u", "2"]);
assert.strictEqual(launch.command, bundleTool);
assert.strictEqual(launch.viaWsl, false);
})();
// First-run runtime gate: before a Fit/Plot action the renderer waits for the
// WSL2 import. It is inert off Windows and cached after a successful import.
async function testRuntimeGateOnWindows() {
const sandbox = buildSandbox(resourcesPath, {}, "win32");
loadLibraries(sandbox);
sandbox.setFitStatus = function() {};
let ensureCalls = 0;
const seen = [];
sandbox.window.electronAPI = {
wslRuntime: {
ensure: function() {
ensureCalls++;
return Promise.resolve({ ok: true, status: "imported" });
},
onStatus: function(handler) {
if (typeof handler === "function") seen.push(handler);
return function() { seen.pop(); };
}
}
};
assert.strictEqual(await sandbox.window.MusrfitRuntimeGate.ready("Fit"), true);
assert.strictEqual(ensureCalls, 1);
assert.strictEqual(seen.length, 0, "the status subscription is removed after use");
// A resolved gate is cached: a later action does not re-run the import.
assert.strictEqual(await sandbox.window.MusrfitRuntimeGate.ready("Plot"), true);
assert.strictEqual(ensureCalls, 1);
}
async function testRuntimeGateFailureAndRetry() {
const sandbox = buildSandbox(resourcesPath, {}, "win32");
loadLibraries(sandbox);
sandbox.setFitStatus = function() {};
let attempts = 0;
sandbox.window.electronAPI = {
wslRuntime: {
ensure: function() {
attempts++;
if (attempts === 1) {
return Promise.resolve({
ok: false, status: "import-failed", error: "WSL not installed"
});
}
return Promise.resolve({ ok: true, status: "imported" });
},
onStatus: function() { return function() {}; }
}
};
assert.strictEqual(await sandbox.window.MusrfitRuntimeGate.ready("Fit"), false);
assert.strictEqual(sandbox.window.MusrfitRuntimeGate.message(), "WSL not installed");
// The failure resets the gate so a later action retries and can succeed.
assert.strictEqual(await sandbox.window.MusrfitRuntimeGate.ready("Fit"), true);
assert.strictEqual(attempts, 2);
}
async function testRuntimeGateFallsBackToConfiguredTools() {
const sandbox = buildSandbox(resourcesPath, {}, "win32");
loadLibraries(sandbox);
sandbox.setFitStatus = function() {};
const nativeDir = fs.mkdtempSync(path.join(os.tmpdir(), "musrflow-native-"));
fs.writeFileSync(path.join(nativeDir, "musrfit.exe"), "x");
sandbox.getConfiguredBinDir = function() { return nativeDir; };
sandbox.window.electronAPI = {
wslRuntime: {
ensure: function() {
return Promise.resolve({
ok: false, status: "import-failed", error: "WSL not installed"
});
},
onStatus: function() { return function() {}; }
}
};
// A failed import must not block a Fit when native tools are configured.
assert.strictEqual(await sandbox.window.MusrfitRuntimeGate.ready("Fit"), true);
}
async function testRuntimeGateInertOffWindows() {
const sandbox = buildSandbox(resourcesPath, {}, "linux");
loadLibraries(sandbox);
let ensureCalls = 0;
sandbox.window.electronAPI = {
wslRuntime: {
ensure: function() { ensureCalls++; return Promise.resolve({ ok: true }); },
onStatus: function() { return function() {}; }
}
};
assert.strictEqual(await sandbox.window.MusrfitRuntimeGate.ready("Fit"), true);
assert.strictEqual(ensureCalls, 0, "the gate never runs on non-Windows hosts");
}
async function main() {
// A private installation is inert until its bin directory is explicitly
// selected. Its own ROOT environment must then outrank unrelated runtimes.
const managedDirectory = path.join(testRoot, 'private-runtimes');
const managedRoot = path.join(managedDirectory, 'test-release', 'runtime');
fs.mkdirSync(path.join(managedRoot, 'bin'), { recursive: true });
fs.mkdirSync(path.join(managedRoot, 'lib'));
fs.writeFileSync(path.join(managedRoot, 'bin', 'musrfit'), '');
fs.writeFileSync(path.join(managedRoot, 'lib', 'libCore.so'), '');
fs.writeFileSync(path.join(managedRoot, 'runtime-manifest.json'), '{}');
fs.writeFileSync(path.join(managedRoot, 'musrfit_startup.xml'), '<musrfit/>');
const managed = buildSandbox(resourcesPath, { MUSRFLOW_MANAGED_RUNTIME_DIRECTORY: managedDirectory });
loadLibraries(managed);
assert.strictEqual(managed.activeRuntimeRoot(), runtimeRoot);
managed.window.localStorage.setItem('musrflow.binDir', path.join(managedRoot, 'bin'));
assert.strictEqual(managed.activeRuntimeRoot(), managedRoot);
assert.strictEqual(managed.resolveLocalCommand('musrfit'), path.join(managedRoot, 'bin', 'musrfit'));
assert.strictEqual(managed.buildToolEnvironment().ROOTSYS, managedRoot);
assert(managed.buildToolEnvironment().LD_LIBRARY_PATH.startsWith(path.join(managedRoot, 'lib')));
assert.strictEqual(managed.loadLocalPortableRunNaming(), path.join(managedRoot, 'musrfit_startup.xml'));
managed.window.localStorage.setItem('musrflow.binDir', '/an/explicit/host/bin');
assert.strictEqual(managed.activeRuntimeRoot(), runtimeRoot);
// Preferences keep their draft semantics. Installing/using a runtime is a
// separately confirmed action, so Cancel must preserve that chosen runtime.
const elements = {};
for (const id of ['localRuntimeStatus', 'runtimeCheck', 'runtimeInstall', 'runtimeCancel', 'FitMSR', 'PlotMSR', 'binDir']) {
elements[id] = { textContent: '', disabled: false, hidden: false, value: '' };
}
elements.preferencesDialog = { dataset: {}, close: function() {} };
managed.document.getElementById = function(id) {
return elements[id] || null;
};
managed.setFitStatus = function() {};
managed.reloadLocalPortableRunNaming = function() {};
managed.setMusrfitActionState = function() {
elements.FitMSR.disabled = false;
elements.PlotMSR.disabled = false;
};
let finishInstall;
let cancelled = 0;
managed.window.electronAPI = { localRuntime: {
install: function() {
return new Promise(function(resolve) { finishInstall = resolve; });
},
cancel: function() { cancelled++; },
onProgress: function() { return function() {}; }
} };
const firstInstall = managed.installElectronRuntime();
assert.strictEqual(elements.FitMSR.disabled, true);
assert.strictEqual(elements.PlotMSR.disabled, true);
assert.strictEqual(await managed.wslRuntimeGateReady(), false);
managed.cancelElectronRuntimeInstall();
finishInstall({ ok: false, cancelled: true });
await firstInstall;
assert.strictEqual(cancelled, 1);
assert.strictEqual(managed.getConfiguredBinDir(), '/an/explicit/host/bin');
assert(elements.localRuntimeStatus.textContent.includes('Previous tools were kept'));
const secondInstall = managed.installElectronRuntime();
finishInstall({ ok: true, root: managedRoot });
await secondInstall;
assert.strictEqual(managed.getConfiguredBinDir(), path.join(managedRoot, 'bin'));
assert.strictEqual(elements.preferencesDialog.dataset.originalBinDir, path.join(managedRoot, 'bin'));
managed.cancelElectronPreferences();
assert.strictEqual(elements.binDir.value, path.join(managedRoot, 'bin'));
assert.strictEqual(elements.FitMSR.disabled, false);
assert.strictEqual(elements.PlotMSR.disabled, false);
await testRuntimeGateOnWindows();
await testRuntimeGateFailureAndRetry();
await testRuntimeGateFallsBackToConfiguredTools();
await testRuntimeGateInertOffWindows();
console.log("Bundled runtime resolution tests passed");
}
main().catch(function(error) {
console.error(error);
process.exit(1);
});