Files
Kamino/tests/scripts/test_select_molecule_scenarios.py
T
Defame1297andClaude Opus 5.5 0837cc387f
Build / build (pull_request) Successful in 15s
Gitea release key / check (pull_request) Successful in 9s
Lint / lint (pull_request) Successful in 51s
Molecule / molecule (pull_request) Canceled after 36s
ci(gitea): warn before the Gitea release key stops verifying releases
The gitea role accepts a release only when it carries a valid signature by
gitea_gpg_key_id or one of its subkeys, so an expired, revoked or replaced
Gitea release key makes every install and update fail closed, without
warning, on the day it happens.

scripts/check_gitea_release_key.py reads the pins from the role defaults,
fetches the release key into a throwaway keyring and only the .asc of the
pinned release (never the binary), and fails when the primary key or a
signing subkey expires within 60 days, is revoked or expired, or when a
signature in the .asc is not by a valid signing key of the pinned key. Its
docstring says what to do on a failure.

The Gitea release key workflow runs it weekly, by hand, and on pull requests
that change the role defaults or the check, so a gitea_version bump is
checked against the new release's signature. It runs in the ci image at the
pin of lint.yml; that image has gpgv but not gpg, so the job installs gpg and
gpg-agent from the Ubuntu archive per run instead of making the check an
image input. The tests that make keys skip without gpg, so the Lint job's
unittest run (no gpg) still covers the parsing and rendering tests.

The workflow pins the ci image, so it joins the pin consumers of
check_image_versions.py and check_bot_pr_diff.py: Renovate's pin follow-up
edits every workflow, and the bot-diff gate would otherwise refuse that pull
request. The new workflow and script are on the molecule selector's IGNORED
list, since no scenario reads them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-11-22 07:29:31 +00:00

536 lines
21 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 shutil
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
ROLE_KEYS = {
f"{prefix}{verb}"
for prefix in ("", "ansible.builtin.", "ansible.legacy.")
for verb in ("include_role", "import_role")
}
TASK_KEYS = {
f"{prefix}{verb}"
for prefix in ("", "ansible.builtin.", "ansible.legacy.")
for verb in ("include_tasks", "import_tasks")
}
def _arg(value, key):
"""`key` of a module argument given as a mapping, a k=v string or a bare string."""
if isinstance(value, dict):
return value.get(key)
if not isinstance(value, str):
return None
for word in value.split():
if word.startswith(f"{key}="):
return word[len(key) + 1 :]
return None if "=" in value else value
def _name_problem(name, how, roles):
if not isinstance(name, str):
return []
if "{{" in name:
return [f"{how} a templated role name {name!r}"]
if name in roles:
return [f"{how} {name} by its bare name"]
return []
def _play_roles_problems(play, roles):
problems = []
for entry in play.get("roles") if isinstance(play.get("roles"), list) else []:
name = (
entry.get("role", entry.get("name")) if isinstance(entry, dict) else entry
)
problems += _name_problem(name, "a play's roles: uses", roles)
return problems
def _key_problems(key, value, roles):
if key in ROLE_KEYS:
return _name_problem(_arg(value, "name"), f"{key} uses", roles)
if key in TASK_KEYS:
target = _arg(value, "file")
if isinstance(target, str) and ".." in target:
return [f"{key} reaches outside the role: {target!r}"]
return []
def role_use_problems(node, roles, in_list=False):
"""The ways `node` (parsed YAML) uses a role that users() could not see."""
problems = []
if isinstance(node, dict):
if in_list:
problems += _play_roles_problems(node, roles)
for key, value in node.items():
problems += _key_problems(key, value, roles)
problems += role_use_problems(value, roles)
elif isinstance(node, list):
for item in node:
problems += role_use_problems(item, roles, in_list=True)
return problems
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):
# A fixture tree with the roles of ALL and no use of one role by another, so that the
# expectations do not depend on which roles of this repository use which (UsersTest
# covers the users).
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = tmp.name
for scenario in ALL:
pathlib.Path(self.root, scenario).mkdir(parents=True)
pathlib.Path(self.root, scenario, "molecule.yml").write_text("---\n")
if scenario.startswith("roles/"):
tasks = pathlib.Path(self.root, *scenario.split("/")[:2], "tasks")
tasks.mkdir()
(tasks / "main.yml").write_text("---\n")
def select(self, changed):
return sel.select(ALL, changed, self.root)
def test_role_change_selects_only_that_role(self):
chosen, _reason = self.select(
["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 = self.select(
["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 = self.select(
[
"docs/x.md",
"changelogs/fragments/a.yml",
"README.md",
"images/ci/Dockerfile",
],
)
self.assertEqual(chosen, [])
def test_gitea_release_key_check_selects_nothing(self):
# The check reads roles/gitea/defaults/main.yml, but no scenario reads the check.
chosen, _reason = self.select(
[
".gitea/workflows/gitea-release-key.yml",
"scripts/check_gitea_release_key.py",
"tests/scripts/test_check_gitea_release_key.py",
],
)
self.assertEqual(chosen, [])
def test_role_rules_for_agents_select_nothing(self):
# roles/AGENTS.md is contributor guidance that no scenario reads (it is not shipped).
chosen, _reason = sel.select(ALL, ["roles/AGENTS.md"])
self.assertEqual(chosen, [])
def test_ignored_does_not_mask_a_role(self):
chosen, _reason = self.select(["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 = self.select(["roles/docker/tasks/main.yml", path])
self.assertEqual(chosen, ALL, path)
def test_deleted_role_selects_nothing_of_its_own(self):
chosen, _reason = self.select(["roles/gone/tasks/main.yml"])
self.assertEqual(chosen, [])
def test_ignored_patterns_are_not_prefix_tricks(self):
chosen, _reason = self.select(["docsx/y"])
self.assertEqual(chosen, ALL)
class UsersTest(unittest.TestCase):
SCENARIOS = (
"roles/base/molecule/default",
"roles/_helper/molecule/default",
"roles/service/molecule/default",
"roles/other/molecule/default",
)
def tree(self, root, files):
for rel, text in files.items():
f = pathlib.Path(root, rel)
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(text)
for s in self.SCENARIOS:
pathlib.Path(root, s).mkdir(parents=True, exist_ok=True)
pathlib.Path(root, s, "molecule.yml").write_text("---\n")
def chain(self, root):
# service uses _helper, _helper uses base; other uses nothing and names itself.
self.tree(
root,
{
"roles/service/tasks/main.yml": "name: mortis.kamino._helper\n",
"roles/_helper/tasks/main.yml": "name: mortis.kamino.base\n",
"roles/base/tasks/main.yml": "---\n",
"roles/other/molecule/default/converge.yml": "mortis.kamino.other\n",
},
)
def test_a_change_selects_its_users_transitively(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
chosen, reason = sel.select(
self.SCENARIOS, ["roles/base/tasks/main.yml"], root
)
self.assertEqual(
sorted(chosen),
[
"roles/_helper/molecule/default",
"roles/base/molecule/default",
"roles/service/molecule/default",
],
)
self.assertIn("their users: _helper, service", reason)
def test_a_user_change_does_not_select_what_it_uses(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
chosen, _reason = sel.select(
self.SCENARIOS, ["roles/service/tasks/main.yml"], root
)
self.assertEqual(chosen, ["roles/service/molecule/default"])
def test_self_and_unknown_names_are_not_uses(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
pathlib.Path(root, "roles/other/tasks").mkdir(parents=True)
pathlib.Path(root, "roles/other/tasks/main.yml").write_text(
"mortis.kamino.nosuchrole\n"
)
self.assertEqual(
sel.users(root), {"_helper": {"service"}, "base": {"_helper"}}
)
chosen, _reason = sel.select(
self.SCENARIOS, ["roles/other/tasks/main.yml"], root
)
self.assertEqual(chosen, ["roles/other/molecule/default"])
def test_a_user_without_a_scenario_fails(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
self.tree(root, {"roles/bare/tasks/main.yml": "mortis.kamino.base\n"})
with self.assertRaisesRegex(ValueError, "bare"):
sel.select(self.SCENARIOS, ["roles/base/tasks/main.yml"], root)
def test_a_deleted_role_still_selects_its_users(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
shutil.rmtree(pathlib.Path(root, "roles/base"))
scenarios = [s for s in self.SCENARIOS if not s.startswith("roles/base/")]
chosen, _reason = sel.select(scenarios, ["roles/base/tasks/main.yml"], root)
self.assertEqual(
sorted(chosen),
["roles/_helper/molecule/default", "roles/service/molecule/default"],
)
def test_cycles_terminate(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
pathlib.Path(root, "roles/base/tasks/main.yml").write_text(
"mortis.kamino.service\n"
)
chosen, _reason = sel.select(
self.SCENARIOS, ["roles/base/tasks/main.yml"], root
)
self.assertEqual(len(chosen), 3)
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::role without a molecule scenario (changed, or a user of a changed role): 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_roles_call_each_other_by_full_name_only(self):
# The selection finds a role's users by the text mortis.kamino.<role> (users()). A use
# by a bare or templated name, a meta dependency, or tasks reached by a relative path
# into another role would be one it cannot see, so its users' scenarios would be
# skipped. Fail here instead.
roles = sorted(p.name for p in (REPO / "roles").iterdir() if p.is_dir())
for role in roles:
for path in sorted((REPO / "roles" / role).rglob("*")):
if path.suffix in (".yml", ".yaml") and path.is_file():
for problem in role_use_problems(
yaml.safe_load(path.read_text()), roles
):
self.fail(f"{path.relative_to(REPO)}: {problem}")
for meta in (REPO / "roles" / role / "meta").glob("main.y*ml"):
data = yaml.safe_load(meta.read_text()) or {}
self.assertEqual(
data.get("dependencies") or [],
[],
f"{role} declares role dependencies",
)
def test_role_use_problems_catches_the_hidden_forms(self):
roles = ["ufw", "traefik"]
for doc in (
[{"ansible.builtin.include_role": {"name": "ufw"}}],
[{"import_role": "name=ufw tasks_from=x"}],
[{"include_role": {"name": "{{ dep }}"}}],
[{"include_role": {"name": "mortis.kamino.{{ dep }}"}}],
[{"hosts": "all", "roles": ["ufw"]}],
[{"hosts": "all", "roles": [{"role": "ufw"}]}],
[{"hosts": "all", "roles": [{"name": "{{ r }}"}]}],
[{"ansible.builtin.include_tasks": "../../ufw/tasks/x.yml"}],
[{"import_tasks": {"file": "{{ role_path }}/../ufw/tasks/x.yml"}}],
):
self.assertTrue(role_use_problems(doc, roles), doc)
for doc in (
[{"include_role": {"name": "mortis.kamino.ufw"}}],
[{"hosts": "all", "roles": ["mortis.kamino.traefik"]}],
[{"include_role": {"name": "community.general.thing"}}],
[{"include_tasks": "download.yml"}],
{"roles": "not a play"},
):
self.assertEqual(role_use_problems(doc, roles), [], doc)
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()