Files
Kamino/tests/scripts/test_ansible_test_sanity_wrapper.py
T
Defame1297andClaude Sonnet 5.5 574c0d00f9 ci(scripts): add a wrapper that runs ansible-test sanity on HEAD
ansible-test only runs a collection from an ansible_collections/<namespace>/<name> directory, so scripts/ansible-test-sanity.sh copies HEAD (git archive: the committed files only) into a temporary one, applies the Build job's ignore-file step and runs ansible-test sanity --requirements, passing extra arguments through. The sanity tests carry their own pylint, pep8 and shellcheck settings and also scan the Python under tests/, which ruff and the other hooks do not (the Build check failed on a name only that pylint disallows). The hook that runs it before a push follows in the next commit.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 15:49:51 +00:00

219 lines
7.4 KiB
Python

# 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()