From 6c80ab77725cc9fbf7cb540461161b23cf6fc00e Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 6 Dec 2026 19:10:56 +0000 Subject: [PATCH 1/5] test(scripts): keep git fixtures off the caller's GIT_* variables A git hook exports GIT_DIR (and often GIT_INDEX_FILE). A fixture that passes the caller's environment to git would run its init, add and commit against this repository instead of its temporary one once the suite runs as a hook. tests/scripts/git_env.py gives each fixture a copy of the environment without any GIT_* key and with no user or system config. The bot pull request gate's repository tests also isolate os.environ, because the gate runs git in-process. Refs: #187 Assisted-by: Claude Code --- tests/scripts/git_env.py | 12 ++++++++++++ tests/scripts/test_check_bot_pr_diff.py | 13 +++++++------ tests/scripts/test_check_image_versions.py | 8 ++------ tests/scripts/test_check_scenarios_load_checkout.py | 7 ++++++- tests/scripts/test_select_molecule_scenarios.py | 6 ++---- 5 files changed, 29 insertions(+), 17 deletions(-) create mode 100644 tests/scripts/git_env.py diff --git a/tests/scripts/git_env.py b/tests/scripts/git_env.py new file mode 100644 index 0000000..fce8bb7 --- /dev/null +++ b/tests/scripts/git_env.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""The environment for a test's git fixture: no caller GIT_* and no user or system config.""" + +import os + + +def isolated(**extra): + """A copy of os.environ for git: a hook exports GIT_DIR, which would point it at the real repo.""" + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env.update(GIT_CONFIG_GLOBAL="/dev/null", GIT_CONFIG_NOSYSTEM="1", **extra) + return env diff --git a/tests/scripts/test_check_bot_pr_diff.py b/tests/scripts/test_check_bot_pr_diff.py index e8ee19c..40404d7 100644 --- a/tests/scripts/test_check_bot_pr_diff.py +++ b/tests/scripts/test_check_bot_pr_diff.py @@ -13,6 +13,7 @@ from unittest import mock SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" sys.path.insert(0, str(SCRIPTS)) import check_bot_pr_diff as cbd +import git_env from test_check_uv_lock import APM_NEW, APM_OLD, CLICK_OLD, UV_LOCK, uv_files D1, D2 = "sha256:" + "a" * 64, "sha256:" + "b" * 64 @@ -51,11 +52,7 @@ def run(cwd, *cmd): check=True, capture_output=True, text=True, - env={ - **os.environ, - "GIT_CONFIG_GLOBAL": "/dev/null", - "GIT_CONFIG_SYSTEM": "/dev/null", - }, + env=git_env.isolated(), ) @@ -475,6 +472,10 @@ class RuleTest(unittest.TestCase): class RepoTest(unittest.TestCase): def setUp(self): + # The gate runs git in-process, in the fixture's directory. + patcher = mock.patch.dict(os.environ, git_env.isolated(), clear=True) + patcher.start() + self.addCleanup(patcher.stop) self.tmp = tempfile.TemporaryDirectory() self.repo = pathlib.Path(self.tmp.name) self.addCleanup(self.tmp.cleanup) @@ -579,7 +580,7 @@ class RepoTest(unittest.TestCase): def test_empty_head_ref_on_a_pull_request_fails_closed(self): self.write("roles/x/main.yml", "a\n") self.commit("anything") - env = {**os.environ, "EVENT_NAME": "pull_request"} + env = git_env.isolated(EVENT_NAME="pull_request") proc = subprocess.run( [sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"], cwd=self.repo, diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index afe3dc1..814f2bc 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: GPL-3.0-or-later """Run with: python3 -m unittest discover -s tests/scripts""" -import os import pathlib import subprocess import sys @@ -12,6 +11,7 @@ import unittest SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" sys.path.insert(0, str(SCRIPTS)) import check_image_versions as civ +import git_env DIGEST = "sha256:" + "a" * 64 JOB = f"ubuntu:24.04@{DIGEST}" @@ -67,11 +67,7 @@ def run(cwd, *cmd): check=True, capture_output=True, text=True, - env={ - **os.environ, - "GIT_CONFIG_GLOBAL": "/dev/null", - "GIT_CONFIG_SYSTEM": "/dev/null", - }, + env=git_env.isolated(), ) diff --git a/tests/scripts/test_check_scenarios_load_checkout.py b/tests/scripts/test_check_scenarios_load_checkout.py index 03f2f05..7045bb4 100644 --- a/tests/scripts/test_check_scenarios_load_checkout.py +++ b/tests/scripts/test_check_scenarios_load_checkout.py @@ -14,6 +14,7 @@ import sys import tempfile import unittest +import git_env import yaml REPO = pathlib.Path(__file__).resolve().parents[2] @@ -44,7 +45,11 @@ class CheckScenariosLoadCheckoutTest(unittest.TestCase): self.checkout = collection(self.ac_root) (self.checkout / "scripts").mkdir() # molecule's CLI finds the base config from the repository root, as in the real checkout - subprocess.run(["git", "init", "-q", str(self.checkout)], check=True) + subprocess.run( + ["git", "init", "-q", str(self.checkout)], + check=True, + env=git_env.isolated(), + ) self.base_config = self.checkout / ".config" / "molecule" / "config.yml" self.base_config.parent.mkdir(parents=True) self.base_config.write_text("prerun: false\n") diff --git a/tests/scripts/test_select_molecule_scenarios.py b/tests/scripts/test_select_molecule_scenarios.py index e49ac30..8dfb30c 100644 --- a/tests/scripts/test_select_molecule_scenarios.py +++ b/tests/scripts/test_select_molecule_scenarios.py @@ -17,6 +17,7 @@ import yaml REPO = pathlib.Path(__file__).resolve().parents[2] sys.path.insert(0, str(REPO / "scripts")) +import git_env import select_molecule_scenarios as sel ROLE_KEYS = { @@ -409,9 +410,6 @@ class MainTest(unittest.TestCase): (d / "molecule.yml").write_text("---\n") def git(self, root, *args): - # No GIT_* from the caller (a hook exports GIT_DIR), no user or system config. - env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} - env.update(GIT_CONFIG_GLOBAL="/dev/null", GIT_CONFIG_NOSYSTEM="1") subprocess.run( [ "git", @@ -427,7 +425,7 @@ class MainTest(unittest.TestCase): ], check=True, capture_output=True, - env=env, + env=git_env.isolated(), ) def topic_repo(self, root, files): From b2e547edd57003cfb4d6abba55594b33391769e9 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 6 Dec 2026 19:11:16 +0000 Subject: [PATCH 2/5] test(scripts): reach the fake registry past Lint's dead proxy Lint's fast path exports a dead proxy with an empty no_proxy, and next_image_version.py uses urllib's default opener, which honours them, so the RegistryClient tests could not reach their fake registry on 127.0.0.1. Setting no_proxy for loopback in the tests lets the suite run under the guard instead of the workflow unsetting it. Refs: #187 Assisted-by: Claude Code --- tests/scripts/test_next_image_version.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/scripts/test_next_image_version.py b/tests/scripts/test_next_image_version.py index 11804e3..36c5d60 100644 --- a/tests/scripts/test_next_image_version.py +++ b/tests/scripts/test_next_image_version.py @@ -6,11 +6,13 @@ import contextlib import http.server import io import json +import os import pathlib import sys import tempfile import threading import unittest +from unittest import mock SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts" sys.path.insert(0, str(SCRIPTS)) @@ -156,6 +158,12 @@ class QuietServer(http.server.HTTPServer): class RegistryClient(unittest.TestCase): def setUp(self): + # Lint exports a dead proxy with an empty no_proxy; the fake registry is on loopback. + patcher = mock.patch.dict( + os.environ, no_proxy="127.0.0.1", NO_PROXY="127.0.0.1" + ) + patcher.start() + self.addCleanup(patcher.stop) FakeRegistry.refuse = FakeRegistry.refuse_token = FakeRegistry.no_realm = False FakeRegistry.empty_token = FakeRegistry.unknown = False FakeRegistry.not_found = None From fac7ed47bee47883b1cfbf9e49751843d759f722 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 6 Dec 2026 19:11:42 +0000 Subject: [PATCH 3/5] ci(pre-commit): run check-json, the script tests and the image pins as hooks A contributor learns about a broken renovate.json, a failing script test or a bad image pin from Lint today; as hooks they fail before the push. - check-json from pre-commit-hooks covers renovate.json. - script-tests runs the suite at pre-push, since it takes minutes. Its GIT_DIR points at an uncreatable path, so a fixture that keeps the caller's git environment fails instead of writing to this repository. Lint runs it by id; the suite now runs under the network guard. - check-image-pins runs check_image_versions.py pins on every commit: its inputs span workflows, Dockerfiles and docs/images, and it fails when one is missing. Lint's pre-commit run replaces its separate step. Adding hooks changes .pre-commit-config.yaml, an input of the ci image, so this pull request takes Lint's slow path and the next Images run publishes a new ci version. Refs: #187 Assisted-by: Claude Code --- .gitea/workflows/AGENTS.md | 11 +++++------ .gitea/workflows/lint.yml | 15 +++------------ .pre-commit-config.yaml | 23 +++++++++++++++++++++++ docs/images/ci.md | 6 +++--- images/AGENTS.md | 3 +-- images/ci/Dockerfile | 2 +- requirements-dev.txt | 2 +- scripts/AGENTS.md | 4 ++-- 8 files changed, 39 insertions(+), 27 deletions(-) diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index 22c2070..559ac58 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -50,8 +50,8 @@ issue. branch name is chosen by the pusher, so this constrains only the bot's own pull requests. - **Workflows never mention the image namespace this repository's CI must not use** (the string is in `scripts/check_image_versions.py`). *Why:* this repository's images are built and pulled - only under its own organisation's namespace. *Held:* control: the Lint check's "Check image - pins" step. + only under its own organisation's namespace. *Held:* control: the `check-image-pins` hook, + run by the Lint check. ## Lint and Build @@ -62,13 +62,12 @@ issue. *Why:* a pull request is tested on its own pins, and an unchanged one starts in seconds. *Held:* control: the "Check the baked tooling against the pins" step. - **On the fast path the network is cut by environment**: `PIP_NO_INDEX=1`, the proxy variables - set to a dead local port and `no_proxy` empty, for every later step except "Test the repository - scripts", which unsets them for its fake registry on loopback; the slow path keeps network. + set to a dead local port and `no_proxy` empty, for every later step; the slow path keeps + network. The script tests set `no_proxy` to `127.0.0.1` for their fake registry on loopback. *Why:* a runtime download is a bake-in defect and must fail the job, not silently slow it. *Held:* control, set by the "Check the baked tooling against the pins" step, for pip, curl, git over HTTPS and Python's urllib or requests (anything honouring `PIP_NO_INDEX` or the proxy - variables); review for a raw socket or a tool that ignores the proxy variables, and for the - script tests. + variables); review for a raw socket or a tool that ignores the proxy variables. - **Triggers:** both run on pull requests to `main` and on manual dispatch; Build also runs on `v*` tags, where it checks the tag against `galaxy.yml`. *Why:* the tag is what consumers install. *Held:* review. diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 2ac301b..8e5abef 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -78,14 +78,6 @@ jobs: export PATH="/opt/venv/bin:$PATH" pre-commit run --all-files --show-diff-on-failure - # Image pins (scripts/check_image_versions.py): a pin in a workflow must name an - # image of the matrix. Not a pre-commit hook: a change to .pre-commit-config.yaml - # is itself an input of the ci image and would force an image rebuild. - - name: Check image pins - run: | - export PATH="/opt/venv/bin:$PATH" - python3 scripts/check_image_versions.py pins - # A pull request from a renovate/ branch may only move version, tag, digest and pin # lines (scripts/check_bot_pr_diff.py), so the bot's automerge cannot change workflow # logic or reach the org secrets. The branch name is attacker-controlled: this only @@ -113,12 +105,11 @@ jobs: fi python3 -E -s "$guard" "$HEAD_REF" "$BASE_REF" - # Without the guard: an empty no_proxy would send the fake registry on 127.0.0.1 to the dead proxy. - - name: Test the repository scripts + # The script tests are a pre-push hook (they take minutes), so --all-files above skips them. + - name: Run the script tests hook run: | - unset PIP_NO_INDEX http_proxy https_proxy HTTP_PROXY HTTPS_PROXY export PATH="/opt/venv/bin:$PATH" - python3 -m unittest discover -s tests/scripts + pre-commit run --hook-stage pre-push script-tests --all-files --show-diff-on-failure # The gitleaks hook scans --staged only, which is empty in a clean checkout, # so scan the PR's commits explicitly with the binary pre-commit built. diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cbef59c..bb0e699 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -49,6 +49,8 @@ repos: hooks: - id: check-toml stages: ['pre-commit'] + - id: check-json + stages: ['pre-commit'] - id: check-merge-conflict stages: ['pre-commit'] @@ -114,6 +116,27 @@ repos: require_serial: true stages: ['pre-push'] + # Pre-push only: the suite takes minutes. Lint runs it by id. The uncreatable GIT_DIR makes a + # git fixture that keeps the caller's GIT_* fail instead of writing to this repository. + - id: script-tests + name: A script change passes its tests in tests/scripts (scripts/AGENTS.md) + description: python3 -m unittest discover -s tests/scripts + entry: env GIT_DIR=/dev/null/not-a-repo python3 -m unittest discover -s tests/scripts + language: system + files: ^(scripts/|tests/scripts/|roles/[^/]+/meta/) + pass_filenames: false + stages: ['pre-push'] + + # always_run: its inputs span workflows, Dockerfiles and docs/images, and it fails on a missing one. + - id: check-image-pins + name: Image pins name an image of the image.yml matrix, which has its job image, labels and docs (images/AGENTS.md) + description: python3 scripts/check_image_versions.py pins + entry: python3 scripts/check_image_versions.py pins + language: system + pass_filenames: false + always_run: true + stages: ['pre-commit'] + # SECURITY.md's accepted risks rest on the Collection shipping roles only. It sits before # ansible-lint, whose fail_fast would otherwise hide this message. - id: refuse-plugins diff --git a/docs/images/ci.md b/docs/images/ci.md index 30052ab..d8af45f 100644 --- a/docs/images/ci.md +++ b/docs/images/ci.md @@ -11,7 +11,7 @@ Ubuntu 26.04 with: - **Python tools** in `/opt/venv` (on `PATH`; it runs on Python 3.14, the version of `.python-version`, from the baked copy and not from the distribution's `python3`), from `requirements-dev.lock` (the hashed lock of `requirements-dev.txt`, installed with `pip install --require-hashes`): `ansible-core`, `ansible-lint`, `pre-commit`, `antsibull-changelog`, `galaxy-importer`, `reuse`, `molecule` - (without its Docker driver: Lint's "Test the repository scripts" step runs the tests that import it), and + (without its Docker driver: Lint's run of the `script-tests` hook runs the tests that import it), and `proxmoxer`, the controller-side library the modules of `community.proxmox` import. - **The collections the roles call** in `/opt/collections` (`ANSIBLE_COLLECTIONS_PATH` is set to it), from `requirements.yml`: `community.general`, `ansible.posix` and `community.proxmox` at the exact versions CI tests against, so @@ -20,7 +20,7 @@ Ubuntu 26.04 with: (`PRE_COMMIT_HOME`): conventional-pre-commit, gitleaks, yamllint, ruff, shellcheck-py, pre-commit-hooks, actionlint and zizmor. The Go hooks are prebuilt; their toolchains, and the binaries of those repositories that no hook runs, are removed to keep layers small. The local hooks (`reuse-lint`, - `antsibull-changelog-lint`, `ansible-lint`) are `language: system`: they run from `/opt/venv`, which is why + `antsibull-changelog-lint`, `ansible-lint`, `script-tests`, `check-image-pins`) are `language: system`: they run from `/opt/venv`, which is why that directory must be on `PATH` (it is, in the image). - **`ansible-test sanity` virtualenvs**, primed in `/root/.ansible/test`, and Python 3.11, 3.13 and 3.14 as `python3.11` / `python3.13` / `python3.14` (python-build-standalone, installed with uv) next to the distribution's @@ -63,7 +63,7 @@ jobs: `/opt/ci-pins.sha256` lists the four pin files by their checkout-relative path, so `sha256sum -c` runs in the checkout root. When the checkout's `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml` and `.pre-commit-config.yaml` match, the baked tools and collections are used as they are, and Lint and Build cut the network by environment (proxy variables and -`PIP_NO_INDEX`) for all but the script tests, so a tool that downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned +`PIP_NO_INDEX`), so a tool that downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned tools and collections itself for that run (slower, same result), until the image is rebuilt from `main`. `lint.yml`, `build.yml` and `gitea-release-key.yml` are the real consumers. diff --git a/images/AGENTS.md b/images/AGENTS.md index 1cc8c19..d64a50a 100644 --- a/images/AGENTS.md +++ b/images/AGENTS.md @@ -63,8 +63,7 @@ it to this repository's organisation in the Gitea registry as `` and `l image; a job downloads at run time only on the slow path (a pull request that changes a pin file). *Why:* a run that downloads is slower and depends on the network. *Held:* control: on the fast path Lint and Build cut the network by environment, so a download through pip or a - proxy-honouring client fails the job; review for a raw socket, for the script tests, which keep - network, and for Molecule. + proxy-honouring client fails the job; review for a raw socket and for Molecule. - **Each Dockerfile upgrades the base image's packages in its first apt layer.** *Why:* Ubuntu publishes package updates before it refreshes the base image. *Held:* review. - **Recorded speed:** a speed optimisation that adds machinery states its measured saving where diff --git a/images/ci/Dockerfile b/images/ci/Dockerfile index 5de8985..7a05aae 100644 --- a/images/ci/Dockerfile +++ b/images/ci/Dockerfile @@ -15,7 +15,7 @@ # - /opt/venv: requirements-dev.lock, the hashed lock of requirements-dev.txt (ansible-core, ansible-lint, pre-commit, # antsibull-changelog, galaxy-importer, reuse, molecule, proxmoxer), on the Python of # .python-version (PYTHON_VERSION below), the one the lock was resolved on and a clone's .venv-dev uses. -# molecule is there for Lint's "Test the repository scripts" step, whose molecule tests import it; its +# molecule is there for Lint's run of the script-tests hook, whose molecule tests import it; its # Docker driver and community.docker are not: Molecule runs in the molecule-controller image. # - /opt/collections: the collections of requirements.yml (the versions the roles are # tested against), found through ANSIBLE_COLLECTIONS_PATH, so `ansible-lint --offline` diff --git a/requirements-dev.txt b/requirements-dev.txt index 2d36974..8ab05f5 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -12,7 +12,7 @@ pre-commit==4.7.0 antsibull-changelog==0.38.0 galaxy-importer==0.4.45 reuse==6.3.0 -# molecule without its Docker driver: Lint's "Test the repository scripts" step imports it in +# molecule without its Docker driver: Lint's run of the script-tests hook imports it in # test_check_scenarios_load_checkout.py and test_run_molecule_scenarios.py, which skip without it. molecule==26.11.1 # proxmoxer: the controller-side library community.proxmox's modules import (they refuse anything below 2.3), diff --git a/scripts/AGENTS.md b/scripts/AGENTS.md index 827e5d3..51b3274 100644 --- a/scripts/AGENTS.md +++ b/scripts/AGENTS.md @@ -12,8 +12,8 @@ rules for scripts (prefer a standard tool, comment length) are in - **A script change comes with its test in `tests/scripts/`** (`test_