Files
Defame1297andClaude Sonnet 5.5 b0607a39e2
Build / build (pull_request) Successful in 14s
Molecule / molecule (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 56s
ci(python): one Python (3.14) for the lock, a clone and the ci image
.python-version (3.14) is the source. dev-setup.sh and lock-requirements.sh
require exactly that minor; the ci image builds /opt/venv from its baked
python-build-standalone of that version (ARG PYTHON_VERSION) instead of the
distribution's python3, and derives the python<MINOR> links for
ansible-test from it; `check_image_versions.py pins` fails when
.python-version, the lock header or an `ARG PYTHON_VERSION` differs.
The lock already carries the 3.14 header (Renovate's -full container runs
pip-compile on its own python 3.14.8); renovate.yml now says that python's
minor version must equal .python-version. ci image 0.2.25 -> 0.2.26.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-16 07:42:45 +00:00

372 lines
15 KiB
Python

# Copyright (c) 2026 Mortis
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for scripts/dev-setup.sh against throwaway git repositories.
Python, pip and pre-commit are stubs on a private directory, so nothing is installed
and no network is used. Git is isolated from the real configuration (GIT_CONFIG_GLOBAL
and HOME point into the temporary directory). Skipped when bash or git is missing.
Run: python3 -I -m unittest discover -s tests/scripts
"""
from __future__ import annotations
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "dev-setup.sh"
PYTHON_STUB = """#!/bin/sh
# Stub interpreter: a -c check passes, unless STUB_PY_MINOR is set and the check does not compare against
# that minor version (the pinned-version check of dev-setup.sh); `-m venv DIR` lays out DIR/bin with the stubs.
if [ "$1" = "-c" ]; then
if [ -n "${STUB_PY_MINOR:-}" ]; then
case "$2" in *"== '$STUB_PY_MINOR'"*) exit 0 ;; *) exit 1 ;; esac
fi
exit 0
fi
if [ "$1" = "-m" ] && [ "$2" = "venv" ]; then
mkdir -p "$3/bin"
cp "$STUB_DIR/python" "$3/bin/python"
cp "$STUB_DIR/pip" "$3/bin/pip"
cp "$STUB_DIR/pre-commit" "$3/bin/pre-commit"
cp "$STUB_DIR/ansible-galaxy" "$3/bin/ansible-galaxy"
chmod +x "$3/bin/python" "$3/bin/pip" "$3/bin/pre-commit" "$3/bin/ansible-galaxy"
exit 0
fi
exit 2
"""
# Records the arguments of each call, one line per call.
PIP_STUB = """#!/bin/sh
printf '%s\\n' "$*" >> "$STUB_DIR/pip.log"
exit 0
"""
# Records the collections path and the arguments of each call, one line per call.
GALAXY_STUB = """#!/bin/sh
printf '%s|%s\\n' "${ANSIBLE_COLLECTIONS_PATH:-}" "$*" >> "$STUB_DIR/galaxy.log"
if [ "${STUB_GALAXY_FAIL:-}" = "1" ]; then echo "stub galaxy failure" >&2; exit 1; fi
exit 0
"""
# Mimics `pre-commit install`: refuses when core.hooksPath has any value, otherwise writes
# the two hooks into the repository's hooks directory. The hook body prints PATH.
PRECOMMIT_STUB = """#!/bin/sh
if [ "${STUB_PRECOMMIT_FAIL:-}" = "1" ]; then echo "stub pre-commit failure" >&2; exit 1; fi
if git config --get-all core.hooksPath >/dev/null 2>&1; then
echo "Cannot install: core.hooksPath is set" >&2
exit 1
fi
for h in pre-commit commit-msg pre-push; do
f="$(git rev-parse --path-format=absolute --git-path "hooks/$h")"
mkdir -p "$(dirname "$f")"
printf '#!/usr/bin/env bash\\necho "hook-ran"\\necho "$PATH"\\n' > "$f"
chmod +x "$f"
done
exit 0
"""
@unittest.skipUnless(
shutil.which("bash") and shutil.which("git"), "bash and git are required"
)
class DevSetupTest(unittest.TestCase):
def setUp(self) -> None:
self.tmp = Path(tempfile.mkdtemp(prefix="kamino-devsetup-"))
self.addCleanup(shutil.rmtree, self.tmp, True)
self.stubs = self.tmp / "stubs"
self.stubs.mkdir()
for name, body in (
("python", PYTHON_STUB),
("pip", PIP_STUB),
("pre-commit", PRECOMMIT_STUB),
("ansible-galaxy", GALAXY_STUB),
):
path = self.stubs / name
path.write_text(body)
path.chmod(0o755)
# The venv's own python only has to pass `-c`; reuse the same stub logic.
(self.stubs / "python").write_text(PYTHON_STUB)
self.global_cfg = self.tmp / "gitconfig"
self.global_cfg.write_text("")
self.home = self.tmp / "home"
self.home.mkdir()
self.env = {
"PATH": os.environ["PATH"],
"HOME": str(self.home),
"GIT_CONFIG_GLOBAL": str(self.global_cfg),
"GIT_CONFIG_NOSYSTEM": "1",
"STUB_DIR": str(self.stubs),
"KAMINO_PYTHON": str(self.stubs / "python"),
}
def git(
self, repo: Path, *args: str, check: bool = True
) -> subprocess.CompletedProcess:
return subprocess.run(
["git", "-C", str(repo), *args],
env=self.env,
check=check,
capture_output=True,
)
def make_repo(self, name: str = "repo") -> Path:
repo = self.tmp / name
(repo / "scripts").mkdir(parents=True)
shutil.copy(SCRIPT, repo / "scripts" / "dev-setup.sh")
(repo / ".python-version").write_text("3.13\n")
(repo / "requirements-dev.txt").write_text("")
(repo / "requirements-dev.lock").write_text("")
(repo / "requirements.yml").write_text("---\ncollections: []\n")
self.git(repo, "init", "--quiet")
return repo
def run_setup(
self, repo: Path, cwd: Path | None = None, **extra: str
) -> subprocess.CompletedProcess:
env = {**self.env, **extra}
return subprocess.run(
["bash", str(repo / "scripts" / "dev-setup.sh")],
env=env,
cwd=str(cwd or repo),
capture_output=True,
text=True,
check=False,
)
def hooks_z(self, repo: Path) -> bytes:
return self.git(
repo, "config", "--local", "-z", "--get-all", "core.hooksPath", check=False
).stdout
def add_hooks_path(self, repo: Path, *values: str) -> None:
for value in values:
self.git(repo, "config", "--local", "--add", "core.hooksPath", value)
def hook(self, repo: Path, name: str = "pre-commit") -> Path:
return repo / ".git" / "hooks" / name
def test_a_python_other_than_the_pin_is_refused(self) -> None:
repo = self.make_repo()
wrong = self.stubs / "wrong-python"
wrong.write_text("#!/bin/sh\nexit 1\n")
wrong.chmod(0o755)
proc = self.run_setup(repo, KAMINO_PYTHON=str(wrong))
self.assertNotEqual(proc.returncode, 0)
self.assertIn("is not Python 3.13 (.python-version)", proc.stderr)
self.assertFalse((repo / ".venv").exists())
def test_an_interpreter_of_another_minor_is_refused_and_the_pinned_one_accepted(
self,
) -> None:
repo = self.make_repo()
proc = self.run_setup(repo, STUB_PY_MINOR="3.12")
self.assertNotEqual(proc.returncode, 0)
self.assertIn("is not Python 3.13 (.python-version)", proc.stderr)
self.assertFalse((repo / ".venv").exists())
proc = self.run_setup(repo, STUB_PY_MINOR="3.13")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertTrue((repo / ".venv").is_dir())
def test_a_missing_pin_file_is_refused_with_a_message(self) -> None:
repo = self.make_repo()
(repo / ".python-version").unlink()
proc = self.run_setup(repo)
self.assertNotEqual(proc.returncode, 0)
self.assertIn(".python-version is missing", proc.stderr)
def test_a_malformed_pin_file_is_refused(self) -> None:
repo = self.make_repo()
(repo / ".python-version").write_text("3.13.2\n")
proc = self.run_setup(repo)
self.assertNotEqual(proc.returncode, 0)
self.assertIn(".python-version must hold one MAJOR.MINOR", proc.stderr)
def test_normal_run(self) -> None:
repo = self.make_repo()
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
for name in ("pre-commit", "commit-msg", "pre-push"):
text = self.hook(repo, name).read_text()
self.assertIn("# kamino-dev-setup: virtualenv first on PATH", text)
self.assertEqual(self.hooks_z(repo), b"")
def test_tools_are_installed_from_the_hashed_lock_with_its_pins(self) -> None:
repo = self.make_repo()
self.assertEqual(self.run_setup(repo).returncode, 0)
calls = (self.stubs / "pip.log").read_text().splitlines()
self.assertEqual(len(calls), 1, calls)
# --require-hashes, the lock, and the direct pins next to it (pip refuses a disagreement).
self.assertIn("--require-hashes", calls[0].split())
self.assertTrue(
calls[0].endswith("-r requirements-dev.lock -r requirements-dev.txt"),
calls[0],
)
def galaxy_calls(self) -> list[str]:
return (self.stubs / "galaxy.log").read_text().splitlines()
def test_collections_are_installed_from_requirements_into_the_clone(self) -> None:
repo = self.make_repo()
self.assertEqual(self.run_setup(repo).returncode, 0)
target = repo / ".ansible" / "collections"
# The path is scoped to the target for the install, so a copy elsewhere is not skipped.
self.assertEqual(
self.galaxy_calls(),
[f"{target}|collection install -r requirements.yml -p {target}"],
)
def test_failed_collection_install_fails_the_setup(self) -> None:
repo = self.make_repo()
result = self.run_setup(repo, STUB_GALAXY_FAIL="1")
self.assertNotEqual(result.returncode, 0)
self.assertIn("stub galaxy failure", result.stderr)
self.assertNotIn("kamino-dev-setup", self.hook(repo).read_text())
def test_rerun_is_idempotent(self) -> None:
repo = self.make_repo()
self.assertEqual(self.run_setup(repo).returncode, 0)
first = self.hook(repo).read_text()
second_run = self.run_setup(repo)
self.assertEqual(second_run.returncode, 0, second_run.stderr)
self.assertEqual(self.hook(repo).read_text(), first)
self.assertEqual(first.count("kamino-dev-setup: virtualenv first"), 1)
def test_own_absolute_hooks_path_is_lifted_and_restored(self) -> None:
repo = self.make_repo()
self.add_hooks_path(repo, str(repo / ".git" / "hooks"))
before = self.hooks_z(repo)
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hooks_z(repo), before)
self.assertTrue(self.hook(repo).exists())
def test_own_relative_hooks_path_is_lifted_and_restored(self) -> None:
repo = self.make_repo()
self.add_hooks_path(repo, ".git/hooks")
before = self.hooks_z(repo)
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hooks_z(repo), before)
def test_foreign_hooks_path_fails_and_is_untouched(self) -> None:
repo = self.make_repo()
self.add_hooks_path(repo, str(self.tmp / "elsewhere"))
before = self.hooks_z(repo)
result = self.run_setup(repo)
self.assertNotEqual(result.returncode, 0)
self.assertIn("core.hooksPath is set to", result.stderr)
self.assertEqual(self.hooks_z(repo), before)
self.assertFalse(self.hook(repo).exists())
def test_global_hooks_path_fails_and_local_value_is_restored(self) -> None:
repo = self.make_repo()
self.global_cfg.write_text("[core]\n\thooksPath = /somewhere/global\n")
self.add_hooks_path(repo, ".git/hooks")
before = self.hooks_z(repo)
result = self.run_setup(repo)
self.assertNotEqual(result.returncode, 0)
self.assertIn("global", result.stderr)
self.assertEqual(self.hooks_z(repo), before)
def test_multi_valued_setting_is_restored(self) -> None:
repo = self.make_repo()
self.add_hooks_path(
repo, ".git/hooks", str(repo / ".git" / "hooks"), "./.git/hooks/"
)
before = self.hooks_z(repo)
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hooks_z(repo), before)
def test_value_with_newline_is_restored_exactly(self) -> None:
repo = self.make_repo()
# The newline sits in a component that ".." removes, so the value resolves to the
# repository's own hooks directory.
self.add_hooks_path(repo, ".git/hooks\n/../hooks")
before = self.hooks_z(repo)
self.assertIn(b"\n", before)
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hooks_z(repo), before)
def test_newline_value_is_restored_after_failure(self) -> None:
repo = self.make_repo()
self.add_hooks_path(repo, ".git/hooks\n/../hooks", "")
before = self.hooks_z(repo)
result = self.run_setup(repo, STUB_PRECOMMIT_FAIL="1")
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.hooks_z(repo), before)
def test_empty_value_is_lifted_and_restored(self) -> None:
repo = self.make_repo()
self.add_hooks_path(repo, "")
before = self.hooks_z(repo)
self.assertEqual(before, b"\0")
# The stub refuses on ANY value, so success proves the empty value was lifted.
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hooks_z(repo), before)
def test_trailing_empty_value_is_lifted_and_restored(self) -> None:
repo = self.make_repo()
self.add_hooks_path(repo, ".git/hooks", "")
before = self.hooks_z(repo)
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hooks_z(repo), before)
def test_setting_is_restored_when_pre_commit_fails(self) -> None:
repo = self.make_repo()
self.add_hooks_path(repo, ".git/hooks", str(repo / ".git" / "hooks"))
before = self.hooks_z(repo)
result = self.run_setup(repo, STUB_PRECOMMIT_FAIL="1")
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.hooks_z(repo), before)
def test_run_from_another_repository_leaves_it_untouched(self) -> None:
repo = self.make_repo("target")
other = self.tmp / "other"
other.mkdir()
self.git(other, "init", "--quiet")
result = self.run_setup(repo, cwd=other)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse((other / ".venv").exists())
self.assertEqual(
os.listdir(other / ".git" / "hooks"),
[n for n in os.listdir(other / ".git" / "hooks") if n.endswith(".sample")],
)
self.assertTrue((repo / ".venv").is_dir())
self.assertTrue(self.hook(repo).exists())
def test_crafted_repository_path_is_not_executed(self) -> None:
repo = self.make_repo('a b $(touch PWNED) "q" `touch PWNED2` $HOME')
result = self.run_setup(repo)
self.assertEqual(result.returncode, 0, result.stderr)
workdir = self.tmp / "hookcwd"
workdir.mkdir()
hook = subprocess.run(
[str(self.hook(repo))],
env={**self.env},
cwd=str(workdir),
capture_output=True,
text=True,
check=False,
)
self.assertEqual(hook.returncode, 0, hook.stderr)
lines = hook.stdout.splitlines()
self.assertEqual(lines[0], "hook-ran")
self.assertTrue(lines[1].startswith(f"{repo}/.venv/bin:"), lines[1])
for place in (workdir, repo, self.tmp, Path.cwd()):
self.assertFalse((place / "PWNED").exists(), place)
self.assertFalse((place / "PWNED2").exists(), place)
if __name__ == "__main__":
unittest.main()