Files
Kamino/tests/scripts/test_select_molecule_scenarios.py
T
Defame1297 2d1f142662 ci(molecule): skip the Molecule runner when no scenario is selected
A pull request that selects no scenario still took the single Molecule
runner slot to pull the controller image, select nothing and exit.

The workflow now has three jobs. select runs the selector from main's
copy in a job container on kamino-docker, in the molecule-controller pin,
and outputs the selected list. scenarios runs it on kamino-molecule and
is skipped when the list is empty. result runs always() and is the one
job to require: it fails unless select passed and scenarios passed or
was skipped for an empty list, because Gitea counts a skipped job as
passing. Scheduled and dispatched runs still select every scenario.

container.image cannot read env, so the controller pin is written in all
three jobs; a test holds the copies equal. The pin moves to 0.1.1, which
has git for the select job's checkout. Branch protection must then
require "Molecule / Result (pull_request)".

Closes #433

Assisted-by: Claude Code
2026-12-01 23:20:01 +00:00

887 lines
35 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_root_agent_guidance_selects_nothing(self):
# The root AGENTS.md is contributor guidance that no scenario reads (it is not shipped).
chosen, _reason = sel.select(ALL, ["AGENTS.md"])
self.assertEqual(chosen, [])
def test_nested_agent_guidance_selects_nothing(self):
chosen, _reason = self.select(
[
".gitea/workflows/AGENTS.md",
"scripts/AGENTS.md",
"roles/docker/AGENTS.md",
],
)
self.assertEqual(chosen, [])
def test_agent_tool_settings_select_nothing(self):
# Claude Code reads .claude/ on a contributor's machine; no scenario reads it.
chosen, _reason = self.select(
[".claude/settings.json", ".claude/hooks/guard.sh"],
)
self.assertEqual(chosen, [])
def test_role_readme_selects_nothing(self):
# A role's README is documentation; its scenarios and its users' do not read it.
chosen, _reason = self.select(["roles/docker/README.md"])
self.assertEqual(chosen, [])
def test_selector_and_dev_python_select_nothing(self):
# Molecule runs the base copy of the selector and the runner's own venv.
chosen, _reason = self.select(
[
"scripts/select_molecule_scenarios.py",
"scripts/lock-requirements.sh",
".python-version",
],
)
self.assertEqual(chosen, [])
def test_issue_and_pull_request_templates_select_nothing(self):
# Gitea reads them for its web forms; no scenario does, and they are not shipped.
chosen, _reason = self.select(
[
".gitea/ISSUE_TEMPLATE/config.yml",
".gitea/ISSUE_TEMPLATE/bug.yml",
".gitea/PULL_REQUEST_TEMPLATE.md",
],
)
self.assertEqual(chosen, [])
def test_a_ci_pin_bump_in_lint_or_build_selects_nothing(self):
chosen, _reason = self.select(
[".gitea/workflows/lint.yml", ".gitea/workflows/build.yml"]
)
self.assertEqual(chosen, [])
def test_lint_requirements_select_nothing(self):
# requirements-dev.* pin Lint's tools; Molecule's come from requirements-molecule.*.
chosen, _reason = self.select(["requirements-dev.txt", "requirements-dev.lock"])
self.assertEqual(chosen, [])
def test_molecule_requirements_select_everything(self):
# An ansible-core or molecule bump there changes the tools every scenario runs with.
for path in ("requirements-molecule.txt", "requirements-molecule.lock"):
chosen, _reason = self.select([path])
self.assertEqual(chosen, ALL, path)
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_galaxy_yml_selects_nothing_and_does_not_mask_a_role(self):
chosen, _reason = self.select(["galaxy.yml"])
self.assertEqual(chosen, [])
chosen, _reason = self.select(["galaxy.yml", "roles/docker/tasks/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
def test_anything_else_selects_everything(self):
for path in (
"meta/runtime.yml",
"plugins/modules/x.py",
"extensions/molecule/requirements.yml",
"extensions/molecule/gone/molecule.yml",
".gitea/workflows/molecule.yml",
"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_image_smoke_change_selects_only_that_scenario(self):
chosen, reason = self.select(
["extensions/molecule/image-smoke-2604/verify.yml"]
)
self.assertEqual(chosen, ["extensions/molecule/image-smoke-2604"])
self.assertIn("image-smoke-2604", reason)
def test_image_smoke_and_role_changes_combine(self):
chosen, _reason = self.select(
[
"extensions/molecule/image-smoke/converge.yml",
"roles/docker/tasks/main.yml",
]
)
self.assertEqual(
chosen,
["extensions/molecule/image-smoke", "roles/docker/molecule/default"],
)
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)
IMG = "git.rkdr.net/mortis/molecule-ubuntu2604:0.1.1@sha256:" + "a" * 64
WORKFLOW_BASE = (
f"env:\n # a comment\n MOLECULE_IMAGE_2604: >-\n {IMG}\nrun: x\n"
)
def run_workflow_topic(self, text):
with tempfile.TemporaryDirectory() as root:
pathlib.Path(root, ".gitea/workflows").mkdir(parents=True)
pathlib.Path(root, sel.WORKFLOW).write_text(self.WORKFLOW_BASE)
self.topic_repo(root, {sel.WORKFLOW: text})
cwd = os.getcwd()
os.chdir(root)
try:
return self.run_main(["main"], {"EVENT_NAME": "pull_request"})
finally:
os.chdir(cwd)
def test_a_comment_only_change_selects_nothing(self):
code, out, _err = self.run_workflow_topic(
self.WORKFLOW_BASE.replace("a comment", "other")
)
self.assertEqual((code, out), (0, []))
def test_a_pin_change_selects_by_image_and_another_change_everything(self):
code, out, err = self.run_workflow_topic(
self.WORKFLOW_BASE.replace(self.IMG, self.IMG.replace("0.1.1", "0.1.2"))
)
# make_repo's scenarios name no image, so the 2604 pin reaches none of them
self.assertEqual((code, out), (0, []))
self.assertIn("image pins changed: MOLECULE_IMAGE_2604", err)
code, out, _err = self.run_workflow_topic(
self.WORKFLOW_BASE.replace("run: x", "run: y")
)
self.assertEqual((code, len(out)), (0, 3))
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_its_own_scenario(
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))
own = "/".join(path.split("/")[:3])
if path.startswith("extensions/molecule/") and own in scenarios:
# A file of one image-smoke scenario selects that scenario only.
self.assertEqual(chosen, [own], path)
else:
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))
class WorkflowPinsTest(unittest.TestCase):
WORKFLOW = (REPO / sel.WORKFLOW).read_text()
def edited(self, old, new):
self.assertIn(old, self.WORKFLOW)
return sel.pin_changes(self.WORKFLOW, self.WORKFLOW.replace(old, new, 1))
def pin(self, key):
lines = self.WORKFLOW.splitlines()
return lines[lines.index(f" {key}: >-") + 1].strip()
def bumped(self, key):
"""The pin of `key` at another digest, as Renovate would write it."""
return self.pin(key).split("@sha256:")[0] + "@sha256:" + "0" * 64
def test_the_workflow_has_each_pin_where_the_selector_looks(self):
for key in ("CONTROLLER_IMAGE", "MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"):
old, new = (
f"{key}: >-\n {v}" for v in (self.pin(key), self.bumped(key))
)
self.assertEqual(self.edited(old, new), {key}, key)
def test_the_workflow_runs_in_the_controller_image_not_ci(self):
# A ci pin bump must touch only Lint and Build, which IGNORED lists (ADR 0003).
self.assertIn("/mortis/molecule-controller:", self.pin("CONTROLLER_IMAGE"))
self.assertNotIn("/mortis/ci:", self.WORKFLOW)
def test_every_controller_pin_is_the_same(self):
# container.image cannot read env, so the select and result jobs repeat CONTROLLER_IMAGE
jobs = yaml.safe_load(self.WORKFLOW)["jobs"]
pins = [
jobs["select"]["container"]["image"],
self.pin("CONTROLLER_IMAGE"),
jobs["result"]["container"]["image"],
]
self.assertEqual(len(set(pins)), 1, pins)
self.assertEqual(self.WORKFLOW.count("/mortis/molecule-controller:"), len(pins))
# Renovate moves all three, which the selector reads as "any other change": every
# scenario, as for CONTROLLER_IMAGE alone.
bumped = self.WORKFLOW.replace(pins[0], self.bumped("CONTROLLER_IMAGE"))
self.assertIsNone(sel.pin_changes(self.WORKFLOW, bumped))
def test_comments_and_blank_lines_change_nothing(self):
self.assertEqual(self.edited("# Behavioural tests", "# Other words"), set())
self.assertEqual(self.edited("\njobs:\n", "\n\n\njobs:\n"), set())
self.assertEqual(
self.edited(
" # Used by the scenarios", " # Read by the scenarios"
),
set(),
)
def test_a_hash_line_inside_a_block_scalar_is_content(self):
# In a `run: |` script a `#` line may be heredoc content, not a comment.
self.assertIsNone(
self.edited(" # Assigned first", " # Set first")
)
def test_two_pins(self):
changed = sel.pin_changes(
self.WORKFLOW,
self.WORKFLOW.replace(
self.pin("MOLECULE_IMAGE"), self.bumped("MOLECULE_IMAGE")
).replace(
self.pin("MOLECULE_IMAGE_2604"), self.bumped("MOLECULE_IMAGE_2604")
),
)
self.assertEqual(changed, {"MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"})
def test_a_pin_value_is_the_next_line_in_renovates_shape(self):
value = self.pin("MOLECULE_IMAGE")
indent = " " * 8
for new in (
# YAML folds the comment into the value: '# x git.rkdr.net/...'
f"{indent}# x\n{indent}{value}",
f"\n{indent}{value}",
f"{indent}{value}\n{indent}more",
f"{indent}other:1",
value,
):
self.assertIsNone(self.edited(f"{indent}{value}", new), new)
def test_a_value_line_replaced_by_an_env_key_is_not_narrowed(self):
self.assertIsNone(
self.edited(
" " + self.pin("MOLECULE_IMAGE_2604"),
" MOLECULE_IMAGE: other:1",
)
)
def test_any_other_change_is_not_narrowed(self):
for old, new in (
("timeout-minutes: 90", "timeout-minutes: 60"),
(" MOLECULE_IMAGE_2604: >-", " MOLECULE_IMAGE_2605: >-"),
(" MOLECULE_IMAGE: >-", " MOLECULE_IMAGE: >"),
("-e MOLECULE_IMAGE -e", "-e"),
(
" # Every scenario, nightly",
" schedule: []\n # Every scenario, nightly",
),
("--init", "--init # not a comment line"),
):
self.assertIsNone(self.edited(old, new), old)
def test_a_pin_and_another_change_is_not_narrowed(self):
text = self.WORKFLOW.replace(
self.pin("MOLECULE_IMAGE_2604"), self.bumped("MOLECULE_IMAGE_2604")
).replace("timeout-minutes: 90", "timeout-minutes: 60")
self.assertIsNone(sel.pin_changes(self.WORKFLOW, text))
SCENARIO_IMAGES = {
"extensions/molecule/image-smoke": "image: ${MOLECULE_IMAGE}",
"extensions/molecule/image-smoke-2604": "image: ${MOLECULE_IMAGE_2604}",
"roles/docker/molecule/default": "${MOLECULE_IMAGE} ${MOLECULE_IMAGE_2604}",
"roles/fail2ban/molecule/default": "image: ${MOLECULE_IMAGE}",
"roles/system_baseline/molecule/default": "image: ubuntu:24.04",
}
class SelectByPinTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = tmp.name
for scenario, text in SCENARIO_IMAGES.items():
pathlib.Path(self.root, scenario).mkdir(parents=True)
pathlib.Path(self.root, scenario, "molecule.yml").write_text(text)
def select(self, pins, changed=(sel.WORKFLOW,)):
return sel.select(ALL, list(changed), self.root, pins)[0]
def test_a_2604_pin_selects_the_scenarios_naming_it(self):
self.assertEqual(
self.select({"MOLECULE_IMAGE_2604"}),
["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"],
)
def test_a_2404_pin_does_not_match_the_2604_name(self):
self.assertEqual(
self.select({"MOLECULE_IMAGE"}),
[
"extensions/molecule/image-smoke",
"roles/docker/molecule/default",
"roles/fail2ban/molecule/default",
],
)
def test_comments_only_select_nothing(self):
self.assertEqual(self.select(set()), [])
def test_the_controller_image_or_no_analysis_selects_everything(self):
self.assertEqual(self.select({"CONTROLLER_IMAGE"}), ALL)
self.assertEqual(self.select({"CONTROLLER_IMAGE", "MOLECULE_IMAGE"}), ALL)
self.assertEqual(self.select(None), ALL)
def test_pins_do_not_narrow_another_file(self):
self.assertEqual(self.select(set(), [sel.WORKFLOW, "meta/runtime.yml"]), ALL)
self.assertEqual(self.select(set(), ["meta/runtime.yml"]), ALL)
def test_a_shared_file_naming_the_pin_selects_everything(self):
for shared in (
".config/molecule/config.yml",
"extensions/molecule/shared/vars.yml",
"roles/docker/molecule/resources/prepare.yml",
):
path = pathlib.Path(self.root, shared)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("image: ${MOLECULE_IMAGE_2604}")
try:
self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL, shared)
finally:
path.unlink()
def test_a_shared_file_not_naming_the_pin_narrows(self):
path = pathlib.Path(self.root, ".config/molecule/config.yml")
path.parent.mkdir(parents=True)
path.write_text("image: ${MOLECULE_IMAGE}")
self.assertEqual(
self.select({"MOLECULE_IMAGE_2604"}),
["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"],
)
def test_an_unreadable_scenario_selects_everything(self):
shutil.rmtree(pathlib.Path(self.root, "roles/fail2ban/molecule/default"))
self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL)
def test_a_symlink_selects_everything(self):
# os.walk does not follow a directory symlink, so its target would go unread.
target = pathlib.Path(self.root, "elsewhere")
target.mkdir()
(target / "vars.yml").write_text("image: ${MOLECULE_IMAGE_2604}")
for link in (
"roles/fail2ban/molecule/default/shared",
"extensions/molecule/shared",
):
path = pathlib.Path(self.root, link)
path.symlink_to(target, target_is_directory=True)
try:
self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL, link)
finally:
path.unlink()
self.assertEqual(
self.select({"MOLECULE_IMAGE_2604"}),
["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"],
)
def test_pins_combine_with_a_role(self):
self.assertEqual(
self.select(
{"MOLECULE_IMAGE_2604"},
[sel.WORKFLOW, "roles/system_baseline/tasks/main.yml"],
),
[
"extensions/molecule/image-smoke-2604",
"roles/docker/molecule/default",
"roles/system_baseline/molecule/default",
],
)
if __name__ == "__main__":
unittest.main()