9 Commits
Author SHA1 Message Date
Defame1297 ceeca66209 Merge pull request 'ci(molecule): cancel superseded runs, trim the test sequence, run nightly' (#117) from ci/molecule-cancel-and-trim into main
Build / build (push) Successful in 12s
Lint / lint (push) Successful in 21s
Molecule / molecule (push) Successful in 6m5s
Reviewed-on: #117
2026-11-14 11:56:00 +00:00
Defame1297andClaude Sonnet 5.5 676c950c08 Merge branch 'ci/molecule-changed-roles' into ci/molecule-cancel-and-trim
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 24s
Molecule / molecule (pull_request) Successful in 6m50s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:34:25 +00:00
Defame1297andClaude Sonnet 5.5 a94bee8fd3 fix(lint): satisfy ansible-test pylint in the molecule selector
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 24s
Molecule / molecule (pull_request) Successful in 7m0s
ansible-test sanity runs pylint over scripts/ and tests/scripts/ too and
rejects a mutable default argument (environ=os.environ) and `_` as a variable
name. main() now takes environ=None and reads os.environ itself, and the tests
name the values they ignore.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:34:13 +00:00
Defame1297 37420825a1 Merge branch 'main' into ci/molecule-cancel-and-trim
Build / build (pull_request) Failing after 11s
Lint / lint (pull_request) Successful in 20s
Molecule / molecule (pull_request) Canceled after 5m0s
2026-11-14 11:23:52 +00:00
Defame1297 fdab483109 Merge branch 'main' into ci/molecule-changed-roles
Build / build (pull_request) Failing after 12s
Lint / lint (pull_request) Successful in 21s
Molecule / molecule (pull_request) Successful in 7m19s
2026-11-14 11:23:46 +00:00
Defame1297andClaude Sonnet 5.5 25bca2ebff ci(molecule): run every scenario nightly
Build / build (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
A pull request runs only the scenarios of the roles it changes, so drift in the
others (a package mirror, the runner's molecule venv) would wait for the next
push to main. A nightly run of everything bounds that. It is scheduled after
Renovate's run, since the runner has a single slot.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:06:59 +00:00
Defame1297andClaude Sonnet 5.5 792b3414d3 ci(molecule): drop the leading destroy from every scenario's test sequence
The first destroy runs against a container that is not there and only waits out
the Docker driver's fixed 5 s poll, about 6 s per scenario and 42 s per full
run. The run step already removes what a killed run left, and molecule's state
file lives under the job's own ANSIBLE_HOME (Runtime(isolated=False)), which is
deleted with the checkout, so a cancelled run cannot make the next one skip
create or prepare. The rest of the sequence is molecule's default.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:06:18 +00:00
Defame1297andClaude Sonnet 5.5 db52adcb81 ci(molecule): cancel superseded pull request runs
A new commit on a pull request now cancels its running Molecule run, as for
Lint and Build; a run on main is never cancelled (its group is the commit SHA).

The old global concurrency group kept two runs off the runner's shared Docker
daemon, whose container names are fixed. That is now the runner's single slot
(gitea_runner_capacity: 1), as the workflow comment and CLAUDE.md say. A
cancelled run is killed before molecule can destroy its container, so the run
step first removes the containers of every scenario by their exact platform
names, whether or not this run selects that scenario.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:06:17 +00:00
Defame1297andClaude Sonnet 5.5 4d330d41c7 ci(molecule): run only the scenarios of the roles a pull request changes
Build / build (pull_request) Failing after 12s
Lint / lint (pull_request) Successful in 21s
Molecule / molecule (pull_request) Successful in 6m53s
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
12 changed files with 628 additions and 24 deletions

No files matched your search

+63 -21
View File
@@ -36,15 +36,25 @@ on: # yamllint disable-line rule:truthy
- 'meta/**'
- 'galaxy.yml'
- '.gitea/workflows/molecule.yml'
# Every scenario, nightly: a pull request runs only the scenarios of the roles it changes, so
# drift in the others (a package mirror, the runner's molecule venv) would otherwise wait for
# the next push to main. After Renovate's 03:17 run, which can take 30 minutes of the one slot.
schedule:
- cron: "43 4 * * *"
workflow_dispatch: {}
permissions:
contents: read
# Scenarios use fixed container names on the runner's shared Docker daemon.
# A pull request run is cancelled when a newer commit is pushed to the same pull request (the
# same rule as lint.yml and build.yml); a run on main is never cancelled, so its group is the
# commit SHA. Scenarios use fixed container names on the runner's shared Docker daemon, so two
# runs must not overlap. The group no longer guarantees that (it is per pull request now): the
# runner's single slot does (gitea_runner_capacity: 1 in the maintainer's environment
# repository). Raise that capacity and this needs a lock or a shared group again.
concurrency:
group: molecule
cancel-in-progress: false
group: molecule-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
molecule:
@@ -98,10 +108,25 @@ jobs:
git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; }
echo "Checked out $(git rev-parse HEAD)"
# molecule test destroys its instance on success and on failure.
# A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py
# explains the rules); a push to main and a manual dispatch run all of them.
# molecule test destroys its instance on success and on failure; a cancelled run is killed
# before it can, so the step first removes what such a run left, since the next run may not
# select the same scenarios.
- name: Run the scenarios
working-directory: ac/ansible_collections/mortis/kamino
env:
EVENT_NAME: ${{ github.event_name }}
# The workflow only runs for pull requests to main; lint.yml uses the same constant.
BASE_REF: origin/main
run: |
# The platform names of every scenario, anchored: <role>-instance and image-smoke[-2604].
# Assigned first so that a failing `docker ps` fails the step instead of looking empty.
stale="$(docker ps -aq --filter 'name=^/[a-z0-9-]+-instance$' --filter 'name=^/image-smoke(-2604)?$')"
if [ -n "$stale" ]; then
# shellcheck disable=SC2086 # container ids, one word each
docker rm -f $stale
fi
# molecule calls ansible-config and ansible-playbook by name
export PATH="$MOLECULE_VENV/bin:$PATH"
# The collection under test first, then what the roles use. molecule also
@@ -113,26 +138,43 @@ jobs:
export ANSIBLE_HOME="$ac_root/.ansible"
export ANSIBLE_COLLECTIONS_PATH="$ac_root:$MOLECULE_COLLECTIONS"
rm -rf "$HOME/.ansible/collections/ansible_collections/mortis"
# The selector comes from the base branch, so a pull request cannot edit the rules it is
# judged by (lint.yml does the same for check_bot_pr_diff.py); the first pull request that
# adds it has no base copy yet and uses its own.
sel=scripts/select_molecule_scenarios.py
if git cat-file -e "$BASE_REF:$sel" 2>/dev/null; then
sel_dir="$(mktemp -d)"
trap 'rm -rf "$sel_dir"' EXIT
git show "$BASE_REF:$sel" > "$sel_dir/select.py"
sel="$sel_dir/select.py"
else
echo "::notice::no base copy of $sel; running this checkout's copy"
fi
selected="$(python3 -I "$sel" "$BASE_REF")" || exit 1
failed=""
ran=0
for cfg in extensions/molecule/*/molecule.yml; do
[ -e "$cfg" ] || continue
name="$(basename "$(dirname "$cfg")")"
echo "::group::molecule test: $name"
molecule test -s "$name" || failed="$failed $name"
while IFS= read -r dir; do
[ -n "$dir" ] || continue
name="$(basename "$dir")"
case "$dir" in
extensions/*)
label="$name"
echo "::group::molecule test: $label"
molecule test -s "$name" </dev/null || failed="$failed $label"
;;
*)
role="${dir#roles/}"
role="${role%%/*}"
label="$role/$name"
echo "::group::molecule test: $label"
(cd "roles/$role" && molecule test -s "$name" </dev/null) || failed="$failed $label"
;;
esac
ran=$((ran + 1))
echo "::endgroup::"
done
for cfg in roles/*/molecule/*/molecule.yml; do
[ -e "$cfg" ] || continue
role="${cfg#roles/}"
role="${role%%/*}"
name="$(basename "$(dirname "$cfg")")"
echo "::group::molecule test: $role/$name"
(cd "roles/$role" && molecule test -s "$name") || failed="$failed $role/$name"
ran=$((ran + 1))
echo "::endgroup::"
done
done <<< "$selected"
echo "Scenarios run: $ran"
test "$ran" -gt 0 || { echo "::error::no molecule scenario found"; exit 1; }
# A scenario that swallowed the rest of the list must not pass quietly.
want="$(grep -c . <<< "$selected" || true)"
test "$ran" -eq "$want" || { echo "::error::ran $ran of $want selected scenarios"; exit 1; }
test -z "$failed" || { echo "::error::Failed:$failed"; exit 1; }
+11 -1
View File
@@ -59,7 +59,17 @@ Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily.
checksums baked into the image: a PR that changes `requirements-dev.txt` or
`.pre-commit-config.yaml` takes the slower path that installs the pinned tools.
- Molecule runs on every same-repo pull request, Renovate's included (a new image is tested by its own pin
pull request), with no path filter, so that it can be a required check. Fork pull requests are skipped.
pull request), with no workflow path filter, so that it can be a required check. Fork pull requests are skipped.
What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`, run from the base branch's copy
(a pull request cannot edit its own rules): only the scenarios of the roles it changes, none for a diff of
only its IGNORED paths, a failure for a changed role with no scenario, and every scenario for any other file,
for every push to `main`, for manual dispatch and for the nightly run (04:43 UTC, after Renovate's). A new file outside `roles/<role>/` runs everything until it
is added to IGNORED, which is right only when no scenario reads it. A new commit cancels the pull request's
running Molecule run, and the step first removes containers a cancelled run left; two runs never overlap
because the runner has a single slot, so raising its capacity needs a lock or a shared concurrency group.
- Every scenario sets `scenario.test_sequence` to molecule's default minus the leading `destroy` (the workflow
clears stale containers first, and the molecule state lives in the job's own `ANSIBLE_HOME`, so a killed run leaves
none behind); copy it into a new scenario.
- Molecule discovers `extensions/molecule/*/` and `roles/*/molecule/*/`. The `image-smoke`
and `image-smoke-2604` scenarios test the molecule images themselves (24.04 and 26.04); a role scenario that
must pass on both takes `image: ${MOLECULE_IMAGE}` or `${MOLECULE_IMAGE_2604}` per platform.
+3 -2
View File
@@ -53,8 +53,9 @@ outside contributions:
- Protect the `v*` tags so only maintainers can create them. A tag run uses the
workflow files of the tagged commit and may receive organisation secrets.
- Protect `main`: pull request required, with the `Lint` and `Build` checks. Molecule is not a required
check: its path filter would leave the check pending forever on a pull request that touches no role.
- Protect `main`: pull request required, with the `Lint` and `Build` checks. Molecule has no path filter
on pull requests (the job always starts and chooses its scenarios itself), so it can be made a required
check as well; that is the operator's decision.
- The image workflow (`.gitea/workflows/image.yml`) tries the Actions job token first;
Gitea 28 refuses it for an organisation's packages, so it pushes with the organisation secrets
`PACKAGE_PUSH_USER` and `PACKAGE_PUSH_TOKEN` (a bot user with write access to the
@@ -25,3 +25,20 @@ provisioner:
name: ansible
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -25,3 +25,20 @@ provisioner:
name: ansible
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -26,3 +26,20 @@ provisioner:
name: ansible
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -24,3 +24,20 @@ provisioner:
name: ansible
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -24,3 +24,20 @@ provisioner:
name: ansible
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -31,3 +31,20 @@ provisioner:
skip-tags: molecule-notest,notest,sysctl,secure_tmp,update,timezone
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -24,3 +24,20 @@ provisioner:
name: ansible
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
+184
View File
@@ -0,0 +1,184 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Choose the molecule scenarios a run needs.
python3 -I scripts/select_molecule_scenarios.py [<base-ref>]
Prints one scenario directory per line (`extensions/molecule/<name>` or
`roles/<role>/molecule/<name>`), extensions first, then roles, each sorted. The molecule
workflow runs `molecule test` in each.
Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAME is
`pull_request`. Then the diff of <base-ref>...HEAD decides:
* a file under roles/<role>/ selects that role's scenarios, and nothing else;
* a file on the IGNORED list (documentation, changelog, repository tooling that no
scenario reads) selects nothing;
* any other file selects every scenario.
The roles do not depend on one another, so a change inside one role cannot alter another
role's result. If one ever does (a role calling another, a shared plugin), the shared file
sits outside roles/<role>/ and so already selects everything; only an explicit role-to-role
dependency would need a rule here.
Every other case runs everything: a push, a manual dispatch, a scheduled run, no <base-ref>, a git
failure.
Narrowing is an optimisation, so any doubt resolves to the full set. The scenarios the
selection skips are not skipped on `main`: the push run after the merge runs them all.
A changed role that exists but has no scenario is an error, not an empty selection: a new role
without a molecule scenario, or a deleted or renamed scenario, must not pass Molecule with
nothing tested. A role whose directory is gone (the role was deleted) selects nothing.
The workflow runs this script from the base branch's copy, not the pull request's, so a pull
request cannot edit the rules it is judged by (the same reason lint.yml runs
check_bot_pr_diff.py from origin/main). A change to this file therefore selects everything
under the base copy's rules, because the file is not on the IGNORED list.
Exit codes: 0 ok (an empty selection from an all-ignored diff is ok), 1 no scenario exists at
all, or a changed role has none, 2 bad usage. Notices go to stderr as `::notice::` lines, with
control characters in paths escaped so a crafted file name cannot inject a log command.
"""
import fnmatch
import os
import subprocess
import sys
# Paths no scenario reads. A match is by fnmatch on the repository-relative path, where `*`
# also crosses `/`. Keep this list short and literal: anything not listed runs everything.
IGNORED = (
"docs/*",
"changelogs/*",
"LICENSES/*",
"README.md",
"CONTRIBUTING.md",
"SECURITY.md",
"GLOSSARY.md",
"CLAUDE.md",
"CHANGELOG.rst",
"COPYING",
"NOTICE",
"REUSE.toml",
"renovate.json",
".gitignore",
".yamllint",
".ansible-lint",
".pre-commit-config.yaml",
"requirements-dev.txt",
"apm.yml",
"apm.lock.yaml",
"tests/sanity/*",
"tests/scripts/*",
"images/*",
".gitea/actionlint.yaml",
".gitea/workflows/lint.yml",
".gitea/workflows/build.yml",
".gitea/workflows/image.yml",
".gitea/workflows/renovate.yml",
"scripts/bump_image_versions.py",
"scripts/check_bot_pr_diff.py",
"scripts/check_image_versions.py",
"scripts/check_tarball.py",
"scripts/dev-setup.sh",
"scripts/reuse_lint.py",
)
def printable(text):
"""`text` with control characters (a newline in a file name) escaped, for a log line."""
return "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii") for c in text)
def discover(root="."):
"""Every scenario directory, extensions first, each group sorted."""
found = []
ext = os.path.join(root, "extensions", "molecule")
if os.path.isdir(ext):
for name in sorted(os.listdir(ext)):
if name.isprintable() and os.path.isfile(os.path.join(ext, name, "molecule.yml")):
found.append(f"extensions/molecule/{name}")
roles = os.path.join(root, "roles")
if os.path.isdir(roles):
for role in sorted(os.listdir(roles)):
mol = os.path.join(roles, role, "molecule")
if not os.path.isdir(mol):
continue
for name in sorted(os.listdir(mol)):
if role.isprintable() and name.isprintable() and os.path.isfile(os.path.join(mol, name, "molecule.yml")):
found.append(f"roles/{role}/molecule/{name}")
return found
def is_ignored(path):
return any(fnmatch.fnmatchcase(path, pattern) for pattern in IGNORED)
def select(all_scenarios, changed, root="."):
"""The scenarios `changed` (repository-relative paths) needs, and a one-line reason.
Raises ValueError when a changed role still exists but has no scenario.
"""
roles = set()
for path in changed:
if is_ignored(path):
continue
parts = path.split("/")
if len(parts) > 2 and parts[0] == "roles":
roles.add(parts[1])
continue
return list(all_scenarios), f"{printable(path)} can affect every scenario"
chosen = [s for s in all_scenarios if s.startswith("roles/") and s.split("/")[1] in roles]
covered = {s.split("/")[1] for s in chosen}
bare = sorted(r for r in roles - covered if os.path.isdir(os.path.join(root, "roles", r)))
if bare:
raise ValueError("changed role without a molecule scenario: " + ", ".join(printable(r) for r in bare))
if roles:
reason = "only roles changed: " + ", ".join(printable(r) for r in sorted(roles))
else:
reason = "no change that a scenario reads"
return chosen, reason
def changed_paths(base_ref):
"""Paths changed in base_ref...HEAD; a rename counts as a delete plus an add."""
out = subprocess.run(
["git", "diff", "--name-only", "--no-renames", "-z", f"{base_ref}...HEAD", "--"],
check=True, capture_output=True,
).stdout
return [os.fsdecode(p) for p in out.split(b"\0") if p]
def main(argv, environ=None):
environ = os.environ if environ is None else environ
if len(argv) > 2:
print("usage: select_molecule_scenarios.py [<base-ref>]", file=sys.stderr)
return 2
base_ref = argv[1] if len(argv) == 2 else ""
scenarios = discover()
if not scenarios:
print("::error::no molecule scenario found", file=sys.stderr)
return 1
if environ.get("EVENT_NAME") != "pull_request" or not base_ref:
print(f"::notice::Running all {len(scenarios)} scenarios (not a pull request)", file=sys.stderr)
chosen = scenarios
else:
try:
changed = changed_paths(base_ref)
except (subprocess.CalledProcessError, OSError, UnicodeError) as exc:
print(f"::warning::cannot diff against {printable(base_ref)} ({printable(str(exc))}); running all scenarios",
file=sys.stderr)
chosen = scenarios
else:
try:
chosen, reason = select(scenarios, changed)
except ValueError as exc:
print(f"::error::{exc}", file=sys.stderr)
return 1
print(f"::notice::Running {len(chosen)} of {len(scenarios)} scenarios: {reason}", file=sys.stderr)
for scenario in chosen:
print(scenario)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -0,0 +1,248 @@
# 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, _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()