diff --git a/.ansible-lint b/.ansible-lint index 3184737..2665ca0 100644 --- a/.ansible-lint +++ b/.ansible-lint @@ -11,16 +11,9 @@ exclude_paths: - changelogs - images -# The Collection is checked out outside an ansible_collections/mortis/kamino path (CI clones it -# into the workspace), so ansible-lint cannot resolve a role of this Collection by its FQCN in -# a scenario's converge play. List the roles the scenarios call by FQCN. -mock_roles: - - mortis.kamino.docker - - mortis.kamino.fail2ban - - mortis.kamino.network_interfaces - - mortis.kamino.system_baseline - - mortis.kamino.systemd_hardening - # The collections of the Collection's dependencies (galaxy.yml) are pinned in requirements.yml and # resolved offline: the ci image bakes them into /opt/collections and scripts/dev-setup.sh installs -# them into .ansible/collections, so their modules are linted, not mocked. +# them into .ansible/collections, so their modules are linted, not mocked. The Collection's own role +# names (mortis.kamino., used by the scenarios) resolve the same way: scripts/ansible-lint.sh, +# which the hook runs, links the checkout as ansible_collections/mortis/kamino. A bare `ansible-lint` +# does not do that and reports the role names as not found; run it through the hook. diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 576acfa..9a615e7 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -32,7 +32,7 @@ jobs: timeout-minutes: 30 # The ci image (images/ci, built by image.yml): tag for the release, digest enforced. container: - image: git.rkdr.net/mortis/ci:0.2.15@sha256:32b6b44640b0864266fdabb37f7c9d1c8e83834753e63f69af9c0c8a1cc67eb1 + image: git.rkdr.net/mortis/ci:0.2.18@sha256:ff30bb7fe0106c7b0c8bd1021b56861763157fc26f7e94edf28f1d0259f266a8 env: PIP_DISABLE_PIP_VERSION_CHECK: "1" steps: diff --git a/.gitea/workflows/image.yml b/.gitea/workflows/image.yml index 63e94e9..2a4b87f 100644 --- a/.gitea/workflows/image.yml +++ b/.gitea/workflows/image.yml @@ -87,7 +87,7 @@ jobs: dockerfile: Dockerfile job_image: ubuntu:26.04@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c - name: ci - version: 0.2.16 + version: 0.2.18 subpath: "" dockerfile: images/ci/Dockerfile job_image: ubuntu:26.04@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 4ba4321..99304c0 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -35,7 +35,7 @@ jobs: # The tag says which release, the digest is what is enforced (bump both together # when image.yml publishes a new version). container: - image: git.rkdr.net/mortis/ci:0.2.15@sha256:32b6b44640b0864266fdabb37f7c9d1c8e83834753e63f69af9c0c8a1cc67eb1 + image: git.rkdr.net/mortis/ci:0.2.18@sha256:ff30bb7fe0106c7b0c8bd1021b56861763157fc26f7e94edf28f1d0259f266a8 env: PIP_DISABLE_PIP_VERSION_CHECK: "1" PRE_COMMIT_HOME: /opt/pre-commit diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4645f17..6961103 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,4 +1,4 @@ -default_install_hook_types: [pre-commit, commit-msg] +default_install_hook_types: [pre-commit, commit-msg, pre-push] repos: - repo: https://github.com/compilerla/conventional-pre-commit @@ -83,6 +83,20 @@ repos: stages: ['pre-commit'] pass_filenames: false + # Pre-push only: the Build job's ansible-test sanity run, on HEAD (scripts/ansible-test-sanity.sh). + # The sanity tests carry their own pylint, pep8 and shellcheck settings, which the hooks above do + # not, and a cold run builds virtualenvs, so it is not a commit hook. CI's pre-commit run does not + # run this stage (the Build job runs sanity itself), and no hook environment is built for it. + - id: ansible-test-sanity + name: ansible-test sanity + description: ansible-test sanity on HEAD, as the Build job runs it + entry: scripts/ansible-test-sanity.sh + language: system + pass_filenames: false + always_run: true + require_serial: true + stages: ['pre-push'] + - id: ansible-lint name: ansible-lint description: ansible-lint production profile, offline diff --git a/CLAUDE.md b/CLAUDE.md index 298936a..5610eaa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,6 +27,8 @@ or create tags: those are the operator's. actionlint, ansible-lint, gitleaks, changelog lint, Conventional Commits) only run in `git commit`; an API commit skips them and CI finds the problem after the push. The first hook run builds the Go hook environments and takes minutes: run commits in the background. + `git push` also runs `ansible-test sanity` on HEAD (`scripts/ansible-test-sanity.sh`, the Build + job's check, which ruff and the other hooks do not cover); its first run builds virtualenvs and takes minutes. - Feature branch and pull request; `main` and `v*` tags are protected. Never push to `main`. Releases are the operator's: annotated `vX.Y.Z` tags equal to `galaxy.yml`'s version. - Conventional Commits. A PR says what was verified and what was not. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 370d9fd..d5392f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,9 @@ (`requirements.yml`, into `.ansible/collections`, so local lint resolves the versions CI does) and installs git hooks that find the tools (the `ansible-lint` hook, `scripts/ansible-lint.sh`, uses those collections, also from a bare `pre-commit run`). Then - `pre-commit run --all-files` before pushing. + `pre-commit run --all-files` before pushing. A `git push` runs `ansible-test sanity` on HEAD + (`scripts/ansible-test-sanity.sh`, the Build job's check; the first run builds virtualenvs and + takes minutes), so a finding only that test reports stops the push, not the Build check. - Never commit credentials, tokens or key material. - Releases are cut by the maintainer: bump `version` in `galaxy.yml`, add a `release_summary:` fragment, run `antsibull-changelog release` in a release PR diff --git a/docs/images/ci.md b/docs/images/ci.md index 8248a2e..e0f2cfb 100644 --- a/docs/images/ci.md +++ b/docs/images/ci.md @@ -14,7 +14,8 @@ Ubuntu 26.04 with: `ansible-lint --offline` resolves their modules instead of mocking them. - **Every pre-commit hook environment** of `.pre-commit-config.yaml` in `/opt/pre-commit` (`PRE_COMMIT_HOME`): conventional-pre-commit, gitleaks, yamllint, ruff, shellcheck-py, pre-commit-hooks and actionlint. The Go - hooks are prebuilt; their toolchains are removed to keep layers small. The local hooks (`reuse-lint`, + 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 that directory must be on `PATH` (it is, in the image). - **`ansible-test sanity` virtualenvs**, primed in `/root/.ansible/test`, and Python 3.11 and 3.13 as @@ -77,7 +78,8 @@ files are copied in). The workflow runs on pushes to `main` that touch `images/* `version:` in the workflow's matrix is not yet published. A change to the image's inputs therefore needs a new `version:` (Lint enforces it, and Renovate's bump step does it for dependency updates), and the merge builds the image. Each pushed layer stays below 100 MB (Cloudflare's request limit), which is why the Go toolchains -are deleted from the hook cache. +and the unused Go binaries are deleted from the hook cache, and why the build prints the compressed size of each layer +directory. ## Image metadata diff --git a/images/ci/Dockerfile b/images/ci/Dockerfile index 6b178b1..bfe64e7 100644 --- a/images/ci/Dockerfile +++ b/images/ci/Dockerfile @@ -82,9 +82,19 @@ RUN python3 -m venv /opt/uv-venv \ # downloads into /.go, about 170 MB per environment, which alone pushed the # /opt/pre-commit layer past Cloudflare's 100 MB limit (413 on the first push). At run # time only the built binaries in /bin run, so the toolchains and the Go build -# cache are deleted. The hooks below run on a staged sample before and after the +# cache are deleted. So are the binaries no hook runs: pre-commit installs every main +# package of a hook repository, which leaves gitleaks' `config` and actionlint's +# `check-checks` and `generate-*` (about 60 MB raw, 20 MB compressed) next to the +# `gitleaks` and `actionlint` that the hooks call. Without them the ruff and shellcheck +# environments fit: with them the layer was about 103 MB compressed and the push of +# ci 0.2.16 got a 413. The hooks below run on a staged sample before and after the # deletion: a cache that is incomplete (a missing environment would be rebuilt, which # needs the network) or no longer works fails the image build, not the jobs. +# +# The last lines print the compressed size of each directory a later COPY turns into a +# layer, which is what the 100 MB (95 MiB) limit applies to. These gzip -6 figures run +# about 9% below the sizes the registry stores, and every new hook environment adds +# 15 to 25 MB to /opt/pre-commit, so read them before adding one. RUN set -eu; \ git init -q /tmp/hooks; \ cp .pre-commit-config.yaml /tmp/hooks/; \ @@ -101,10 +111,14 @@ RUN set -eu; \ smoke() { for h in yamllint gitleaks actionlint ruff-check ruff-format shellcheck; do /opt/venv/bin/pre-commit run "$h" --all-files; done; }; \ smoke; \ rm -rf /opt/pre-commit/repo*/golangenv-*/.go /root/.cache/go-build; \ + find /opt/pre-commit/repo*/golangenv-*/bin -mindepth 1 -maxdepth 1 -type f \ + ! -name gitleaks ! -name actionlint -delete; \ smoke; \ rm -rf /tmp/hooks; \ find /opt/pre-commit -maxdepth 1 -mindepth 1 -exec du -sh {} + | sort -h; \ - du -sh /opt/venv /opt/python /opt/pre-commit + gz() { tar -C "$(dirname "$1")" -cf - "$(basename "$1")" | gzip -6 | wc -c \ + | awk -v d="$1" '{printf "%7.1f MB compressed %s\n", $1 / 1048576, d}'; }; \ + for d in /opt/venv /opt/python /opt/collections /opt/pre-commit; do gz "$d"; done # ansible-test builds one virtualenv per sanity test under ~/.ansible/test/venv, keyed # by the hash of the test's requirements (so by the ansible-core pin), and reuses it on diff --git a/scripts/ansible-lint.sh b/scripts/ansible-lint.sh index ebdf8e9..9cbfc34 100755 --- a/scripts/ansible-lint.sh +++ b/scripts/ansible-lint.sh @@ -7,6 +7,12 @@ # ones CI tests against (#118, #80). So when the variable is unset, this script uses the collections # scripts/dev-setup.sh installed into .ansible/collections of this clone, and fails with the fix # when they are missing. That covers `git commit` and a bare `pre-commit run` alike. +# +# The Collection's own role names (mortis.kamino., which the molecule scenarios' converge +# plays use) only resolve from an / directory under an ansible_collections root, +# and a checkout is not one. So the checkout is linked into a temporary root, put first on the +# collections path, and ansible-lint reads the checkout itself through it (#118 step 5). The link +# is removed on exit. set -euo pipefail root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -21,4 +27,19 @@ if [ -z "${ANSIBLE_COLLECTIONS_PATH:-}" ]; then export ANSIBLE_COLLECTIONS_PATH="$root/.ansible/collections" fi -exec ansible-lint --offline --nocolor +# The Collection's own name, from galaxy.yml, so a rename needs no edit here. +namespace="$(sed -n 's/^namespace: *//p' galaxy.yml)" +name="$(sed -n 's/^name: *//p' galaxy.yml)" +if [ -z "$namespace" ] || [ -z "$name" ]; then + echo "error: no namespace and name in $root/galaxy.yml" >&2 + exit 1 +fi + +link_root="$(mktemp -d)" +trap 'rm -rf "$link_root"' EXIT +mkdir -p "$link_root/ansible_collections/$namespace" +ln -s "$root" "$link_root/ansible_collections/$namespace/$name" +export ANSIBLE_COLLECTIONS_PATH="$link_root:$ANSIBLE_COLLECTIONS_PATH" + +# Not exec: the trap above has to run when ansible-lint ends. +ansible-lint --offline --nocolor diff --git a/scripts/ansible-test-sanity.sh b/scripts/ansible-test-sanity.sh new file mode 100755 index 0000000..d3bc0b1 --- /dev/null +++ b/scripts/ansible-test-sanity.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# The ansible-test sanity pre-push hook: the Build job's sanity run, on the commit being pushed. +# +# ansible-test only runs a collection from an ansible_collections// directory, +# and a checkout is not one. So this copies HEAD (git archive: the committed files, no untracked +# or unstaged changes, no .git) into a temporary one, as the Build job does with a git worktree, +# and applies the same ignore-file step. ruff and the other hooks cannot stand in for it: the +# sanity tests carry their own pylint, pep8 and shellcheck settings (ansible-test also scans +# the Python under tests/). +# +# Extra arguments go to ansible-test, e.g. `scripts/ansible-test-sanity.sh --test pylint`. +# The first run builds the sanity virtualenvs (minutes, and it needs the network); later ones +# reuse them. HEAD is what runs, so a push of another branch than the checked-out one checks +# the wrong commit. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$root" + +for tool in ansible ansible-test; do + if ! command -v "$tool" >/dev/null 2>&1; then + echo "error: $tool is not on PATH; run scripts/dev-setup.sh and use its virtualenv (.venv/bin)" >&2 + exit 1 + fi +done + +# The Collection's own name, from galaxy.yml, so a rename needs no edit here. +namespace="$(sed -n 's/^namespace: *//p' galaxy.yml)" +name="$(sed -n 's/^name: *//p' galaxy.yml)" +if [ -z "$namespace" ] || [ -z "$name" ]; then + echo "error: no namespace and name in $root/galaxy.yml" >&2 + exit 1 +fi + +core="$(ansible --version | sed -n 's/^ansible \[core \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -n 1)" +if [ -z "$core" ]; then + echo "error: cannot read the ansible-core version from 'ansible --version'" >&2 + exit 1 +fi + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +dest="$work/ansible_collections/$namespace/$name" +mkdir -p "$dest" +git archive HEAD | tar -x -C "$dest" +cd "$dest" + +# ansible-test reads tests/sanity/ignore-.txt and has no wildcard. The committed +# ignore-common.txt applies to every core version: it is copied to the file name of the installed +# core here, in this copy only (plus the lines of a committed ignore-.txt, for a +# finding of one version only). The Build job does the same. +ignore="tests/sanity/ignore-${core}.txt" +{ + cat tests/sanity/ignore-common.txt + if [ -f "$ignore" ]; then cat "$ignore"; fi +} >"$work/ignore.new" +mv "$work/ignore.new" "$ignore" + +# Not exec: the trap above has to run when ansible-test ends. +ansible-test sanity --requirements "$@" diff --git a/scripts/dev-setup.sh b/scripts/dev-setup.sh index e06a2f2..91365dd 100755 --- a/scripts/dev-setup.sh +++ b/scripts/dev-setup.sh @@ -133,7 +133,7 @@ ANSIBLE_COLLECTIONS_PATH="$collections" .venv/bin/ansible-galaxy collection inst marker="# kamino-dev-setup: virtualenv first on PATH" # default_install_hook_types in .pre-commit-config.yaml names these; keep in step. -for hook in pre-commit commit-msg; do +for hook in pre-commit commit-msg pre-push; do file="$(git -C "$root" rev-parse --path-format=absolute --git-path "hooks/$hook")" if [ ! -f "$file" ]; then echo "error: $file was not installed by 'pre-commit install'; check default_install_hook_types in .pre-commit-config.yaml." >&2 diff --git a/scripts/select_molecule_scenarios.py b/scripts/select_molecule_scenarios.py index 770f621..8d34914 100644 --- a/scripts/select_molecule_scenarios.py +++ b/scripts/select_molecule_scenarios.py @@ -82,6 +82,7 @@ IGNORED = ( "scripts/check_image_versions.py", "scripts/check_tarball.py", "scripts/ansible-lint.sh", + "scripts/ansible-test-sanity.sh", "scripts/dev-setup.sh", "scripts/reuse_lint.py", ) diff --git a/tests/scripts/test_ansible_lint_wrapper.py b/tests/scripts/test_ansible_lint_wrapper.py index b8300bb..2eb8111 100644 --- a/tests/scripts/test_ansible_lint_wrapper.py +++ b/tests/scripts/test_ansible_lint_wrapper.py @@ -14,15 +14,34 @@ import unittest SCRIPT = pathlib.Path(__file__).resolve().parents[2] / "scripts" / "ansible-lint.sh" -# Prints what the wrapper hands to ansible-lint: its arguments, directory and the two variables. +# Prints what the wrapper hands to ansible-lint: its arguments, directory, the two variables and +# the temporary collections root (the first element of the path) with every link inside it. STUB = """#!/bin/sh +first="${ANSIBLE_COLLECTIONS_PATH%%:*}" echo "args=$*" echo "cwd=$(pwd -P)" echo "home=${ANSIBLE_HOME-unset}" echo "path=${ANSIBLE_COLLECTIONS_PATH-unset}" +echo "first=$first" +for link in "$first"/ansible_collections/*/*; do + echo "link=${link#"$first"/ansible_collections/} -> $(readlink "$link")" +done +exit "${STUB_EXIT:-0}" """ +def parsed(stdout): + """{key: value} of the stub's output; `link` may repeat, so it is collected in a list.""" + out = {"link": []} + for line in stdout.splitlines(): + parts = line.partition("=") + if parts[0] == "link": + out["link"].append(parts[2]) + else: + out[parts[0]] = parts[2] + return out + + @unittest.skipUnless(shutil.which("bash"), "bash is required") class AnsibleLintWrapperTest(unittest.TestCase): def setUp(self): @@ -31,12 +50,18 @@ class AnsibleLintWrapperTest(unittest.TestCase): self.repo = self.tmp / "repo" (self.repo / "scripts").mkdir(parents=True) shutil.copy(SCRIPT, self.repo / "scripts" / "ansible-lint.sh") + self.galaxy("mortis", "kamino") self.bin = self.tmp / "bin" self.bin.mkdir() stub = self.bin / "ansible-lint" stub.write_text(STUB) stub.chmod(0o755) + def galaxy(self, namespace, name): + (self.repo / "galaxy.yml").write_text( + f"---\nnamespace: {namespace}\nname: {name}\nversion: 1.0.0\n" + ) + def run_wrapper(self, cwd=None, **env): base = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.tmp)} return subprocess.run( @@ -57,16 +82,60 @@ class AnsibleLintWrapperTest(unittest.TestCase): self.install_collections() result = self.run_wrapper() self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("args=--offline --nocolor", result.stdout) - self.assertIn(f"home={self.repo / '.ansible'}", result.stdout) - self.assertIn(f"path={self.repo / '.ansible' / 'collections'}", result.stdout) + seen = parsed(result.stdout) + self.assertEqual(seen["args"], "--offline --nocolor") + self.assertEqual(seen["home"], str(self.repo / ".ansible")) + # The temporary link root comes first, then the clone's pinned collections. + self.assertEqual( + seen["path"], f"{seen['first']}:{self.repo / '.ansible' / 'collections'}" + ) - def test_leaves_a_preset_collections_path_alone(self): + def test_leaves_a_preset_collections_path_after_the_link_root(self): # CI sets it (the ci image bakes the collections into /opt/collections), even with none in the clone. result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections") self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("path=/opt/collections", result.stdout) - self.assertIn("home=unset", result.stdout) + seen = parsed(result.stdout) + self.assertEqual(seen["path"], f"{seen['first']}:/opt/collections") + self.assertEqual(seen["home"], "unset") + + def test_links_the_checkout_as_the_collection(self): + result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + parsed(result.stdout)["link"], [f"mortis/kamino -> {self.repo}"] + ) + + def test_takes_the_collection_name_from_galaxy_yml(self): + self.galaxy("acme", "widgets") + result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + parsed(result.stdout)["link"], [f"acme/widgets -> {self.repo}"] + ) + + def test_fails_without_a_namespace_and_name(self): + (self.repo / "galaxy.yml").write_text("---\nversion: 1.0.0\n") + result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections") + self.assertNotEqual(result.returncode, 0) + self.assertIn("galaxy.yml", result.stderr) + self.assertNotIn("args=", result.stdout) + + def test_removes_the_link_root_afterwards(self): + result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections") + first = pathlib.Path(parsed(result.stdout)["first"]) + self.assertNotEqual(first, pathlib.Path("/opt/collections")) + self.assertFalse(first.exists()) + # The checkout itself is untouched: only the link went. + self.assertTrue((self.repo / "galaxy.yml").is_file()) + + def test_removes_the_link_root_and_keeps_the_exit_code_when_ansible_lint_fails( + self, + ): + result = self.run_wrapper( + ANSIBLE_COLLECTIONS_PATH="/opt/collections", STUB_EXIT="3" + ) + self.assertEqual(result.returncode, 3) + self.assertFalse(pathlib.Path(parsed(result.stdout)["first"]).exists()) def test_fails_with_the_fix_when_the_collections_are_not_installed(self): result = self.run_wrapper() @@ -80,7 +149,7 @@ class AnsibleLintWrapperTest(unittest.TestCase): elsewhere.mkdir() result = self.run_wrapper(cwd=elsewhere) self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn(f"cwd={self.repo}", result.stdout) + self.assertEqual(parsed(result.stdout)["cwd"], str(self.repo)) if __name__ == "__main__": diff --git a/tests/scripts/test_ansible_test_sanity_wrapper.py b/tests/scripts/test_ansible_test_sanity_wrapper.py new file mode 100644 index 0000000..de4819b --- /dev/null +++ b/tests/scripts/test_ansible_test_sanity_wrapper.py @@ -0,0 +1,218 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Tests for scripts/ansible-test-sanity.sh against a throwaway git repository and stub tools. + +Run with: python3 -m unittest discover -s tests/scripts +""" + +import os +import pathlib +import shutil +import subprocess +import tempfile +import unittest + +SCRIPT = ( + pathlib.Path(__file__).resolve().parents[2] / "scripts" / "ansible-test-sanity.sh" +) + +ANSIBLE_STUB = """#!/bin/sh +echo "ansible [core ${STUB_CORE:-2.22.0}]" +echo " config file = None" +""" + +# Prints what the wrapper hands to ansible-test: arguments, the directory it runs in, the ignore +# file it will read, and the files of the copy it runs on. +ANSIBLE_TEST_STUB = """#!/bin/sh +echo "args=$*" +echo "cwd=$(pwd -P)" +echo "files=$(find . -type f | sort | tr '\\n' ' ')" +echo "plugins=$(cat plugins.txt 2>/dev/null)" +for f in tests/sanity/ignore-*.txt; do + echo "ignore:$f=$(tr '\\n' '|' < "$f")" +done +exit "${STUB_EXIT:-0}" +""" + + +def parsed(stdout): + """{key: value} of the stub's output lines.""" + out = {} + for line in stdout.splitlines(): + parts = line.partition("=") + out[parts[0]] = parts[2] + return out + + +@unittest.skipUnless( + shutil.which("bash") and shutil.which("git"), "bash and git are required" +) +class AnsibleTestSanityWrapperTest(unittest.TestCase): + def setUp(self): + self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="kamino-sanitywrap-")).resolve() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.repo = self.tmp / "repo" + (self.repo / "scripts").mkdir(parents=True) + (self.repo / "tests" / "sanity").mkdir(parents=True) + shutil.copy(SCRIPT, self.repo / "scripts" / "ansible-test-sanity.sh") + (self.repo / "galaxy.yml").write_text( + "---\nnamespace: mortis\nname: kamino\nversion: 1.0.0\n" + ) + (self.repo / "tests" / "sanity" / "ignore-common.txt").write_text( + "COPYING no-smart-quotes\n" + ) + (self.repo / "plugins.txt").write_text("committed\n") + self.bin = self.tmp / "bin" + self.bin.mkdir() + for name, body in ( + ("ansible", ANSIBLE_STUB), + ("ansible-test", ANSIBLE_TEST_STUB), + ): + tool = self.bin / name + tool.write_text(body) + tool.chmod(0o755) + self.env = { + "PATH": f"{self.bin}:{os.environ['PATH']}", + "HOME": str(self.tmp), + "GIT_CONFIG_GLOBAL": str(self.tmp / "gitconfig"), + "GIT_CONFIG_NOSYSTEM": "1", + } + self.git("init", "--quiet") + self.git("add", ".") + self.git( + "-c", + "user.name=t", + "-c", + "user.email=t@localhost", + "commit", + "-q", + "-m", + "x", + ) + + def git(self, *args): + subprocess.run( + ["git", "-C", str(self.repo), *args], + env=self.env, + check=True, + capture_output=True, + ) + + def run_wrapper(self, *args, cwd=None, **env): + return subprocess.run( + ["bash", str(self.repo / "scripts" / "ansible-test-sanity.sh"), *args], + env={**self.env, **env}, + cwd=str(cwd or self.repo), + capture_output=True, + text=True, + check=False, + ) + + def test_runs_sanity_with_requirements_in_a_collection_directory(self): + result = self.run_wrapper() + self.assertEqual(result.returncode, 0, result.stderr) + seen = parsed(result.stdout) + self.assertEqual(seen["args"], "sanity --requirements") + self.assertTrue( + seen["cwd"].endswith("/ansible_collections/mortis/kamino"), seen["cwd"] + ) + self.assertNotEqual(seen["cwd"], str(self.repo)) + + def test_passes_extra_arguments_to_ansible_test(self): + result = self.run_wrapper("--test", "pylint") + self.assertEqual( + parsed(result.stdout)["args"], "sanity --requirements --test pylint" + ) + + def test_takes_the_collection_name_from_galaxy_yml(self): + (self.repo / "galaxy.yml").write_text( + "---\nnamespace: acme\nname: widgets\nversion: 1.0.0\n" + ) + self.git("add", "galaxy.yml") + self.git( + "-c", + "user.name=t", + "-c", + "user.email=t@localhost", + "commit", + "-q", + "-m", + "y", + ) + seen = parsed(self.run_wrapper().stdout) + self.assertTrue( + seen["cwd"].endswith("/ansible_collections/acme/widgets"), seen["cwd"] + ) + + def test_checks_the_committed_files_only(self): + (self.repo / "plugins.txt").write_text("changed but not committed\n") + (self.repo / "untracked.txt").write_text("new\n") + seen = parsed(self.run_wrapper().stdout) + self.assertIn("./plugins.txt", seen["files"]) + self.assertNotIn("untracked.txt", seen["files"]) + self.assertNotIn(".git/", seen["files"]) + # The copy holds the committed content, not the edit. + self.assertEqual(seen["plugins"], "committed") + + def test_copies_the_common_ignore_file_to_the_name_of_the_core_version(self): + seen = parsed(self.run_wrapper().stdout) + self.assertEqual( + seen["ignore:tests/sanity/ignore-2.22.txt"], "COPYING no-smart-quotes|" + ) + + def test_appends_the_lines_of_a_committed_core_specific_ignore_file(self): + (self.repo / "tests" / "sanity" / "ignore-2.22.txt").write_text( + "plugins.txt shebang\n" + ) + self.git("add", "tests") + self.git( + "-c", + "user.name=t", + "-c", + "user.email=t@localhost", + "commit", + "-q", + "-m", + "z", + ) + seen = parsed(self.run_wrapper().stdout) + self.assertEqual( + seen["ignore:tests/sanity/ignore-2.22.txt"], + "COPYING no-smart-quotes|plugins.txt shebang|", + ) + + def test_uses_the_installed_core_version_for_the_ignore_file_name(self): + seen = parsed(self.run_wrapper(STUB_CORE="2.23.1").stdout) + self.assertIn("ignore:tests/sanity/ignore-2.23.txt", seen) + + def test_keeps_the_exit_code_of_ansible_test_and_removes_the_copy(self): + result = self.run_wrapper(STUB_EXIT="4") + self.assertEqual(result.returncode, 4) + copy = pathlib.Path(parsed(result.stdout)["cwd"]) + self.assertFalse(copy.exists()) + + def test_fails_with_the_fix_when_a_tool_is_missing(self): + (self.bin / "ansible-test").unlink() + result = self.run_wrapper(PATH=f"{self.bin}:/usr/bin:/bin") + self.assertNotEqual(result.returncode, 0) + self.assertIn("scripts/dev-setup.sh", result.stderr) + + def test_fails_without_a_namespace_and_name(self): + (self.repo / "galaxy.yml").write_text("---\nversion: 1.0.0\n") + result = self.run_wrapper() + self.assertNotEqual(result.returncode, 0) + self.assertIn("galaxy.yml", result.stderr) + self.assertNotIn("args=", result.stdout) + + def test_runs_from_the_repository_whatever_the_caller_directory(self): + elsewhere = self.tmp / "elsewhere" + elsewhere.mkdir() + result = self.run_wrapper(cwd=elsewhere) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn( + "/ansible_collections/mortis/kamino", parsed(result.stdout)["cwd"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/scripts/test_dev_setup.py b/tests/scripts/test_dev_setup.py index 17f40d5..483467a 100644 --- a/tests/scripts/test_dev_setup.py +++ b/tests/scripts/test_dev_setup.py @@ -52,7 +52,7 @@ 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; do +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" @@ -143,7 +143,7 @@ class DevSetupTest(unittest.TestCase): repo = self.make_repo() result = self.run_setup(repo) self.assertEqual(result.returncode, 0, result.stderr) - for name in ("pre-commit", "commit-msg"): + 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"")