Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
# SPDX-License-Identifier: AGPL-3.0-only
import importlib.util
import io
import contextlib
import dataclasses
import json
import os
import sys
import tarfile
import types
import zipfile
from pathlib import Path
import pytest
PACKAGE_ROOT = Path(__file__).resolve().parents[3]
MODULE_PATH = PACKAGE_ROOT / "studio" / "install_node_prebuilt.py"
SPEC = importlib.util.spec_from_file_location("studio_install_node_prebuilt", MODULE_PATH)
assert SPEC is not None and SPEC.loader is not None
M = importlib.util.module_from_spec(SPEC)
sys.modules[SPEC.name] = M
SPEC.loader.exec_module(M)
HostInfo = M.HostInfo
PrebuiltFallback = M.PrebuiltFallback
@pytest.fixture(autouse = True)
def _no_ambient_node_mirror(monkeypatch):
monkeypatch.delenv(M.NODE_MIRROR_ENV, raising = False)
@pytest.mark.parametrize("content_length", ["2097152", None])
def test_download_file_reports_progress(tmp_path, monkeypatch, capsys, content_length):
from io import BytesIO
payload = b"x" * (2 * 1024 * 1024)
response = BytesIO(payload)
response.headers = {"Content-Length": content_length}
monkeypatch.setattr(M.urllib.request, "urlopen", lambda *args, **kwargs: response)
monkeypatch.setattr(M, "_LOG_TO_STDOUT", True)
destination = tmp_path / "node.zip"
M.download_file("https://nodejs.org/node.zip", destination)
output = capsys.readouterr()
assert output.err == ""
assert "Downloading node.zip:" in output.out
if content_length:
assert "50.0% (1.0 MiB/2.0 MiB)" in output.out
assert "100.0% (2.0 MiB/2.0 MiB)" in output.out
else:
assert "2.0 MiB downloaded at" in output.out
assert "%" not in output.out
assert destination.read_bytes() == payload
def _host(node_os: str, node_arch: str) -> HostInfo:
ext = ".zip" if node_os == "win" else ".tar.gz"
return HostInfo(
system = {"linux": "Linux", "darwin": "Darwin", "win": "Windows"}[node_os],
machine = node_arch,
node_os = node_os,
node_arch = node_arch,
archive_ext = ext,
is_windows = node_os == "win",
)
@pytest.mark.parametrize(
"system,machine,exp_os,exp_arch,exp_ext",
[
("Linux", "x86_64", "linux", "x64", ".tar.xz"),
("Linux", "aarch64", "linux", "arm64", ".tar.xz"),
("Darwin", "x86_64", "darwin", "x64", ".tar.xz"),
("Darwin", "arm64", "darwin", "arm64", ".tar.xz"),
("Windows", "AMD64", "win", "x64", ".zip"),
("Windows", "ARM64", "win", "arm64", ".zip"),
],
)
def test_detect_host(monkeypatch, system, machine, exp_os, exp_arch, exp_ext):
monkeypatch.setattr(M.platform, "system", lambda: system)
monkeypatch.setattr(M.platform, "machine", lambda: machine)
host = M.detect_host()
assert (host.node_os, host.node_arch, host.archive_ext) == (exp_os, exp_arch, exp_ext)
assert host.is_windows == (exp_os == "win")
@pytest.mark.parametrize(
"system,machine",
[("Plan9", "x86_64"), ("Linux", "sparc64"), ("Linux", "armv7l"), ("Linux", "armhf")],
)
def test_detect_host_unsupported(monkeypatch, system, machine):
monkeypatch.setattr(M.platform, "system", lambda: system)
monkeypatch.setattr(M.platform, "machine", lambda: machine)
with pytest.raises(PrebuiltFallback):
M.detect_host()
def test_asset_and_url_linux():
host = _host("linux", "x64")
assert M.node_asset_name("24.17.0", host) == "node-v24.17.0-linux-x64.tar.gz"
assert (
M.node_download_url("24.17.0", M.node_asset_name("24.17.0", host))
== "https://nodejs.org/dist/v24.17.0/node-v24.17.0-linux-x64.tar.gz"
)
def test_asset_windows_is_zip():
host = _host("win", "x64")
assert M.node_asset_name("24.17.0", host) == "node-v24.17.0-win-x64.zip"
def test_shasums_url():
assert M.node_shasums_url("24.17.0") == "https://nodejs.org/dist/v24.17.0/SHASUMS256.txt"
@pytest.mark.parametrize("value", ["https://mirror.example/node/", " https://mirror.example/node "])
def test_node_mirror_env_rebases_every_url(monkeypatch, value):
monkeypatch.setenv(M.NODE_MIRROR_ENV, value)
assert M.node_dist_index_url() == "https://mirror.example/node/index.json"
assert M.node_shasums_url("24.17.0") == "https://mirror.example/node/v24.17.0/SHASUMS256.txt"
assert (
M.node_download_url("24.17.0", "node-v24.17.0-linux-x64.tar.gz")
== "https://mirror.example/node/v24.17.0/node-v24.17.0-linux-x64.tar.gz"
)
def test_blank_node_mirror_env_keeps_nodejs_org(monkeypatch):
monkeypatch.setenv(M.NODE_MIRROR_ENV, " ")
assert M.node_dist_index_url() == "https://nodejs.org/dist/index.json"
assert M.node_shasums_url("24.17.0") == "https://nodejs.org/dist/v24.17.0/SHASUMS256.txt"
assert (
M.node_download_url("24.17.0", "node-v24.17.0-linux-x64.tar.gz")
== "https://nodejs.org/dist/v24.17.0/node-v24.17.0-linux-x64.tar.gz"
)
def test_binary_layout_is_host_aware():
# Windows ships node.exe + node_modules\npm at the root; Unix uses bin/ + lib/.
win = _host("win", "x64")
nix = _host("linux", "x64")
assert M.node_binary_path(Path("/n"), win) == Path("/n/node.exe")
assert M.node_binary_path(Path("/n"), nix) == Path("/n/bin/node")
assert M.npm_cli_path(Path("/n"), win) == Path("/n/node_modules/npm/bin/npm-cli.js")
assert M.npm_cli_path(Path("/n"), nix) == Path("/n/lib/node_modules/npm/bin/npm-cli.js")
def test_expected_sha256_for():
asset = "node-v24.17.0-linux-x64.tar.gz"
good = "a" * 64
text = (
f"{'b' * 64} node-v24.17.0-linux-arm64.tar.gz\n"
f"{good} {asset}\n"
f"{'c' * 64} node-v24.17.0-win-x64.zip\n"
)
assert M.expected_sha256_for(text, asset) == good
assert M.expected_sha256_for(text, "node-v24.17.0-darwin-x64.tar.gz") is None
def test_expected_sha256_rejects_malformed():
asset = "node-v24.17.0-linux-x64.tar.gz"
assert M.expected_sha256_for(f"notahex {asset}\n", asset) is None
INDEX = [
{"version": "v26.3.1", "lts": False},
{"version": "v24.18.0", "lts": "Krypton"},
{"version": "v24.9.0", "lts": "Krypton"},
{"version": "v22.20.0", "lts": "Jod"},
{"version": "v20.19.0", "lts": "Iron"},
]
def test_select_lts_respects_min_major():
# Newest LTS at/above 24 -> 24.18.0 (22.x LTS is below the floor).
assert M.select_node_version(INDEX, channel = "lts", min_major = 24) == "24.18.0"
def test_select_latest_overall():
assert M.select_node_version(INDEX, channel = "latest", min_major = 24) == "26.3.1"
def test_select_explicit_passthrough():
assert M.select_node_version(INDEX, channel = "v24.5.0", min_major = 24) == "24.5.0"
def test_select_no_candidate_raises():
with pytest.raises(PrebuiltFallback):
M.select_node_version(INDEX, channel = "lts", min_major = 99)
def _add_file(
tar: tarfile.TarFile,
name: str,
data: bytes,
mode: int = 0o644,
):
info = tarfile.TarInfo(name)
info.size = len(data)
info.mode = mode
tar.addfile(info, io.BytesIO(data))
def _add_symlink(tar: tarfile.TarFile, name: str, target: str):
info = tarfile.TarInfo(name)
info.type = tarfile.SYMTYPE
info.linkname = target
tar.addfile(info)
@pytest.mark.skipif(
os.name == "nt",
reason = "Node ships a .zip (no symlinks) on Windows; the tar+symlink path is Unix-only",
)
def test_extract_tar_gz_with_npm_symlink(tmp_path: Path):
# Mirrors the real Node tarball: bin/npm -> ../lib/node_modules/npm/bin/npm-cli.js
archive = tmp_path / "node.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
_add_file(tar, "node-v24/bin/node", b"#!/bin/sh\necho v24.17.0\n", mode = 0o755)
_add_file(tar, "node-v24/lib/node_modules/npm/bin/npm-cli.js", b"// npm")
_add_symlink(tar, "node-v24/bin/npm", "../lib/node_modules/npm/bin/npm-cli.js")
dest = tmp_path / "out"
M.extract_archive(archive, dest)
npm_link = dest / "node-v24" / "bin" / "npm"
assert npm_link.is_symlink()
assert (dest / "node-v24" / "bin" / "node").exists()
assert (dest / "node-v24" / "bin" / "node").stat().st_mode & 0o111
def test_extract_zip(tmp_path: Path):
archive = tmp_path / "node.zip"
with zipfile.ZipFile(archive, "w") as zf:
zf.writestr("node-v24-win-x64/node.exe", b"MZ")
zf.writestr("node-v24-win-x64/npm.cmd", b"@echo off")
dest = tmp_path / "out"
M.extract_archive(archive, dest)
assert (dest / "node-v24-win-x64" / "node.exe").exists()
def test_extract_rejects_path_traversal(tmp_path: Path):
archive = tmp_path / "evil.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
_add_file(tar, "../escape.txt", b"pwn")
with pytest.raises(PrebuiltFallback):
M.extract_archive(archive, tmp_path / "out")
def test_download_file_verified_accepts_match(tmp_path: Path, monkeypatch):
payload = b"real-node-archive"
sha = M.hashlib.sha256(payload).hexdigest()
def fake_download(url: str, destination: Path):
destination.write_bytes(payload)
monkeypatch.setattr(M, "download_file", fake_download)
dest = tmp_path / "a.tar.gz"
M.download_file_verified("http://x/a.tar.gz", dest, expected_sha256 = sha, label = "a")
assert dest.read_bytes() == payload
def test_download_file_verified_rejects_mismatch(tmp_path: Path, monkeypatch):
def fake_download(url: str, destination: Path):
destination.write_bytes(b"tampered")
monkeypatch.setattr(M, "download_file", fake_download)
with pytest.raises(PrebuiltFallback):
M.download_file_verified("http://x/a", tmp_path / "a", expected_sha256 = "0" * 64, label = "a")
def test_pid_is_alive_windows_uses_tasklist_not_os_kill(monkeypatch):
monkeypatch.setattr(M.sys, "platform", "win32")
def fail_kill(pid, sig):
raise AssertionError("Windows liveness must not call os.kill(pid, 0)")
def fake_run(cmd, **kwargs):
assert cmd[:2] == ["tasklist", "/FI"]
assert "PID eq 1234" in cmd
return types.SimpleNamespace(stdout = '"node.exe","1234","Console","1","12,345 K"\n')
monkeypatch.setattr(M.os, "kill", fail_kill)
monkeypatch.setattr(M.subprocess, "run", fake_run)
assert M._pid_is_alive(1234) is True
def test_pid_is_alive_windows_false_when_tasklist_omits_pid(monkeypatch):
monkeypatch.setattr(M.sys, "platform", "win32")
monkeypatch.setattr(
M.subprocess,
"run",
lambda *a, **k: types.SimpleNamespace(
stdout = "INFO: No tasks are running which match the specified criteria.\n"
),
)
assert M._pid_is_alive(1234) is False
def test_pid_is_alive_windows_assumes_alive_when_tasklist_fails(monkeypatch):
monkeypatch.setattr(M.sys, "platform", "win32")
def boom(*args, **kwargs):
raise OSError("tasklist unavailable")
monkeypatch.setattr(M.subprocess, "run", boom)
assert M._pid_is_alive(1234) is True
def test_pid_is_alive_posix_signal_zero(monkeypatch):
monkeypatch.setattr(M.sys, "platform", "linux")
calls = []
def fake_kill(pid, sig):
calls.append((pid, sig))
if pid == 9999:
raise ProcessLookupError
monkeypatch.setattr(M.os, "kill", fake_kill)
assert M._pid_is_alive(1234) is True
assert M._pid_is_alive(9999) is False
assert calls == [(1234, 0), (9999, 0)]
def test_existing_install_matches_false_without_metadata(tmp_path: Path):
host = _host("linux", "x64")
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
def test_existing_install_matches_true_when_version_and_runtime_ok(tmp_path: Path, monkeypatch):
host = _host("linux", "x64")
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 10)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
def test_install_prebuilt_short_circuits_when_version_matches(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
install_dir.mkdir()
version = M.pinned_default_version(M.load_pins())
asset = M.node_asset_name(version, _host("linux", "x64"))
pin = M.pinned_sha256(M.load_pins(), version, asset)
M.write_metadata(install_dir, version = version, asset = asset, sha256 = pin)
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
def boom(*a, **k):
raise AssertionError("must not download when the install already matches")
monkeypatch.setattr(M, "download_file", boom)
monkeypatch.setattr(M, "download_bytes", boom)
rc = M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)
assert rc == M.EXIT_SUCCESS
def test_a_matching_install_beside_a_running_installer_still_exits_0(tmp_path: Path, monkeypatch):
"""Failing to write the record under a live lock must still exit 0; exit 3 is fatal in setup.sh."""
host = _host("linux", "x64")
install_dir = tmp_path / "node"
install_dir.mkdir()
_real_node_tree(install_dir, host)
version = M.pinned_default_version(M.load_pins())
asset = M.node_asset_name(version, host)
# A marker written before the record existed: the one shape with something to backfill.
M.write_metadata(
install_dir,
version = version,
asset = asset,
sha256 = M.pinned_sha256(M.load_pins(), version, asset),
)
assert "node_version_checked" not in M.load_metadata(install_dir)
monkeypatch.setattr(M, "detect_host", lambda: host)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
def boom(*a, **k):
raise AssertionError("must not download when the install already matches")
monkeypatch.setattr(M, "download_file", boom)
monkeypatch.setattr(M, "download_bytes", boom)
# Held by this process, which is alive, so the stale-lock reclaim does not fire.
lock_path = M.install_lock_path(install_dir)
lock_path.parent.mkdir(parents = True, exist_ok = True)
lock_path.write_text(f"{os.getpid()}\n", encoding = "utf-8")
# The PID-file implementation, so the holder is a file this test can really write.
monkeypatch.setattr(M, "FileLock", None)
monkeypatch.setattr(M, "RECORD_LOCK_TIMEOUT_SECONDS", 0)
monkeypatch.setattr(M, "INSTALL_LOCK_TIMEOUT_SECONDS", 0)
assert M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False) == (
M.EXIT_SUCCESS
)
assert "node_version_checked" not in M.load_metadata(install_dir)
def test_existing_install_usable_is_version_agnostic(tmp_path: Path, monkeypatch):
host = _host("linux", "x64")
assert M.existing_install_usable(tmp_path, host) is False
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
assert M.existing_install_usable(tmp_path, host) is True
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 10)
assert M.existing_install_usable(tmp_path, host) is False
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: None)
assert M.existing_install_usable(tmp_path, host) is False
def _offline(*a, **k):
raise OSError("nodejs.org unreachable")
def test_install_prebuilt_keeps_existing_when_index_unreachable(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = "24.17.0", asset = "x", sha256 = "y")
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.setattr(M, "fetch_json", _offline)
def boom(*a, **k):
raise AssertionError("must not download when keeping the existing install")
monkeypatch.setattr(M, "download_file", boom)
monkeypatch.setattr(M, "download_bytes", boom)
rc = M.install_prebuilt(install_dir, channel = "lts", min_major = 24, force = False)
assert rc == M.EXIT_SUCCESS
def test_install_prebuilt_reraises_when_index_unreachable_and_no_install(
tmp_path: Path, monkeypatch
):
install_dir = tmp_path / "node"
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "fetch_json", _offline)
with pytest.raises(OSError):
M.install_prebuilt(install_dir, channel = "lts", min_major = 24, force = False)
def test_install_prebuilt_force_does_not_keep_existing_offline(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = "24.17.0", asset = "x", sha256 = "y")
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.setattr(M, "fetch_json", _offline)
with pytest.raises(OSError):
M.install_prebuilt(install_dir, channel = "lts", min_major = 24, force = True)
@pytest.mark.parametrize(
"ver,ok",
[
("20.19.0", True),
("20.18.9", False),
("22.12.0", True),
("22.11.5", False),
("23.0.0", True),
("24.4.1", True),
("21.7.3", False),
("24", True),
("20", False),
],
)
def test_meets_node_floor(ver, ok):
assert M._meets_node_floor(ver) is ok
def test_install_prebuilt_rejects_explicit_below_floor(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
def boom(*a, **k):
raise AssertionError("must not download a below-floor Node")
monkeypatch.setattr(M, "download_file", boom)
monkeypatch.setattr(M, "download_bytes", boom)
with pytest.raises(PrebuiltFallback):
M.install_prebuilt(install_dir, channel = "20.18.0", min_major = 24, force = False)
def test_install_prebuilt_keeps_existing_when_download_fails(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = "24.9.0", asset = "x", sha256 = "y")
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.9.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.setattr(M, "download_file_verified", _offline)
rc = M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)
assert rc == M.EXIT_SUCCESS
def test_install_prebuilt_reraises_download_failure_without_existing(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "download_file_verified", _offline)
with pytest.raises(OSError):
M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)
def _swap_stays_denied(
tmp_path: Path,
monkeypatch,
*,
recorded: str,
runs: bool,
real_swap: bool = False,
) -> Path:
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = recorded, asset = "old", sha256 = "old")
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "installed_node_version", lambda d, h: recorded if runs else None)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.setattr(
M, "download_file_verified", lambda url, path, **kw: path.write_bytes(b"zip")
)
def fake_extract(_archive, extract_dir):
(extract_dir / "node-v24").mkdir(parents = True)
def reported_acl_denial(_extracted, _install_dir):
exc = _oserror(5)
# Literal, so the parity cases also run against a module without the helper.
exc._unsloth_acl_recovery_lines = [f' takeown /F "{install_dir}" /R /D Y']
raise exc
monkeypatch.setattr(M, "extract_archive", fake_extract)
monkeypatch.setattr(M, "_ensure_npm_floor", lambda d, h: None)
if not real_swap:
monkeypatch.setattr(M, "_swap_into_place", reported_acl_denial)
return install_dir
real_os = M.os
class _WindowsRenames:
# Module-local only: a real os.name = "nt" makes Path() a WindowsPath, unusable on Linux.
name = "nt"
def __getattr__(self, attr):
return getattr(real_os, attr)
@staticmethod
def replace(src, dst):
if Path(src).is_dir():
exc = PermissionError(13, "Access is denied", str(src), None, str(dst))
exc.winerror = 5
raise exc
return real_os.replace(src, dst)
monkeypatch.setattr(M, "os", _WindowsRenames())
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
return install_dir
def test_install_prebuilt_keeps_existing_when_a_reported_denial_blocks_the_swap(
tmp_path: Path, monkeypatch, capsys
):
install_dir = _swap_stays_denied(tmp_path, monkeypatch, recorded = "24.9.0", runs = True)
rc = M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)
assert rc == M.EXIT_SUCCESS
output = "".join(capsys.readouterr())
assert "could not be replaced" in output
assert "keeping existing isolated Node" in output
assert "download failed" not in output
@pytest.mark.parametrize(
"runs, force, recorded_is_pinned",
[
pytest.param(False, False, False, id = "node-does-not-run"),
pytest.param(True, True, False, id = "force"),
pytest.param(True, False, True, id = "recorded-digest-is-not-the-pin"),
],
)
def test_install_prebuilt_reraises_a_reported_denial_it_cannot_keep_existing_through(
tmp_path: Path, monkeypatch, runs, force, recorded_is_pinned
):
recorded = M.pinned_default_version(M.load_pins()) if recorded_is_pinned else "24.9.0"
install_dir = _swap_stays_denied(tmp_path, monkeypatch, recorded = recorded, runs = runs)
with pytest.raises(OSError) as excinfo:
M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = force)
assert excinfo.value.winerror == 5
def test_a_denial_that_cannot_keep_node_leaves_the_repair_to_setup(
tmp_path: Path, monkeypatch, capsys
):
# Exit 4: setup.ps1 prints its own repair; ours too would show two sets.
install_dir = _swap_stays_denied(
tmp_path, monkeypatch, recorded = "24.9.0", runs = False, real_swap = True
)
rc = M.main(["--install-dir", str(install_dir)])
output = capsys.readouterr().out
assert rc == M.EXIT_DENIED
assert "rename still blocked (5)" in output
assert f"{M.DENIED_SCOPE_MARKER}{M.DENIED_SCOPE_INSTALL_DIR}" in output
assert "takeown" not in output, output
def test_a_kept_node_prints_the_repair_setup_relays(tmp_path: Path, monkeypatch, capsys):
install_dir = _swap_stays_denied(
tmp_path, monkeypatch, recorded = "24.9.0", runs = True, real_swap = True
)
rc = M.main(["--install-dir", str(install_dir)])
output = capsys.readouterr().out
assert rc == M.EXIT_SUCCESS
assert f'takeown /F "{install_dir}" /R /D Y' in output
assert f'takeown /F "{install_dir.parent}"' in output
assert output.index("takeown") < output.index("existing Node could not be replaced")
def test_run_node_pins_npm_prefix_to_install_dir(tmp_path: Path, monkeypatch):
# npm's global prefix is pinned to install_dir and NODE_PATH dropped, so `npm -g` never hits system Node.
install_dir = tmp_path / "node"
monkeypatch.setenv("NPM_CONFIG_PREFIX", "/usr/local")
monkeypatch.setenv("NODE_PATH", "/usr/lib/node_modules")
captured = {}
def fake_run(cmd, **kw):
captured["env"] = kw["env"]
return types.SimpleNamespace(returncode = 0, stdout = "v24.17.0\n", stderr = "")
monkeypatch.setattr(M.subprocess, "run", fake_run)
assert M._run_node(install_dir, _host("linux", "x64"), ["-v"]) == "v24.17.0"
env = captured["env"]
assert env["NPM_CONFIG_PREFIX"] == str(install_dir)
assert env["npm_config_prefix"] == str(install_dir)
assert "NODE_PATH" not in env
def test_ensure_npm_floor_scopes_upgrade_to_install_dir(tmp_path: Path, monkeypatch):
# npm < 11 self-upgrades only inside the isolated prefix.
install_dir = tmp_path / "node"
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 10)
calls = []
monkeypatch.setattr(M, "_run_node", lambda d, h, args, **kw: calls.append((d, args)) or "")
M._ensure_npm_floor(install_dir, _host("linux", "x64"))
assert len(calls) == 1
target_dir, args = calls[0]
assert target_dir == install_dir
assert args[-3:] == ["install", "-g", f"npm@^{M.NPM_MIN_MAJOR}"]
def test_ensure_npm_floor_noop_when_npm_meets_bar(tmp_path: Path, monkeypatch):
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: M.NPM_MIN_MAJOR)
def boom(*a, **k):
raise AssertionError("must not run an npm upgrade when npm already meets the floor")
monkeypatch.setattr(M, "_run_node", boom)
M._ensure_npm_floor(tmp_path / "node", _host("linux", "x64"))
# Archives must be verified against committed pins, never a same-origin re-fetch.
ALL_SUPPORTED_HOSTS = [
("linux", "x64"),
("linux", "arm64"),
("darwin", "x64"),
("darwin", "arm64"),
("win", "x64"),
("win", "arm64"),
]
def test_load_pins_exposes_valid_default_version():
pins = M.load_pins()
version = M.pinned_default_version(pins)
assert M._version_tuple(version)
assert M._meets_node_floor(version)
def test_pinned_manifest_covers_every_supported_asset():
# A future Node bump must pin all six os/arch archives or a host loses its anchor.
pins = M.load_pins()
version = M.pinned_default_version(pins)
for node_os, node_arch in ALL_SUPPORTED_HOSTS:
host = _host(node_os, node_arch)
asset = M.node_asset_name(version, host)
digest = M.pinned_sha256(pins, version, asset)
assert digest is not None and len(digest) == 64, f"missing pin for {asset}"
assert all(c in "0123456789abcdef" for c in digest)
def test_pinned_sha256_unknown_pair_returns_none():
pins = M.load_pins()
assert M.pinned_sha256(pins, "99.0.0", "node-v99.0.0-linux-x64.tar.gz") is None
version = M.pinned_default_version(pins)
assert M.pinned_sha256(pins, version, "node-vX-bogus-arch.tar.gz") is None
def test_load_pins_rejects_bad_schema(tmp_path: Path, monkeypatch):
bad = tmp_path / "node_prebuilt_pins.json"
bad.write_text(json.dumps({"schema_version": 999}))
monkeypatch.setattr(M, "pins_path", lambda: bad)
with pytest.raises(PrebuiltFallback):
M.load_pins()
def test_load_pins_raises_when_missing(tmp_path: Path, monkeypatch):
monkeypatch.setattr(M, "pins_path", lambda: tmp_path / "does_not_exist.json")
with pytest.raises(PrebuiltFallback):
M.load_pins()
def test_resolve_expected_sha256_uses_pin_without_touching_network(monkeypatch):
pins = M.load_pins()
version = M.pinned_default_version(pins)
asset = M.node_asset_name(version, _host("linux", "x64"))
def boom(*a, **k):
raise AssertionError("pinned path must not fetch the remote SHASUMS256.txt")
monkeypatch.setattr(M, "download_bytes", boom)
sha = M.resolve_expected_sha256(pins, version, asset, allow_unverified = False)
assert sha == M.pinned_sha256(pins, version, asset)
def test_resolve_expected_sha256_failcloses_on_unpinned(monkeypatch):
pins = M.load_pins()
def boom(*a, **k):
raise AssertionError("must not reach the network when refusing an unpinned version")
monkeypatch.setattr(M, "download_bytes", boom)
with pytest.raises(PrebuiltFallback):
M.resolve_expected_sha256(
pins, "26.3.1", "node-v26.3.1-linux-x64.tar.gz", allow_unverified = False
)
def test_resolve_expected_sha256_optin_falls_back_to_remote_shasums(monkeypatch):
pins = M.load_pins()
asset = "node-v26.3.1-linux-x64.tar.gz"
remote_sha = "d" * 64
monkeypatch.setattr(M, "download_bytes", lambda url, **k: f"{remote_sha} {asset}\n".encode())
sha = M.resolve_expected_sha256(pins, "26.3.1", asset, allow_unverified = True)
assert sha == remote_sha
@pytest.mark.parametrize(
"value,expected",
[("1", True), ("true", True), ("YES", True), ("on", True), ("0", False), ("", False)],
)
def test_allow_unverified_node_reads_env(monkeypatch, value, expected):
monkeypatch.setenv(M.ALLOW_UNVERIFIED_ENV, value)
assert M.allow_unverified_node() is expected
def test_install_prebuilt_default_channel_resolves_pinned_version(tmp_path: Path, monkeypatch):
pins = M.load_pins()
version = M.pinned_default_version(pins)
install_dir = tmp_path / "node"
install_dir.mkdir()
asset = M.node_asset_name(version, _host("linux", "x64"))
pin = M.pinned_sha256(pins, version, asset)
M.write_metadata(install_dir, version = version, asset = asset, sha256 = pin)
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
def boom(*a, **k):
raise AssertionError("default channel must not hit nodejs.org when the install matches")
monkeypatch.setattr(M, "fetch_json", boom)
monkeypatch.setattr(M, "download_file", boom)
monkeypatch.setattr(M, "download_bytes", boom)
rc = M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)
assert rc == M.EXIT_SUCCESS
def test_install_prebuilt_failcloses_on_unpinned_latest(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)
monkeypatch.delenv(M.ALLOW_UNVERIFIED_ENV, raising = False)
def boom(*a, **k):
raise AssertionError("must not download an unpinned archive")
monkeypatch.setattr(M, "download_file", boom)
with pytest.raises(M.UnpinnedNodeRefused):
M.install_prebuilt(install_dir, channel = "latest", min_major = 24, force = False)
@pytest.mark.parametrize("channel", ["latest", "26.3.1"])
def test_install_prebuilt_unpinned_refusal_does_not_keep_existing(
tmp_path: Path, monkeypatch, channel
):
# An unpinned refusal fails closed even with a usable install; keep-existing is for transient failures.
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = "24.9.0", asset = "old", sha256 = "old")
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.9.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.delenv(M.ALLOW_UNVERIFIED_ENV, raising = False)
def boom(*a, **k):
raise AssertionError("must not download an unpinned archive")
monkeypatch.setattr(M, "download_file", boom)
with pytest.raises(M.UnpinnedNodeRefused):
M.install_prebuilt(install_dir, channel = channel, min_major = 24, force = False)
def test_unpinned_refusal_maps_to_fallback_exit_code(tmp_path: Path, monkeypatch, capsys):
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = "24.9.0", asset = "old", sha256 = "old")
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.9.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.delenv(M.ALLOW_UNVERIFIED_ENV, raising = False)
rc = M.main(["--install-dir", str(install_dir), "--node-version", "latest"])
assert rc == M.EXIT_FALLBACK
# UnpinnedNodeRefused must be caught before PrebuiltFallback, so assert the message too.
out = capsys.readouterr().out
assert "refusing to install Node" in out
assert "prebuilt unavailable" not in out
def test_resolve_expected_sha256_rejects_malformed_pins():
# A structurally-broken manifest is "not pinned" (None), never a bogus digest.
asset = "node-v24.17.0-linux-x64.tar.gz"
assert M.pinned_sha256({"versions": "nope"}, "24.17.0", asset) is None
assert M.pinned_sha256({"versions": {"24.17.0": "nope"}}, "24.17.0", asset) is None
assert M.pinned_sha256({"versions": {"24.17.0": {asset: "x" * 63}}}, "24.17.0", asset) is None
assert M.pinned_sha256({"versions": {"24.17.0": {asset: "z" * 64}}}, "24.17.0", asset) is None
up = "A" * 64
assert M.pinned_sha256({"versions": {"24.17.0": {asset: up}}}, "24.17.0", asset) == up.lower()
for bad in [{}, {"default_version": ""}, {"default_version": "not-a-version"}]:
with pytest.raises(PrebuiltFallback):
M.pinned_default_version(bad)
def test_install_prebuilt_optin_takes_remote_shasums_path(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
asset = "node-v26.3.1-linux-x64.tar.gz"
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "fetch_json", lambda url: INDEX)
monkeypatch.setenv(M.ALLOW_UNVERIFIED_ENV, "1")
shasums_fetched = {"n": 0}
def fake_shasums(url, **k):
shasums_fetched["n"] += 1
return f"{'d' * 64} {asset}\n".encode()
class _ReachedDownload(Exception):
pass
def reached(*a, **k):
raise _ReachedDownload
monkeypatch.setattr(M, "download_bytes", fake_shasums)
monkeypatch.setattr(M, "download_file_verified", reached)
with pytest.raises(_ReachedDownload):
M.install_prebuilt(install_dir, channel = "latest", min_major = 24, force = False)
assert shasums_fetched["n"] == 1
def test_pins_manifest_ships_next_to_installer():
assert M.pins_path() == MODULE_PATH.parent / M.PINS_FILENAME
assert M.pins_path().is_file()
def test_pins_manifest_is_declared_in_package_data():
# The pins manifest must ship in package data: an unpackaged trust anchor is no trust anchor
tomllib = pytest.importorskip("tomllib" if sys.version_info >= (3, 11) else "tomli")
data = tomllib.loads((PACKAGE_ROOT / "pyproject.toml").read_text(encoding = "utf-8"))
studio_globs = data["tool"]["setuptools"]["package-data"]["studio"]
assert M.PINS_FILENAME in studio_globs
def test_existing_install_matches_enforces_expected_sha(tmp_path: Path, monkeypatch):
# Must not keep a version-matching install whose recorded digest is not the pin.
host = _host("linux", "x64")
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "aa")
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
assert M.existing_install_matches(tmp_path, host, version = "24.17.0", expected_sha = "aa") is True
assert M.existing_install_matches(tmp_path, host, version = "24.17.0", expected_sha = "bb") is False
def test_install_prebuilt_refuses_existing_unpinned_install(tmp_path: Path, monkeypatch):
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = "26.3.1", asset = "a", sha256 = "s")
monkeypatch.setattr(M, "detect_host", lambda: _host("linux", "x64"))
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "26.3.1")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.delenv(M.ALLOW_UNVERIFIED_ENV, raising = False)
def boom(*a, **k):
raise AssertionError("must not keep or download an unpinned install")
monkeypatch.setattr(M, "download_file", boom)
with pytest.raises(M.UnpinnedNodeRefused):
M.install_prebuilt(install_dir, channel = "26.3.1", min_major = 24, force = False)
def test_pinned_target_wrong_sha_not_kept_when_download_fails(tmp_path: Path, monkeypatch):
host = _host("linux", "x64")
version = M.pinned_default_version(M.load_pins())
asset = M.node_asset_name(version, host)
install_dir = tmp_path / "node"
install_dir.mkdir()
M.write_metadata(install_dir, version = version, asset = asset, sha256 = "0" * 64)
monkeypatch.setattr(M, "detect_host", lambda: host)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.setattr(M, "download_file_verified", _offline)
with pytest.raises(OSError):
M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False)
# WinError 5 on a fresh install: a scanner still holds handles in the new files.
def _oserror(winerror: int) -> OSError:
exc = OSError(winerror, "mock")
exc.winerror = winerror
return exc
@pytest.mark.parametrize("winerror", [5, 32, 145])
def test_replace_retries_transient_windows_errors(monkeypatch, tmp_path, winerror):
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
calls = {"n": 0}
def flaky(src, dst):
calls["n"] += 1
if calls["n"] < 3:
raise _oserror(winerror)
monkeypatch.setattr(M.os, "replace", flaky)
M._replace_with_retry(tmp_path / "src", tmp_path / "dst")
assert calls["n"] == 3, "should have retried until the handle was released"
def test_replace_gives_up_and_reports_the_real_error(monkeypatch, tmp_path):
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
monkeypatch.setattr(M.os, "replace", lambda s, d: (_ for _ in ()).throw(_oserror(5)))
with pytest.raises(OSError) as excinfo:
M._replace_with_retry(tmp_path / "src", tmp_path / "dst", attempts = 3)
assert excinfo.value.winerror == 5
def test_replace_names_acl_recovery_when_access_denied_persists(monkeypatch, tmp_path, capsys):
"""A WinError 5 that outlasts the budget names the ACL recovery (#9928)."""
source = tmp_path / "node"
source.mkdir()
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
monkeypatch.setattr(M.os, "replace", lambda s, d: (_ for _ in ()).throw(_oserror(5)))
with pytest.raises(OSError) as excinfo:
M._replace_with_retry(
source, tmp_path / "node.old", attempts = 3, access_denied_paths = ((source, True),)
)
recovery = getattr(excinfo.value, "_unsloth_acl_recovery_lines", [])
assert any("takeown" in line for line in recovery), recovery
assert any("icacls" in line for line in recovery), recovery
assert any("elevated PowerShell" in line for line in recovery), recovery
assert any(str(source) in line for line in recovery), recovery
assert not any("takeown" in line and "icacls" in line for line in recovery), recovery
assert "takeown" not in "".join(capsys.readouterr())
def test_a_denied_marker_write_offers_no_repair_for_its_temp_file(monkeypatch, tmp_path, capsys):
# The source is a temp file about to be removed: nothing to repair.
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
monkeypatch.setattr(M.os, "replace", lambda s, d: (_ for _ in ()).throw(_oserror(5)))
marker = M.metadata_path(tmp_path)
temp = marker.with_name(marker.name + ".tmp-denied")
temp.write_text("{}", encoding = "utf-8")
with pytest.raises(OSError) as excinfo:
M.atomic_replace_from_tempfile(temp, marker)
assert excinfo.value.winerror == 5
assert not getattr(excinfo.value, "_unsloth_acl_recovery_lines", None)
assert "takeown" not in "".join(capsys.readouterr())
def test_replace_does_not_blame_a_scanner_for_access_denied(monkeypatch, tmp_path, capsys):
"""The per-retry line for a 5 offers both causes rather than asserting the scanner."""
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
monkeypatch.setattr(M.os, "replace", lambda s, d: (_ for _ in ()).throw(_oserror(5)))
with pytest.raises(OSError):
M._replace_with_retry(tmp_path / "src", tmp_path / "dst", attempts = 2)
retry_lines = [
line for line in "".join(capsys.readouterr()).splitlines() if "retrying in" in line
]
assert retry_lines, "the retry itself must still be logged"
for line in retry_lines:
assert "is likely still holding" not in line, line
assert "ACLs" in line, line
def test_replace_keeps_the_scanner_message_for_a_sharing_violation(monkeypatch, tmp_path, capsys):
"""WinError 32 is unambiguous, so its scanner message wording is kept as-is on a sharing violation."""
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
monkeypatch.setattr(M.os, "replace", lambda s, d: (_ for _ in ()).throw(_oserror(32)))
with pytest.raises(OSError):
M._replace_with_retry(tmp_path / "src", tmp_path / "dst", attempts = 2)
output = "".join(capsys.readouterr())
assert "a scanner is likely still holding the extracted files" in output
assert "takeown" not in output
def test_replace_does_not_retry_a_genuine_error(monkeypatch, tmp_path):
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
calls = {"n": 0}
def hard_fail(src, dst):
calls["n"] += 1
raise _oserror(17) # ERROR_NOT_SAME_DEVICE
monkeypatch.setattr(M.os, "replace", hard_fail)
with pytest.raises(OSError):
M._replace_with_retry(tmp_path / "src", tmp_path / "dst")
assert calls["n"] == 1
def test_replace_is_a_plain_rename_on_posix(monkeypatch, tmp_path):
# POSIX has no sharing violations, so the retry must add no latency there.
monkeypatch.setattr(M.os, "name", "posix")
calls = {"n": 0}
def once(src, dst):
calls["n"] += 1
raise _oserror(5)
monkeypatch.setattr(M.os, "replace", once)
with pytest.raises(OSError):
M._replace_with_retry(tmp_path / "src", tmp_path / "dst")
assert calls["n"] == 1
def test_swap_into_place_survives_a_transient_lock(monkeypatch, tmp_path):
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
extracted = tmp_path / "extracted" / "node-v24"
extracted.mkdir(parents = True)
(extracted / "marker.txt").write_text("node", encoding = "utf-8")
install_dir = tmp_path / "node"
real_replace = os.replace
state = {"failed": False}
def flaky(src, dst):
if not state["failed"]:
state["failed"] = True
raise _oserror(32)
real_replace(src, dst)
monkeypatch.setattr(M.os, "replace", flaky)
M._swap_into_place(extracted, install_dir)
assert (install_dir / "marker.txt").read_text(encoding = "utf-8") == "node"
def test_a_denial_in_the_cache_is_reported_against_the_cache(capsys, tmp_path):
install_dir = tmp_path / "node"
exc = PermissionError(
13, "Access is denied", str(install_dir / "UNSLOTH_NODE_PREBUILT_INFO.json")
)
assert M._report_access_denied(exc, install_dir) == M.EXIT_DENIED
logged = "".join(capsys.readouterr())
assert f"{M.DENIED_PATH_MARKER}{install_dir / 'UNSLOTH_NODE_PREBUILT_INFO.json'}" in logged
assert f"{M.DENIED_SCOPE_MARKER}{M.DENIED_SCOPE_INSTALL_DIR}" in logged
assert "not a download problem" in logged
def test_a_denial_on_the_lock_is_reported_against_the_parent(capsys, tmp_path):
# The lock and .staging root live one level up, so setup.ps1 would name the wrong dir to delete.
install_dir = tmp_path / "node"
exc = PermissionError(13, "Access is denied", str(M.install_lock_path(install_dir)))
assert M._report_access_denied(exc, install_dir) == M.EXIT_DENIED
assert f"{M.DENIED_SCOPE_MARKER}{M.DENIED_SCOPE_PARENT}" in "".join(capsys.readouterr())
def test_a_denial_without_a_filename_still_exits_denied(capsys, tmp_path):
assert M._report_access_denied(PermissionError(13, "Access is denied"), tmp_path / "node") == (
M.EXIT_DENIED
)
assert M.DENIED_SCOPE_MARKER not in "".join(capsys.readouterr())
def _real_node_tree(root: Path, host) -> None:
"""Real node and npm-cli files, executable; the recorded fast path refuses a node it could not run."""
node = M.node_binary_path(root, host)
npm = M.npm_cli_path(root, host)
node.parent.mkdir(parents = True, exist_ok = True)
npm.parent.mkdir(parents = True, exist_ok = True)
node.write_bytes(b"node" * 64)
npm.write_bytes(b"npm" * 64)
node.chmod(0o755)
def test_a_verified_install_is_not_re_probed(tmp_path: Path, monkeypatch):
"""A verified node install is not re-probed: running node -v on a 110 MB runtime on every
install re-derives an answer that cannot change while the binary is unchanged."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
spawns = []
monkeypatch.setattr(
M, "installed_node_version", lambda d, h: (spawns.append("node"), "24.17.0")[1]
)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: (spawns.append("npm"), 11)[1])
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
assert spawns == ["node", "npm"]
spawns.clear()
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
# `node -v` is saved; npm is re-probed, since the record covers the launcher, not the tree.
assert spawns == ["npm"], "the recorded verification was not believed"
def _runnable_node_tree(
root: Path,
host,
*,
version = "v24.17.0",
npm = "11.0.0",
) -> Path:
"""Runnable node: _run_node execs node for both probes, so the record may skip only the first."""
node = M.node_binary_path(root, host)
npm_cli = M.npm_cli_path(root, host)
node.parent.mkdir(parents = True, exist_ok = True)
npm_cli.parent.mkdir(parents = True, exist_ok = True)
# Padded to a fixed length so a later rewrite can preserve the byte count exactly.
script = f'#!/bin/sh\ncase "$1" in -v) echo {version} ;; *) echo {npm} ;; esac\n'
node.write_text(script.ljust(512), encoding = "utf-8")
node.chmod(0o755)
npm_cli.write_text("// npm launcher\n", encoding = "utf-8")
return node
@pytest.mark.skipif(os.name == "nt", reason = "the stand-in node is a shell script")
def test_a_node_that_no_longer_runs_is_caught_even_at_the_recorded_size_and_mtime(
tmp_path: Path, monkeypatch
):
"""The record compares size and mtime_ns, not the digest; a rewrite that preserves both is still
caught when the node can no longer run, because the node and npm-cli.js spawn probes are
never skipped."""
host = _host("linux", "x64")
node = _runnable_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
recorded = M.load_metadata(tmp_path)["node_binary"]
original = node.stat()
node.write_bytes(b"\x00" * original.st_size)
os.utime(node, ns = (original.st_atime_ns, original.st_mtime_ns))
after = node.stat()
assert (after.st_size, after.st_mtime_ns) == (
recorded["size"],
recorded["mtime_ns"],
), "the rewrite must be invisible to the record for this test to mean anything"
# Non-vacuity: the record itself is satisfied, so the rejection comes from the probe.
assert M._recorded_runtime_matches(tmp_path, host, M.load_metadata(tmp_path), "24.17.0") is True
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
@pytest.mark.skipif(os.name == "nt", reason = "the stand-in node is a shell script")
def test_a_full_check_over_an_unchanged_install_does_not_rewrite_the_marker(
tmp_path: Path, monkeypatch
):
"""UNSLOTH_PREBUILT_FULL_CHECK re-proves what the record already says, on every run.
Publishing an identical marker each time moves its mtime and inode and re-applies its
mode and owner, which is a write, a chmod and a chown for bytes that did not change."""
host = _host("linux", "x64")
_runnable_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
monkeypatch.setenv("UNSLOTH_PREBUILT_FULL_CHECK", "1")
marker = M.metadata_path(tmp_path)
before = marker.stat()
for _ in range(3):
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
after = marker.stat()
assert (after.st_ino, after.st_mtime_ns) == (
before.st_ino,
before.st_mtime_ns,
), "an unchanged record was republished"
def test_a_replaced_binary_is_probed_again(tmp_path: Path, monkeypatch):
"""The record describes bytes, not a directory: a node swapped underneath us has
to answer for itself."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
spawns = []
monkeypatch.setattr(
M, "installed_node_version", lambda d, h: (spawns.append("node"), "24.17.0")[1]
)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: (spawns.append("npm"), 11)[1])
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
assert spawns == ["npm"]
spawns.clear()
M.node_binary_path(tmp_path, host).write_bytes(b"a different node")
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
assert spawns == ["node", "npm"]
def test_a_deleted_binary_is_not_a_match(tmp_path: Path, monkeypatch):
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
M.npm_cli_path(tmp_path, host).unlink()
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: None)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
def test_a_recorded_verification_never_outranks_the_version_or_the_pin(tmp_path: Path, monkeypatch):
"""The short-circuit is only about the two spawns. Version and digest are still
what decide whether this is the install that was asked for."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "pinned")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
assert M.existing_install_matches(tmp_path, host, version = "24.18.0") is False
assert (
M.existing_install_matches(tmp_path, host, version = "24.17.0", expected_sha = "other") is False
)
assert (
M.existing_install_matches(tmp_path, host, version = "24.17.0", expected_sha = "pinned") is True
)
def test_a_recorded_npm_below_the_floor_is_probed_again(tmp_path: Path, monkeypatch):
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 10)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 10)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
# os.access X_OK reads POSIX mode bits, which root ignores and Windows lacks.
_EXECUTE_BIT_IS_ENFORCED = os.name != "nt" and getattr(os, "geteuid", lambda: 0)() != 0
@pytest.mark.skipif(
not _EXECUTE_BIT_IS_ENFORCED,
reason = "needs an unprivileged POSIX user: root and Windows both ignore the execute bit",
)
def test_a_node_that_lost_its_execute_bit_is_not_a_match(tmp_path: Path, monkeypatch):
"""Dropping the execute bit moves only ctime, so the size and mtime_ns record still matches; the
spawn it stands in for would fail, and the install must be repaired."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
node = M.node_binary_path(tmp_path, host)
before = node.stat()
node.chmod(0o644)
after = node.stat()
assert (after.st_size, after.st_mtime_ns) == (before.st_size, before.st_mtime_ns)
# The record itself still matches, which is exactly why the mode has to be asked for.
assert M._file_record_matches(node, M.load_metadata(tmp_path)["node_binary"]) is True
assert (
M._recorded_runtime_matches(tmp_path, host, M.load_metadata(tmp_path), "24.17.0") is False
)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: None)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
def test_an_execute_bit_is_not_demanded_of_the_npm_launcher(tmp_path: Path, monkeypatch):
"""npm-cli.js is read by node, not executed, so its mode says nothing about npm."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
M.npm_cli_path(tmp_path, host).chmod(0o644)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
assert M._recorded_runtime_matches(tmp_path, host, M.load_metadata(tmp_path), "24.17.0") is True
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
def test_a_recorded_install_whose_npm_tree_was_gutted_is_not_a_match(tmp_path: Path, monkeypatch):
"""The record cannot see a gutted npm/lib/cli.js, so the npm probe is still paid on the recorded
path."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
cli_js = M.npm_cli_path(tmp_path, host).parent.parent / "lib" / "cli.js"
cli_js.parent.mkdir(parents = True, exist_ok = True)
cli_js.write_bytes(b"module.exports = () => {};\n")
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
launcher_before = M.npm_cli_path(tmp_path, host).read_bytes()
# Stands in for the real spawn: node loads the launcher, which requires ../lib/cli.js.
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11 if cli_js.exists() else None)
monkeypatch.setattr(
M, "installed_node_version", lambda d, h: pytest.fail("`node -v` should stay saved")
)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
cli_js.unlink()
assert M.npm_cli_path(tmp_path, host).read_bytes() == launcher_before
assert M._recorded_runtime_matches(tmp_path, host, M.load_metadata(tmp_path), "24.17.0") is True
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
def test_the_healthy_recorded_case_never_spawns_node_v(tmp_path: Path, monkeypatch):
"""The saved `node -v` is the whole point of the record; losing it is a silent revert."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
probes = []
monkeypatch.setattr(
M, "installed_node_version", lambda d, h: pytest.fail("`node -v` was spawned")
)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: (probes.append("npm"), 11)[1])
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
assert probes == ["npm"]
def test_the_record_survives_an_unwritable_marker(tmp_path: Path):
"""A marker that cannot be refreshed costs the two spawns again, never the install."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
assert M.load_metadata(tmp_path) is None
def test_a_failed_marker_refresh_leaves_the_old_marker_intact(tmp_path: Path, monkeypatch):
"""Marker rewrites must be atomic: a truncated marker reads as no install and forces a re-download."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
before = M.metadata_path(tmp_path).read_bytes()
def boom(tmp, destination):
raise OSError(28, "No space left on device")
monkeypatch.setattr(M, "atomic_replace_from_tempfile", boom)
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
assert M.metadata_path(tmp_path).read_bytes() == before
assert M.load_metadata(tmp_path) is not None
# A stranded sibling would sit there forever, and _swap_into_place would carry it live.
assert list(tmp_path.glob(M.METADATA_FILENAME + ".tmp-*")) == []
def test_the_marker_is_never_written_in_place(tmp_path: Path, monkeypatch):
"""What makes the guarantee above true: the payload is complete on disk in a
sibling before the destination is touched at all."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
original = M.metadata_path(tmp_path).read_bytes()
seen = {}
real = M.atomic_replace_from_tempfile
def observe(tmp, destination):
seen["destination"] = Path(destination).read_bytes()
seen["staged"] = json.loads(Path(tmp).read_text(encoding = "utf-8"))
return real(tmp, destination)
monkeypatch.setattr(M, "atomic_replace_from_tempfile", observe)
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
assert seen["destination"] == original, "the destination was written before the replace"
assert seen["staged"]["npm_major_checked"] == 11
assert M.load_metadata(tmp_path)["npm_major_checked"] == 11
def test_the_marker_bytes_are_unchanged_by_the_atomic_writer(tmp_path: Path):
"""The setup fast path and the idempotency harness both compare this file byte for
byte, so moving the writer must not re-spell it."""
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
payload = {
"schema_version": M.METADATA_SCHEMA_VERSION,
"kind": "node",
"version": "24.17.0",
"asset": "x",
"sha256": "y",
}
expected = json.dumps(payload, indent = 2) + "\n"
assert M.metadata_path(tmp_path).read_text(encoding = "utf-8") == expected
def test_a_failed_install_marker_write_strands_nothing(tmp_path: Path, monkeypatch):
"""write_metadata still raises -- it writes into a staging tree the caller discards
-- but it must not leave the temp file behind in it either."""
def boom(tmp, destination):
raise OSError(28, "No space left on device")
monkeypatch.setattr(M, "atomic_replace_from_tempfile", boom)
with pytest.raises(OSError):
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
assert not M.metadata_path(tmp_path).exists()
assert list(tmp_path.glob(M.METADATA_FILENAME + ".tmp-*")) == []
def test_both_marker_writers_share_one_atomic_path() -> None:
"""Two spellings of "write the marker" is how one of them would stay non-atomic."""
source = MODULE_PATH.read_text(encoding = "utf-8")
assert source.count("_write_metadata_payload(") == 3 # def + write_metadata + refresh
assert "metadata_path(install_dir).write_text(" not in source
def test_the_record_is_written_after_the_swap_not_before() -> None:
"""_ensure_npm_floor rewrites npm inside the staged tree, so a record taken there
describes bytes that are about to be replaced."""
source = MODULE_PATH.read_text(encoding = "utf-8")
swap = source.index("_swap_into_place(extracted_root, install_dir)")
record = source.index(
"_record_runtime_verification_under_lock(\n install_dir, host, installed_meta, version = final_version"
)
assert swap < record
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX modes")
def test_a_marker_refresh_keeps_the_marker_readable_to_other_users(tmp_path: Path):
"""NamedTemporaryFile is 0600 and os.replace keeps the source file's mode, so the
first runtime-verification refresh used to leave a shared install's marker readable
only by whoever ran it, and every other user's update read "nothing installed"."""
import stat as _stat
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
marker = M.metadata_path(tmp_path)
mask = os.umask(0)
os.umask(mask)
assert _stat.S_IMODE(marker.stat().st_mode) == 0o666 & ~mask
marker.chmod(0o664)
M.record_runtime_verification(tmp_path, host, version = "24.17.0", npm_major = 11)
assert M.load_metadata(tmp_path)["node_version_checked"] == "24.17.0"
assert _stat.S_IMODE(marker.stat().st_mode) == 0o664
def test_the_pre_lock_record_is_written_under_the_lock_and_only_over_the_marker_it_read(
tmp_path: Path, monkeypatch
):
"""The pre-lock record takes the install lock and writes only if the marker is still the one it read."""
host = _host("linux", "x64")
_real_node_tree(tmp_path, host)
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
monkeypatch.setattr(M, "installed_node_version", lambda d, h: "24.17.0")
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
held = {"depth": 0, "writes_under_lock": 0}
real_lock = M.install_lock
real_record = M.record_runtime_verification
@contextlib.contextmanager
def counting_lock(path, **kwargs):
with real_lock(path, **kwargs):
held["depth"] += 1
try:
yield
finally:
held["depth"] -= 1
def counting_record(*args, **kwargs):
assert held["depth"], "the record was written outside the install lock"
held["writes_under_lock"] += 1
real_record(*args, **kwargs)
monkeypatch.setattr(M, "install_lock", counting_lock)
monkeypatch.setattr(M, "record_runtime_verification", counting_record)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is True
assert held["writes_under_lock"] == 1
assert M.load_metadata(tmp_path)["node_version_checked"] == "24.17.0"
# The marker changes hands while the lock is being taken: no record over it.
M.write_metadata(tmp_path, version = "24.17.0", asset = "x", sha256 = "y")
@contextlib.contextmanager
def swapping_lock(path, **kwargs):
with real_lock(path, **kwargs):
M.write_metadata(tmp_path, version = "24.18.0", asset = "z", sha256 = "w")
yield
monkeypatch.setattr(M, "install_lock", swapping_lock)
assert M.existing_install_matches(tmp_path, host, version = "24.17.0") is False
after = M.load_metadata(tmp_path)
assert after["version"] == "24.18.0"
assert "node_version_checked" not in after
@pytest.mark.skipif(not hasattr(os, "chown"), reason = "os.chown is POSIX only")
def test_a_refreshed_marker_keeps_its_owner_and_group(tmp_path, monkeypatch):
"""os.replace installs the temp file's ownership; a group-shared marker refreshed by
another member must not take that member's group and stop being readable."""
install_dir = tmp_path / "node"
install_dir.mkdir()
marker = M.metadata_path(install_dir)
marker.write_text("{}", encoding = "utf-8")
original = marker.stat()
chowned = []
def refusing(path, uid, gid):
chowned.append((uid, gid))
if uid != -1:
raise PermissionError("a non-root member may not give a file away")
monkeypatch.setattr(M.os, "chown", refusing)
M._write_metadata_payload(install_dir, {"kind": "node"})
# Owner+group first (root can restore both); group alone for a non-root group-shared install.
assert chowned == [(original.st_uid, original.st_gid), (-1, original.st_gid)]
chowned.clear()
marker.unlink()
M._write_metadata_payload(install_dir, {"kind": "node"})
assert chowned == []
def test_a_busy_install_lock_keeps_the_verified_install(tmp_path, monkeypatch):
"""A busy install lock is not evidence of a swap; only a changed marker is, so the install stays."""
waited = {}
def busy(_path, *, timeout = None):
waited["timeout"] = timeout
raise M.BusyInstallConflict("held elsewhere")
monkeypatch.setattr(M, "install_lock", busy)
assert (
M._record_runtime_verification_under_lock(
tmp_path, object(), {"version": "v22.0.0"}, version = "v22.0.0", npm_major = 10
)
is True
)
# ...and it does not hold the launch for the install timeout to write an optimisation.
assert waited["timeout"] == M.RECORD_LOCK_TIMEOUT_SECONDS
assert M.RECORD_LOCK_TIMEOUT_SECONDS < M.INSTALL_LOCK_TIMEOUT_SECONDS
def test_a_tree_replaced_under_the_lock_is_still_not_a_match(tmp_path, monkeypatch):
"""The half that DOES answer: the lock was taken, and the marker had changed hands."""
install_dir = tmp_path / "node"
install_dir.mkdir()
M.metadata_path(install_dir).write_text(
json.dumps({"version": "v22.9.9", "sha256": "b" * 64, "asset": "other.tar.xz"}),
encoding = "utf-8",
)
recorded = []
monkeypatch.setattr(M, "record_runtime_verification", lambda *a, **k: recorded.append(a))
assert (
M._record_runtime_verification_under_lock(
install_dir,
object(),
{"version": "v22.0.0", "sha256": "a" * 64, "asset": "node.tar.xz"},
version = "v22.0.0",
npm_major = 10,
)
is False
)
assert recorded == [], "a record was written over another installer's tree"
def test_swap_into_place_reports_the_managed_parent_on_destination_denial(
monkeypatch, tmp_path, capsys
):
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
extracted = tmp_path / "staging" / "node-v24"
extracted.mkdir(parents = True)
install_dir = tmp_path / "managed" / "node"
def destination_denied(src, dst):
assert src == extracted
assert dst == install_dir
raise _oserror(5)
monkeypatch.setattr(M.os, "replace", destination_denied)
with pytest.raises(OSError) as excinfo:
M._swap_into_place(extracted, install_dir)
recovery = excinfo.value._unsloth_acl_recovery_lines
assert any(f'takeown /F "{extracted}"' in line for line in recovery), recovery
assert any(f'takeown /F "{install_dir.parent}"' in line for line in recovery), recovery
assert any("elevated PowerShell" in line for line in recovery), recovery
def test_swap_into_place_reports_the_managed_parent_when_aside_is_denied(
monkeypatch, tmp_path, capsys
):
monkeypatch.setattr(M.os, "name", "nt")
monkeypatch.setattr(M.time, "sleep", lambda _s: None)
extracted = tmp_path / "staging" / "node-v24"
extracted.mkdir(parents = True)
install_dir = tmp_path / "managed" / "node"
install_dir.mkdir(parents = True)
def aside_denied(src, dst):
assert src == install_dir
assert dst.parent == install_dir.parent
raise _oserror(5)
monkeypatch.setattr(M.os, "replace", aside_denied)
with pytest.raises(OSError) as excinfo:
M._swap_into_place(extracted, install_dir)
recovery = excinfo.value._unsloth_acl_recovery_lines
assert f' takeown /F "{install_dir}" /R /D Y' in recovery
parent_takeown = f'takeown /F "{install_dir.parent}"'
assert any(parent_takeown in line for line in recovery), recovery
assert not any(parent_takeown in line and " /R " in line for line in recovery), recovery
def test_detect_host_without_lzma_keeps_tar_gz(monkeypatch):
monkeypatch.setattr(M.platform, "system", lambda: "Linux")
monkeypatch.setattr(M.platform, "machine", lambda: "x86_64")
monkeypatch.delitem(sys.modules, "lzma", raising = False)
monkeypatch.setitem(sys.modules, "_lzma", None)
assert M.detect_host().archive_ext == ".tar.gz"
def test_every_pinned_tar_gz_has_a_tar_xz():
for assets in M.load_pins()["versions"].values():
for name in assets:
if name.endswith(".tar.gz"):
assert name.replace(".tar.gz", ".tar.xz") in assets
def test_extract_tar_xz(tmp_path):
root = tmp_path / "src" / "node"
(root / "bin").mkdir(parents = True)
(root / "bin" / "node").write_text("x")
archive = tmp_path / "node.tar.xz"
with tarfile.open(archive, "w:xz") as tar:
tar.add(root, arcname = "node")
M.extract_archive(archive, tmp_path / "out")
assert (tmp_path / "out" / "node" / "bin" / "node").read_text() == "x"
def test_tar_gz_install_is_kept_after_the_switch_to_tar_xz(tmp_path, monkeypatch):
pins = {
"versions": {
"1.0.0": {
"node-v1.0.0-linux-x64.tar.gz": "a" * 64,
"node-v1.0.0-linux-x64.tar.xz": "b" * 64,
"node-v1.0.0-linux-arm64.tar.gz": "c" * 64,
}
}
}
asset = "node-v1.0.0-linux-x64.tar.xz"
monkeypatch.setattr(M, "load_metadata", lambda d: {"asset": "node-v1.0.0-linux-x64.tar.gz"})
assert M.pin_to_keep(pins, "1.0.0", asset, tmp_path) == "a" * 64
monkeypatch.setattr(M, "load_metadata", lambda d: {"asset": "node-v1.0.0-linux-arm64.tar.gz"})
assert M.pin_to_keep(pins, "1.0.0", asset, tmp_path) == "b" * 64
monkeypatch.setattr(M, "load_metadata", lambda d: None)
assert M.pin_to_keep(pins, "1.0.0", asset, tmp_path) == "b" * 64
monkeypatch.setattr(M, "load_metadata", lambda d: {"asset": "node-v1.0.0-linux-x64.tar.zst"})
assert M.pin_to_keep(pins, "1.0.0", asset, tmp_path) == "b" * 64
def test_mirror_without_tar_xz_falls_back_to_pinned_tar_gz(tmp_path, monkeypatch):
install_dir = tmp_path / "node"
version = M.pinned_default_version(M.load_pins())
host = dataclasses.replace(_host("linux", "x64"), archive_ext = ".tar.xz")
monkeypatch.setattr(M, "detect_host", lambda: host)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
monkeypatch.setattr(M, "_ensure_npm_floor", lambda d, h: None)
fetched = []
def fake_download(url, path, **kw):
fetched.append(path.name)
if path.name.endswith(".tar.xz"):
raise OSError("HTTP Error 404: Not Found")
path.write_bytes(b"gz")
monkeypatch.setattr(M, "download_file_verified", fake_download)
monkeypatch.setattr(
M, "extract_archive", lambda a, d: (d / "node-root" / "bin").mkdir(parents = True)
)
assert M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False) == 0
gz = f"node-v{version}-linux-x64.tar.gz"
assert fetched == [f"node-v{version}-linux-x64.tar.xz", gz]
meta = M.load_metadata(install_dir)
assert meta["asset"] == gz
assert meta["sha256"] == M.pinned_sha256(M.load_pins(), version, gz)
def test_format_switched_by_another_installer_while_waiting_is_kept(tmp_path, monkeypatch):
install_dir = tmp_path / "node"
install_dir.mkdir()
pins = M.load_pins()
version = M.pinned_default_version(pins)
gz, xz = (f"node-v{version}-linux-x64.tar.{ext}" for ext in ("gz", "xz"))
M.write_metadata(install_dir, version = version, asset = gz, sha256 = "stale")
host = dataclasses.replace(_host("linux", "x64"), archive_ext = ".tar.xz")
monkeypatch.setattr(M, "detect_host", lambda: host)
monkeypatch.setattr(M, "installed_node_version", lambda d, h: version)
monkeypatch.setattr(M, "installed_npm_major", lambda d, h: 11)
real_lock = M.install_lock
@contextlib.contextmanager
def lock_after_other_installer(path):
M.write_metadata(
install_dir, version = version, asset = xz, sha256 = M.pinned_sha256(pins, version, xz)
)
with real_lock(path):
yield
monkeypatch.setattr(M, "install_lock", lock_after_other_installer)
monkeypatch.setattr(M, "download_file_verified", lambda *a, **k: pytest.fail("downloaded"))
assert M.install_prebuilt(install_dir, channel = "pinned", min_major = 24, force = False) == 0