Files
Kamino/tests/scripts/test_select_molecule_scenarios.py
T
Defame1297andClaude Sonnet 5.5 4d330d41c7
Build / build (pull_request) Failing after 12s
Lint / lint (pull_request) Successful in 21s
Molecule / molecule (pull_request) Successful in 6m53s
ci(molecule): run only the scenarios of the roles a pull request changes
A pull request now runs the scenarios of the roles it touches, none when it
touches only paths no scenario reads, and everything for any other file, for
every push to main and for manual dispatch. The job stays unconditional so
Molecule can remain a required check.

scripts/select_molecule_scenarios.py makes the choice and is run from the base
branch's copy, so a pull request cannot edit its own rules. A changed role
that exists but has no scenario fails instead of passing with nothing tested.

The scenario loop no longer gives molecule the list as stdin, which a child
could have drained, and fails when it ran fewer scenarios than were selected.

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

249 lines
11 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import contextlib
import io
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
import yaml
REPO = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / "scripts"))
import select_molecule_scenarios as sel # noqa: E402
ALL = [
"extensions/molecule/image-smoke",
"extensions/molecule/image-smoke-2604",
"roles/docker/molecule/default",
"roles/fail2ban/molecule/default",
"roles/system_baseline/molecule/default",
]
class SelectTest(unittest.TestCase):
def test_role_change_selects_only_that_role(self):
chosen, _ = sel.select(ALL, ["roles/docker/tasks/main.yml", "roles/docker/molecule/default/verify.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
def test_two_roles(self):
chosen, _ = sel.select(ALL, ["roles/fail2ban/defaults/main.yml", "roles/docker/meta/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default", "roles/fail2ban/molecule/default"])
def test_ignored_only_selects_nothing(self):
chosen, _ = sel.select(ALL, ["docs/x.md", "changelogs/fragments/a.yml", "README.md", "images/ci/Dockerfile"])
self.assertEqual(chosen, [])
def test_ignored_does_not_mask_a_role(self):
chosen, _ = sel.select(ALL, ["docs/x.md", "roles/docker/tasks/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
def test_anything_else_selects_everything(self):
for path in ("galaxy.yml", "meta/runtime.yml", "plugins/modules/x.py", "extensions/molecule/image-smoke/molecule.yml",
".gitea/workflows/molecule.yml", "scripts/select_molecule_scenarios.py",
"tests/unit/x.py",
"new_top_level_file", "roles/README.md"):
chosen, _ = sel.select(ALL, ["roles/docker/tasks/main.yml", path])
self.assertEqual(chosen, ALL, path)
def test_deleted_role_selects_nothing_of_its_own(self):
chosen, _ = sel.select(ALL, ["roles/gone/tasks/main.yml"])
self.assertEqual(chosen, [])
def test_ignored_patterns_are_not_prefix_tricks(self):
chosen, _ = sel.select(ALL, ["docsx/y"])
self.assertEqual(chosen, ALL)
class MainTest(unittest.TestCase):
def setUp(self):
# main() runs git in the current directory: a hook's GIT_DIR must not redirect it.
patcher = mock.patch.dict(os.environ)
patcher.start()
self.addCleanup(patcher.stop)
for key in [k for k in os.environ if k.startswith("GIT_")]:
del os.environ[key]
def run_main(self, argv, env):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = sel.main(["x"] + argv, env)
return code, out.getvalue().split(), err.getvalue()
def make_repo(self, root):
for rel in ("extensions/molecule/image-smoke", "roles/docker/molecule/default", "roles/fail2ban/molecule/default"):
d = pathlib.Path(root, rel)
d.mkdir(parents=True)
(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", "-C", root, "-c", "user.name=t", "-c", "[email protected]",
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True, env=env)
def topic_repo(self, root, files):
"""A repo on `topic` whose one commit over `main` adds `files` (relative path -> text)."""
self.make_repo(root)
self.git(root, "init", "-q", "-b", "main")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "base")
self.git(root, "switch", "-qc", "topic")
for rel, text in files.items():
f = pathlib.Path(root, rel)
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(text)
self.git(root, "add", "-A")
self.git(root, "commit", "-q", "--allow-empty", "-m", "change")
def in_dir(self, root):
cwd = os.getcwd()
os.chdir(root)
self.addCleanup(os.chdir, cwd)
def test_pull_request_is_narrowed_and_push_is_not(self):
with tempfile.TemporaryDirectory() as root:
self.make_repo(root)
self.git(root, "init", "-q", "-b", "main")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "base")
self.git(root, "switch", "-qc", "topic")
pathlib.Path(root, "roles/docker/tasks").mkdir()
pathlib.Path(root, "roles/docker/tasks/main.yml").write_text("---\n")
self.git(root, "add", "-A")
self.git(root, "commit", "-q", "--allow-empty", "-m", "change")
cwd = os.getcwd()
os.chdir(root)
try:
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, ["roles/docker/molecule/default"]))
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "push"})
self.assertEqual(len(out), 3)
code, out, _ = self.run_main([], {"EVENT_NAME": "pull_request"})
self.assertEqual(len(out), 3)
code, out, err = self.run_main(["no-such-ref"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3))
self.assertIn("::warning::", err)
finally:
os.chdir(cwd)
def test_empty_base_ref_argument_runs_all(self):
with tempfile.TemporaryDirectory() as root:
self.make_repo(root)
self.in_dir(root)
code, out, _ = self.run_main([""], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3))
def test_changed_role_without_a_scenario_fails(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {"roles/newrole/tasks/main.yml": "---\n"})
self.in_dir(root)
code, out, err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (1, []))
self.assertIn("::error::changed role without a molecule scenario: newrole", err)
def test_deleted_role_is_not_an_error(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {})
self.git(root, "rm", "-rq", "roles/fail2ban")
self.git(root, "commit", "-qm", "drop")
self.in_dir(root)
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, []))
def test_ignored_only_diff_passes_empty(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {"docs/a.md": "x\n"})
self.in_dir(root)
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, []))
def test_non_utf8_path_does_not_crash(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {})
broot = os.fsencode(root)
os.makedirs(os.path.join(broot, b"docs"))
with open(os.path.join(broot, b"docs", b"\xff.md"), "wb") as f:
f.write(b"x\n")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "odd")
self.in_dir(root)
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, [])) # docs/* is ignored whatever the bytes
with open(os.path.join(broot, b"top\xff"), "wb") as f:
f.write(b"x")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "odd2")
code, out, _ = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3)) # not ignored: everything
def test_too_many_arguments_is_usage(self):
code, out, err = self.run_main(["a", "b"], {})
self.assertEqual((code, out), (2, []))
self.assertIn("usage:", err)
def test_control_characters_are_escaped_in_notices(self):
self.assertEqual(sel.printable("a\n::add-mask::b"), "a\\n::add-mask::b")
_, reason = sel.select(ALL, ["zz\n::add-mask::foo"])
self.assertNotIn("\n", reason)
def test_no_scenario_at_all_fails(self):
with tempfile.TemporaryDirectory() as root:
cwd = os.getcwd()
os.chdir(root)
try:
code, out, _ = self.run_main([], {})
self.assertEqual((code, out), (1, []))
finally:
os.chdir(cwd)
def test_every_tracked_file_is_ignored_or_selects_everything_or_is_a_role_file(self):
tracked = subprocess.run(["git", "-C", str(REPO), "ls-files", "-z"], capture_output=True, check=True,
env={k: v for k, v in os.environ.items() if not k.startswith("GIT_")}).stdout
scenarios = sel.discover(str(REPO))
for raw in tracked.split(b"\0"):
if not raw:
continue
path = os.fsdecode(raw)
if sel.is_ignored(path) or path.startswith("roles/"):
continue
chosen, _ = sel.select(scenarios, [path], str(REPO))
self.assertEqual(chosen, scenarios, path)
def test_no_role_refers_to_another_role(self):
# The selection assumes roles are independent: a role that includes another would need a
# dependency rule in select(). Fail here instead of silently skipping the other's scenario.
roles = sorted(p.name for p in (REPO / "roles").iterdir() if p.is_dir())
for role in roles:
others = [r for r in roles if r != role]
for path in (REPO / "roles" / role).rglob("*"):
if not path.is_file():
continue
text = path.read_text(errors="ignore")
for other in others:
self.assertNotIn(f"mortis.kamino.{other}", text, f"{path.relative_to(REPO)} refers to {other}")
meta = REPO / "roles" / role / "meta" / "main.yml"
if meta.is_file():
data = yaml.safe_load(meta.read_text()) or {}
self.assertEqual(data.get("dependencies") or [], [], f"{role} declares role dependencies")
def test_literal_ignored_entries_exist(self):
for pattern in sel.IGNORED:
if "*" not in pattern:
self.assertTrue((REPO / pattern).exists(), f"{pattern} is on IGNORED but is not in the repository")
def test_discover_matches_the_repository(self):
found = sel.discover(str(REPO))
self.assertIn("extensions/molecule/image-smoke", found)
self.assertTrue(all((REPO / d / "molecule.yml").is_file() for d in found))
if __name__ == "__main__":
unittest.main()