feat(ci): run the molecule scenarios of the roles that use a changed role
The scenario picker assumed the roles were independent and a test enforced it. Wave 2 roles call other Collection roles (traefik includes ufw and the internal _binary_update), so a change to the called role must also run the callers' scenarios. A role uses another when a file under its directory names it as mortis.kamino.<role>; the relation is followed transitively and read from the tree under test. A role the pull request deletes or renames still counts as used by the roles that name it, so their scenarios run and show the break. The independence test becomes a test that fails a bare or templated role name in an include, import (also in the k=v form), play roles: entry or meta dependency, and task includes that reach outside the role through '..'. It walks .yml and .yaml files and has its own cases for each form. This lands before the first such role because the workflow runs the picker from the base branch's copy. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
This commit is contained in:
1 parent
30ce518f00
commit
fcb51da065
3 files changed
+271
-25
No files matched your search
@@ -6,6 +6,7 @@ import contextlib
|
||||
import io
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -18,6 +19,75 @@ 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",
|
||||
@@ -83,6 +153,104 @@ class SelectTest(unittest.TestCase):
|
||||
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.
|
||||
@@ -193,7 +361,8 @@ class MainTest(unittest.TestCase):
|
||||
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
|
||||
"::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):
|
||||
@@ -272,24 +441,20 @@ class MainTest(unittest.TestCase):
|
||||
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.
|
||||
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:
|
||||
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():
|
||||
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 [],
|
||||
@@ -297,6 +462,29 @@ class MainTest(unittest.TestCase):
|
||||
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:
|
||||
|
||||
Reference in new issue
Block a user