Files
Kamino/tests/scripts/test_run_molecule_scenarios.py
T
Defame1297 1ab01b6e3a
Build / build (pull_request) Successful in 19s
Lint / lint (pull_request) Successful in 1m7s
Molecule / molecule (pull_request) Successful in 11m58s
ci(molecule): run the selected scenarios side by side in four lanes
A full run executes 15 scenarios one after another, about 1100 s in
total, with the slowest (traefik/default) at about 216 s. The scenarios
share nothing on the runner's Docker daemon but the daemon itself: their
container names are unique. So scripts/run_molecule_scenarios.sh now runs
MOLECULE_LANES (default 4, a positive integer) of them at once inside the
one job, with the slowest scenario as the floor; the saving will be
measured in CI.

Each scenario gets its own ANSIBLE_HOME under the job tree. With
Runtime(isolated=False), ansible-compat uses ANSIBLE_HOME as molecule's
cache dir: molecule's prerun installs the collection under test there with
`ansible-galaxy collection install --force` (which first deletes the
installed copy), and the scenario's ephemeral directory (inventory,
ansible.cfg, state) lives under it. A shared one would let a scenario
delete the copy another is running.

Each scenario's output goes to its own log, printed afterwards in the
selection order inside its own group with its wall time, plus a timing
summary. The failure list, the ran-N-of-M guard, </dev/null stdin, the
role-directory cwd and the per-scenario container removal are kept. A
TERM, INT or HUP to the script stops each lane's whole process tree,
including the process groups of ansible's detached workers (they call
setsid), terminates it, ignores further signals until done, and exits
128 plus the first signal. A kill of the step's process group reaches
the lanes and molecule but not ansible's detached workers. Either way a
cancelled job leaves no molecule behind to recreate a container after
the next run's cleanup. The logic moved from the workflow into a script
so a unit test with stub molecule and docker can hold it; the test also
fails a scenario whose platform name is not unique or not matched by the
stale-container filter, which is what makes running side by side safe.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 22:37:00 +00:00

305 lines
13 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for scripts/run_molecule_scenarios.sh with stub molecule and docker on PATH.
Run with: python3 -m unittest discover -s tests/scripts
"""
import os
import pathlib
import re
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
import yaml
REPO = pathlib.Path(__file__).resolve().parents[2]
SCRIPT = REPO / "scripts" / "run_molecule_scenarios.sh"
WORKFLOW = REPO / ".gitea" / "workflows" / "molecule.yml"
# Records what each run saw, then behaves as STUB_<scenario label> asks: fail, sleep, hang (and
# record its pids), detach (as an ansible worker does, into its own process group, whose orphaned
# child no parent link reaches; record both), or read stdin (which must be empty).
MOLECULE_STUB = """#!/usr/bin/env bash
label="$(basename "$PWD")/$3"
[ "$PWD" = "$STUB_ROOT" ] && label="$3"
key="STUB_$(printf %s "$label" | tr -c 'A-Za-z0-9' _)"
echo "$label start $(date +%s.%N) home=$ANSIBLE_HOME cwd=$PWD args=$*" >> "$STUB_LOG"
echo "output of $label"
case "${!key:-}" in
fail) echo "$label end $(date +%s.%N)" >> "$STUB_LOG"; exit 2 ;;
sleep) sleep 1 ;;
hang) sleep 60 & echo "$$ $!" >> "$STUB_PIDS"; wait ;;
detach)
setsid bash -c '(sleep 60 & echo $! >> "$STUB_PIDS"); echo $$ >> "$STUB_PIDS"; exec sleep 60' &
wait ;;
stdin) echo "stdin of $label: [$(cat)]" ;;
esac
echo "$label end $(date +%s.%N)" >> "$STUB_LOG"
"""
# `ps` lists a container id per name filter; `rm` records the ids or fails on request.
DOCKER_STUB = """#!/usr/bin/env bash
echo "docker $*" >> "$STUB_DOCKER_LOG"
case "$1" in
ps) for a in "$@"; do case "$a" in name=*) n="${a#name=^/}"; echo "id-${n%$}" ;; esac; done ;;
rm) [ -z "${STUB_RM_FAIL:-}" ] || exit 1 ;;
esac
"""
PLATFORMS = {
"roles/alpha/molecule/default": ["alpha-instance"],
"roles/beta/molecule/default": ["beta-instance", "beta2-instance"],
"roles/beta/molecule/check_mode": ["beta-check-instance"],
"extensions/molecule/image-smoke": ["image-smoke"],
}
@unittest.skipUnless(shutil.which("bash"), "bash is required")
class RunMoleculeScenariosTest(unittest.TestCase):
def setUp(self):
self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="kamino-runmol-")).resolve()
self.addCleanup(shutil.rmtree, self.tmp, True)
self.root = self.tmp / "kamino"
self.hung = []
for scenario, names in PLATFORMS.items():
d = self.root / scenario
d.mkdir(parents=True)
platforms = [{"name": n, "image": "${MOLECULE_IMAGE}"} for n in names]
(d / "molecule.yml").write_text(yaml.safe_dump({"platforms": platforms}))
bin_dir = self.tmp / "bin"
bin_dir.mkdir()
for name, body in (("molecule", MOLECULE_STUB), ("docker", DOCKER_STUB)):
(bin_dir / name).write_text(body)
(bin_dir / name).chmod(0o755)
self.log = self.tmp / "molecule.log"
self.docker_log = self.tmp / "docker.log"
self.log.touch()
self.docker_log.touch()
self.env = {
"PATH": f"{bin_dir}:{os.environ['PATH']}",
"HOME": str(self.tmp),
"STUB_ROOT": str(self.root),
"STUB_LOG": str(self.log),
"STUB_DOCKER_LOG": str(self.docker_log),
}
def run_script(self, scenarios, **env):
return subprocess.run(
["bash", str(SCRIPT), str(self.tmp / "work")],
cwd=self.root,
env={**self.env, **env},
input="".join(f"{s}\n" for s in scenarios),
capture_output=True,
text=True,
check=False,
)
def events(self):
"""{label: (start, end)} from the molecule stub's log."""
times = {}
for line in self.log.read_text().splitlines():
label, what, stamp = line.split()[:3]
times.setdefault(label, {})[what] = float(stamp)
return {k: (v["start"], v.get("end")) for k, v in times.items()}
def test_groups_follow_the_selection_order_with_times(self):
order = list(PLATFORMS)
proc = self.run_script(order, STUB_alpha_default="sleep")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
groups = re.findall(
r"^::group::molecule test: (\S+) \((\d+) s\)$", proc.stdout, re.MULTILINE
)
self.assertEqual(
[g[0] for g in groups],
["alpha/default", "beta/default", "beta/check_mode", "image-smoke"],
)
self.assertGreaterEqual(int(groups[0][1]), 1)
self.assertEqual(proc.stdout.count("::endgroup::"), 4)
# each log sits inside its own group
body = proc.stdout.split("::group::molecule test: beta/default")[1].split(
"::endgroup::"
)[0]
self.assertIn("output of beta/default", body)
self.assertNotIn("output of alpha/default", body)
self.assertIn("Scenarios run: 4", proc.stdout)
self.assertIn(" image-smoke: ", proc.stdout)
def test_runs_in_lanes_and_isolates_each_scenario(self):
order = list(PLATFORMS)
stubs = {
f"STUB_{k}": "sleep"
for k in ("alpha_default", "beta_default", "image_smoke")
}
proc = self.run_script(order, MOLECULE_LANES="2", **stubs)
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
spans = self.events()
self.assertEqual(len(spans), 4)
running_at = [
sum(s <= t < e for s, e in spans.values()) for t, _end in spans.values()
]
self.assertEqual(max(running_at), 2, spans)
starts = [
line for line in self.log.read_text().splitlines() if " start " in line
]
homes = {re.search(r"home=(\S+)", s).group(1) for s in starts}
self.assertEqual(len(homes), 4)
check = next(s for s in starts if s.startswith("beta/check_mode "))
self.assertIn(
f"cwd={self.root / 'roles' / 'beta'} args=test -s check_mode", check
)
smoke = next(s for s in starts if s.startswith("image-smoke "))
self.assertIn(f"cwd={self.root} args=test -s image-smoke", smoke)
def test_a_failure_is_reported_and_its_containers_still_go(self):
proc = self.run_script(list(PLATFORMS), STUB_beta_default="fail")
self.assertEqual(proc.returncode, 1)
self.assertIn("::error::Failed: beta/default\n", proc.stdout)
self.assertIn("Scenarios run: 4", proc.stdout)
docker = self.docker_log.read_text()
for name in (n for names in PLATFORMS.values() for n in names):
self.assertIn(f"--filter name=^/{name}$", docker)
self.assertIn("docker rm -f id-beta-instance id-beta2-instance", docker)
def test_molecule_gets_no_stdin(self):
proc = self.run_script(list(PLATFORMS), STUB_alpha_default="stdin")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
self.assertIn("stdin of alpha/default: []", proc.stdout)
self.assertIn("Scenarios run: 4", proc.stdout)
def test_a_failed_removal_fails_the_scenario(self):
proc = self.run_script(["roles/alpha/molecule/default"], STUB_RM_FAIL="1")
self.assertEqual(proc.returncode, 1)
self.assertIn(
"could not remove the containers of roles/alpha/molecule/default",
proc.stdout,
)
self.assertIn("::error::Failed: alpha/default\n", proc.stdout)
def test_a_scenario_without_a_result_fails_the_run(self):
# a lane that dies leaves no rc file: a file where the second scenario's work directory
# goes makes its lane fail before molecule starts
(self.tmp / "work").mkdir()
(self.tmp / "work" / "1").write_text("not a directory")
proc = self.run_script(
["roles/alpha/molecule/default", "roles/beta/molecule/default"]
)
self.assertEqual(proc.returncode, 1)
self.assertIn("::error::ran 1 of 2 selected scenarios", proc.stdout)
def test_lanes_must_be_a_positive_integer(self):
for lanes in ("0", "-1", "two", "04"):
proc = self.run_script(list(PLATFORMS), MOLECULE_LANES=lanes)
self.assertEqual(proc.returncode, 2, lanes)
self.assertIn("MOLECULE_LANES must be a positive integer", proc.stderr)
self.assertEqual(self.log.read_text(), "")
def start_hung_run(self, count=4, **stubs):
"""A run in its own process group whose molecule stubs hang, and the pids they record."""
pids = self.tmp / "pids"
pids.touch()
env = {**self.env, "STUB_PIDS": str(pids), "MOLECULE_LANES": "2"}
env.update(stubs or {"STUB_alpha_default": "hang", "STUB_beta_default": "hang"})
proc = subprocess.Popen(
["bash", str(SCRIPT), str(self.tmp / "work")],
cwd=self.root, env=env, stdin=subprocess.PIPE, text=True,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, start_new_session=True,
) # fmt: skip
self.addCleanup(lambda: proc.poll() is None and os.killpg(proc.pid, 9))
self.addCleanup(lambda: [os.kill(p, 9) for p in self.hung if alive(p)])
proc.stdin.write("".join(f"{s}\n" for s in PLATFORMS))
proc.stdin.close()
deadline = time.monotonic() + 10
while len(pids.read_text().split()) < count and time.monotonic() < deadline:
time.sleep(0.05)
self.hung = [int(p) for p in pids.read_text().split()]
self.assertEqual(len(self.hung), count)
return proc
def assert_all_gone(self, pids):
deadline = time.monotonic() + 5
while any(map(alive, pids)) and time.monotonic() < deadline:
time.sleep(0.05)
self.assertEqual([p for p in pids if alive(p)], [])
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
def test_a_terminated_run_kills_its_lanes(self):
proc = self.start_hung_run()
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=10), 143)
self.assert_all_gone(self.hung)
self.assertEqual(proc.stderr.read(), "")
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
@unittest.skipUnless(shutil.which("setsid"), "needs setsid")
def test_a_terminated_run_kills_detached_process_groups(self):
proc = self.start_hung_run(count=2, STUB_alpha_default="detach")
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=10), 143)
self.assert_all_gone(self.hung)
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
def test_a_killed_process_group_takes_its_lanes(self):
# a runner may cancel a step by killing its process group, which the script cannot trap
proc = self.start_hung_run()
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=10)
self.assert_all_gone(self.hung)
def test_an_empty_selection_runs_nothing(self):
proc = self.run_script(["", ""])
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
self.assertIn("Scenarios run: 0", proc.stdout)
self.assertEqual(self.log.read_text(), "")
def alive(pid):
"""Whether pid is a running process, not gone or a zombie."""
try:
stat = pathlib.Path(f"/proc/{pid}/stat").read_text()
except FileNotFoundError:
return False
return stat.rsplit(")", 1)[1].split()[0] != "Z"
def stale_filters():
"""The name filters of the workflow's stale-container cleanup, as docker matches /<name>."""
workflow = yaml.safe_load(WORKFLOW.read_text())
steps = [s for job in workflow["jobs"].values() for s in job.get("steps", [])]
run = next(s["run"] for s in steps if s.get("name") == "Run the scenarios")
stale = next(line for line in run.splitlines() if line.strip().startswith("stale="))
return re.findall(r"--filter 'name=([^']+)'", stale)
class ScenarioPlatformNamesTest(unittest.TestCase):
"""The run script removes containers by literal platform name, and scenarios run side by side."""
def test_platform_names_are_literal_unique_and_cleared_before_a_run(self):
files = sorted(REPO.glob("roles/*/molecule/*/molecule.yml"))
files += sorted(REPO.glob("extensions/molecule/*/molecule.yml"))
self.assertTrue(files)
seen = {}
stale = stale_filters()
self.assertTrue(stale)
for path in files:
data = yaml.safe_load(path.read_text())
for platform in data["platforms"]:
name = platform["name"]
where = path.relative_to(REPO)
self.assertTrue(
any(re.search(f, f"/{name}") for f in stale), f"{where}: {name}"
)
self.assertNotIn(
name, seen, f"{where} and {seen.get(name)} share {name}"
)
seen[name] = where
self.assertNotIn("destroy", data["scenario"]["test_sequence"], path)
if __name__ == "__main__":
unittest.main()