Fix what ruff 0.17.5's default rule set and the complexity rules report (#112): removeprefix/removesuffix instead of slicing, `_unused` for discarded tuple members, obsolete `noqa: E402` removed, a parenthesised string pair and an immutable class constant in the tests. Three functions stay over a complexity threshold and carry an inline `# noqa` with the rule code and a reason: matrix_of and copy_sources of check_image_versions.py (#96 may replace them) and path_problems of check_tarball.py. No rule is ignored globally and no threshold is tuned. ruff writes .ruff_cache/ into the checkout, which test_real_build_passes caught in the Collection archive: add it to galaxy.yml build_ignore. ruff.toml joins the molecule selector's IGNORED paths, since no scenario reads it. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
316 lines
12 KiB
Python
316 lines
12 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
|
|
|
|
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, _reason = 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, _reason = 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, _reason = 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, _reason = 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, _reason = 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, _reason = sel.select(ALL, ["roles/gone/tasks/main.yml"])
|
|
self.assertEqual(chosen, [])
|
|
|
|
def test_ignored_patterns_are_not_prefix_tricks(self):
|
|
chosen, _reason = 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, _err = self.run_main(
|
|
["main"], {"EVENT_NAME": "pull_request"}
|
|
)
|
|
self.assertEqual((code, out), (0, ["roles/docker/molecule/default"]))
|
|
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "push"})
|
|
self.assertEqual(len(out), 3)
|
|
code, out, _err = 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, _err = 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, _err = 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, _err = 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, _err = 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, _err = 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")
|
|
_chosen, 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, _err = 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, _reason = 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()
|