blob: 7440b3534885cbb17a18957aef7f946313133fac [file]
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""`magpie-python`: the launcher every Magpie start goes through, and its checks."""
import os
import pwd
import re
import shutil
import subprocess
from pathlib import Path
from typing import Any
import pytest
from setup_preflight import sections
from setup_preflight.python_runtime import LAUNCHER_VERSION, REQUIRED_PYTHON, findings
REPO_ROOT = Path(__file__).resolve().parents[3]
LAUNCHER = REPO_ROOT / "plugins/magpie-setup/bin/magpie-python"
#: The suite's conftest points HOME at a temporary directory; the launcher
#: tells home from a checkout by HOME, so it runs with the real one.
REAL_HOME = pwd.getpwuid(os.getuid()).pw_dir
def _runner(stdout: str, returncode: int = 0) -> Any:
def run(argv: list[str], **_: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(argv, returncode, stdout, "")
return run
# --- the pre-flight check ---------------------------------------------------------
def test_the_shipped_launcher_is_not_a_finding() -> None:
assert (
findings(which=lambda _: "/home/u/.local/bin/magpie-python", run=_runner(f"{LAUNCHER_VERSION}\n"))
== []
)
def test_an_older_launcher_is_reported() -> None:
(found,) = findings(which=lambda _: "/home/u/.local/bin/magpie-python", run=_runner("0\n"))
assert (found.scope, found.code, found.section) == ("machine", "launcher-outdated", "launcher-outdated")
assert found.facts == {
"installed": "0",
"expected": LAUNCHER_VERSION,
"path": "/home/u/.local/bin/magpie-python",
}
def test_a_launcher_that_cannot_say_its_version_is_reported_as_unknown() -> None:
(found,) = findings(which=lambda _: "/x/magpie-python", run=_runner("", returncode=2))
assert found.facts["installed"] == "unknown"
def test_no_launcher_on_path_is_left_to_the_block() -> None:
# Pre-flight cannot start through a launcher that is not there; the block's
# rules handle that case, so the Python check has nothing to add.
assert findings(which=lambda _: None, run=_runner("1\n")) == []
def test_the_finding_has_its_rules() -> None:
assert "launcher-outdated" in sections.available()
assert "/magpie-setup:upgrade" in sections.load("launcher-outdated")
# --- the launcher itself ----------------------------------------------------------
def test_the_check_expects_the_shipped_launcher_version() -> None:
text = LAUNCHER.read_text(encoding="utf-8")
assert re.search(rf"^MAGPIE_PYTHON_LAUNCHER_VERSION={LAUNCHER_VERSION}$", text, re.M)
assert re.search(rf"^required={re.escape(REQUIRED_PYTHON)}$", text, re.M)
def test_the_required_python_is_the_workspace_interpreter() -> None:
assert (REPO_ROOT / ".python-version").read_text(encoding="utf-8").strip() == REQUIRED_PYTHON
def test_the_launcher_reports_its_version() -> None:
done = subprocess.run(
["sh", str(LAUNCHER), "--launcher-version"], capture_output=True, text=True, check=True
)
assert done.stdout.strip() == LAUNCHER_VERSION
@pytest.mark.skipif(shutil.which("uv") is None, reason="needs uv")
def test_the_launcher_never_runs_the_working_directory_venv(tmp_path: Path) -> None:
# A repository can ship a `.venv`; the launcher must ignore it.
venv = tmp_path / ".venv"
subprocess.run(
["uv", "venv", "--no-config", "--python", REQUIRED_PYTHON, str(venv)], check=True, capture_output=True
)
done = subprocess.run(
["sh", str(LAUNCHER), "-c", "import sys; print(sys.prefix)"],
cwd=tmp_path,
env={**os.environ, "HOME": REAL_HOME},
capture_output=True,
text=True,
check=False,
)
if done.returncode == 2:
pytest.skip("no Python 3.14 installed outside a venv here")
assert done.returncode == 0, done.stderr
assert Path(done.stdout.strip()).resolve() != venv.resolve()
def test_a_missing_python_blocks_with_the_install_command(tmp_path: Path) -> None:
env = {
**os.environ,
"HOME": REAL_HOME,
"UV_PYTHON_INSTALL_DIR": str(tmp_path / "none"),
"UV_PYTHON_PREFERENCE": "only-managed",
}
done = subprocess.run(
["sh", str(LAUNCHER), "-c", "pass"], env=env, capture_output=True, text=True, check=False
)
assert done.returncode == 2 # blocks an agent hook rather than failing open
assert "uv python install 3.14" in done.stderr
UPGRADE_SKILL = REPO_ROOT / "plugins/magpie-setup/skills/upgrade/SKILL.md"
def _section(text: str, heading: str) -> str:
start = text.index(f"\n## {heading}\n")
end = text.find("\n## ", start + 1)
return text[start : end if end != -1 else len(text)]
def test_the_upgrade_checks_the_launcher_before_anything_runs_through_it() -> None:
# Every later upgrade step starts Python through `magpie-python`, so a missing
# launcher has to be caught first, by a step that needs nothing but a shell.
text = UPGRADE_SKILL.read_text(encoding="utf-8")
headings = re.findall(r"^## (.+)$", text, re.M)
assert headings.index("The launcher first") < headings.index("Move the version")
assert headings.index("The launcher first") < headings.index("Gather")
section = _section(text, "The launcher first")
# The launcher is only probed or asked its version here, never used to run
# Magpie code, and no other interpreter starts.
calls = re.findall(r"(?<![/\w-])magpie-python\s+([^\s`]+(?:\s+[^\s`]+)?)", section)
assert "-c pass" in calls, calls
assert all(
call in ("-c pass", "--launcher-version") or call.startswith("--launcher-version") for call in calls
), calls
for start in ("python3", "setup_preflight", "uvx ", "uv run"):
assert start not in section, start
assert not re.search(r"python\S*\s+(?:-\w+\s+)*-m\b", section), (
"a module runs before the launcher is known"
)
def test_a_snapshot_install_fetches_the_launcher_by_ref_and_compares_it_first() -> None:
# A pinned snapshot or checkout sits in the sandbox-writable project, so its
# copy is installed only when it matches apache/magpie at the lock's ref.
assert "launcher.md" in _section(UPGRADE_SKILL.read_text(encoding="utf-8"), "The launcher first")
section = (UPGRADE_SKILL.parent / "launcher.md").read_text(encoding="utf-8")
url = "https://raw.githubusercontent.com/apache/magpie/<ref>/plugins/magpie-setup/bin/magpie-python"
assert url in section
fetch, compare, install = section.index(url), section.index("cmp "), section.index('install -m 0755 "$t"')
assert fetch < compare < install
assert not re.search(r"\b[0-9a-f]{40}\b", section), "a commit id can be served by a fork"
assert "never a commit id" in section
def test_a_missing_uv_blocks_with_where_to_get_it(tmp_path: Path) -> None:
env = {**os.environ, "HOME": REAL_HOME, "PATH": str(tmp_path)}
done = subprocess.run(
["/bin/sh", str(LAUNCHER), "-c", "pass"], env=env, capture_output=True, text=True, check=False
)
assert done.returncode == 2
assert "docs.astral.sh/uv" in done.stderr
# --- nothing the sandbox can write decides what runs ------------------------------
def _managed_python() -> Path | None:
"""A uv-managed 3.14 install (relocatable, so a copy of it still runs), or None."""
if shutil.which("uv") is None:
return None
done = subprocess.run(
["uv", "python", "find", "--no-config", "--managed-python", REQUIRED_PYTHON],
capture_output=True,
text=True,
check=False,
)
if done.returncode != 0:
return None
return Path(done.stdout.strip()).resolve().parents[1]
def _plant(tmp_path: Path) -> Path:
"""A working Python 3.14 copied under a temporary (sandbox-writable) directory."""
install = _managed_python()
if install is None:
pytest.skip("needs a uv-managed Python 3.14 to copy")
copy = tmp_path / "planted"
shutil.copytree(install, copy, symlinks=True)
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
(bin_dir / "python3.14").symlink_to(copy / "bin" / "python3.14")
return bin_dir
def test_a_python_planted_first_on_path_is_skipped(tmp_path: Path) -> None:
bin_dir = _plant(tmp_path)
env = {**os.environ, "HOME": REAL_HOME, "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}"}
done = subprocess.run(
["sh", str(LAUNCHER), "-c", "import sys; print(sys.executable)"],
env=env,
capture_output=True,
text=True,
check=False,
)
assert done.returncode == 0, done.stderr
assert not Path(done.stdout.strip()).resolve().is_relative_to(tmp_path.resolve())
def test_only_a_planted_python_is_refused(tmp_path: Path) -> None:
bin_dir = _plant(tmp_path)
# uv alone in a directory, not uv's own: `uv python install` links a real
# python3.14 beside a standalone uv (~/.local/bin), and the launcher would
# rightly run that one instead of refusing the planted copy.
uv_dir = tmp_path / "uv-only"
uv_dir.mkdir()
(uv_dir / "uv").symlink_to(Path(shutil.which("uv") or "uv").resolve())
env = {
**os.environ,
"HOME": REAL_HOME,
"PATH": f"{bin_dir}{os.pathsep}{uv_dir}{os.pathsep}/usr/bin{os.pathsep}/bin",
# An empty install directory: uv sees no managed Python, only PATH's.
"UV_PYTHON_INSTALL_DIR": str(tmp_path / "none"),
# uv colours its listing under FORCE_COLOR (as in CI); the launcher
# must still read the paths out of it.
"FORCE_COLOR": "1",
}
# The test needs uv to list the planted copy at all; where it cannot run
# one (a noexec temporary directory, say) the launcher would rightly say
# "not installed", which proves nothing about refusing it.
seen = subprocess.run(
["uv", "python", "list", "--only-installed", "--no-config", "--color", "never", REQUIRED_PYTHON],
env=env,
capture_output=True,
text=True,
check=False,
)
if str(bin_dir) not in seen.stdout:
pytest.skip(f"uv does not list the planted copy here: {seen.stdout.strip() or seen.stderr.strip()}")
done = subprocess.run(
["sh", str(LAUNCHER), "-c", "pass"], env=env, capture_output=True, text=True, check=False
)
if "sandbox can write" not in done.stderr:
traced = subprocess.run(
["sh", "-x", str(LAUNCHER), "-c", "pass"], env=env, capture_output=True, text=True, check=False
)
pytest.fail(f"uv listed:\n{seen.stdout}\nthe launcher, traced:\n{traced.stderr[-6000:]}")
assert done.returncode == 2
assert "uv python install 3.14" in done.stderr
@pytest.mark.parametrize("start", ["home", "above-home"])
def test_a_start_in_home_or_above_is_refused(tmp_path: Path, start: str) -> None:
# The sandbox can write the directory a session starts in; from home, or a
# parent of it, that is every Python under home, ~/.local/bin included.
home = tmp_path / "home" / "someone"
home.mkdir(parents=True)
cwd = home if start == "home" else home.parent
done = subprocess.run(
["sh", str(LAUNCHER), "-c", "pass"],
cwd=cwd,
env={**os.environ, "HOME": str(home)},
capture_output=True,
text=True,
check=False,
)
assert done.returncode == 2
assert "holds your home directory" in done.stderr
assert done.stdout == ""
def test_the_launcher_needs_no_temporary_file() -> None:
# sh writes a here-document to a temporary file; where it cannot (inside
# the sandbox) a here-document loop sees an empty list, and an empty list of
# sandbox-writable directories would let every interpreter through.
code = [
line
for line in LAUNCHER.read_text(encoding="utf-8").splitlines()
if not line.lstrip().startswith("#")
]
assert not any("<<" in line for line in code)
@pytest.mark.parametrize("shell", ["sh", "dash"])
def test_the_launcher_runs_under_posix_shells(shell: str) -> None:
if shutil.which(shell) is None:
pytest.skip(f"no {shell} here")
done = subprocess.run(
[shell, str(LAUNCHER), "-c", "import sys; print(sys.version_info[:2])"],
env={**os.environ, "HOME": REAL_HOME},
capture_output=True,
text=True,
check=False,
)
if done.returncode == 2 and "not installed" in done.stderr:
pytest.skip("no Python 3.14 installed outside a venv here")
assert done.returncode == 0, done.stderr
assert done.stdout.strip() == "(3, 14)"
@pytest.mark.parametrize("start", [["-m", "magpie_probe"], ["-c", "import magpie_probe"]])
def test_a_package_planted_in_the_working_directory_is_not_imported(tmp_path: Path, start: list[str]) -> None:
# `-m` and `-c` put the working directory first on sys.path, ahead of
# PYTHONPATH; for a skill it is someone else's repository.
planted = tmp_path / "repo" / "magpie_probe"
planted.mkdir(parents=True)
(planted / "__init__.py").write_text("print('PLANTED')\n", encoding="utf-8")
(planted / "__main__.py").write_text("", encoding="utf-8")
real = tmp_path / "src" / "magpie_probe"
real.mkdir(parents=True)
(real / "__init__.py").write_text("print('REAL')\n", encoding="utf-8")
(real / "__main__.py").write_text("", encoding="utf-8")
done = subprocess.run(
["sh", str(LAUNCHER), *start],
cwd=tmp_path / "repo",
env={**os.environ, "HOME": REAL_HOME, "PYTHONPATH": str(tmp_path / "src")},
capture_output=True,
text=True,
check=False,
)
if done.returncode == 2 and "not installed" in done.stderr:
pytest.skip("no Python 3.14 installed outside a venv here")
assert done.returncode == 0, done.stderr
assert done.stdout.strip() == "REAL"
def test_a_script_still_sees_its_own_directory(tmp_path: Path) -> None:
(tmp_path / "helper.py").write_text("VALUE = 'sibling'\n", encoding="utf-8")
script = tmp_path / "run.py"
script.write_text("import helper\nprint(helper.VALUE)\n", encoding="utf-8")
done = subprocess.run(
["sh", str(LAUNCHER), str(script)],
env={**os.environ, "HOME": REAL_HOME},
capture_output=True,
text=True,
check=False,
)
if done.returncode == 2 and "not installed" in done.stderr:
pytest.skip("no Python 3.14 installed outside a venv here")
assert done.stdout.strip() == "sibling", done.stderr
def test_a_uv_in_a_sandbox_writable_directory_is_refused(tmp_path: Path) -> None:
fake = tmp_path / "uv"
fake.write_text("#!/bin/sh\necho planted\n", encoding="utf-8")
fake.chmod(0o755)
env = {**os.environ, "HOME": REAL_HOME, "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}"}
done = subprocess.run(
["sh", str(LAUNCHER), "-c", "pass"], env=env, capture_output=True, text=True, check=False
)
assert done.returncode == 2
assert "planted" not in done.stdout
assert "sandbox can write" in done.stderr