Files
Kamino/tests/scripts/test_run_molecule_scenarios.py
T
Defame1297 258cbaf516
Build / build (pull_request) Successful in 31s
Lint / lint (pull_request) Successful in 3m27s
Molecule / molecule (pull_request) Successful in 31m13s
ci(molecule): say what a scenario time limit leaves running
A reader of the time limit needs to know its limits: on expiry only
molecule is signalled, so its ansible-playbook and workers run until the
run container ends, and the run-label cleanup step removes anything they
recreate. The default's reasoning holds at the default 2 lanes, and the
variable is for local runs and tests only.

The timeout test now runs on one lane, so beta running proves the stalled
lane was freed. The workflows rule gives the limit its reason and names
the two tests that hold it.

Refs #474

Assisted-by: Claude Code
2026-11-29 11:56:57 +00:00

549 lines
23 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for scripts/run_molecule_scenarios.sh with a stub molecule and a stub Docker SDK.
Run with: python3 -m unittest discover -s tests/scripts
"""
import importlib.util
import os
import pathlib
import re
import shutil
import signal
import subprocess
import sys
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"
RUN_ID = "${KAMINO_RUN_ID:-local}"
RUN_LABEL = "net.rkdr.mortis.molecule-run"
# The script expands platform names with molecule's own interpolator, as molecule does.
HAS_MOLECULE = importlib.util.find_spec("molecule") is not None
NEEDS_MOLECULE = "the run script imports molecule to expand platform names"
# Records what each run saw, then behaves as STUB_<scenario label> asks: fail, sleep, stall (past
# a short time limit), 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 ;;
stall) exec sleep 30 ;;
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"
"""
# The Docker SDK as the script uses it: each container a name filter matches is listed, and its
# removal is recorded or fails on request.
DOCKER_SDK_STUB = """import os, re
class Container:
def __init__(self, name):
self.name = name
self.id = "id-" + name
def remove(self, force=False):
if os.environ.get("STUB_RM_FAIL"):
raise RuntimeError("removal refused")
with open(os.environ["STUB_DOCKER_LOG"], "a") as log:
log.write(f"remove {self.name} force={force}\\n")
class Containers:
def list(self, all=False, filters=None):
name = re.fullmatch(r"\\^/(.+)\\$", filters["name"])[1]
with open(os.environ["STUB_DOCKER_LOG"], "a") as log:
log.write(f"list {name} all={all}\\n")
return [Container(name), Container(name + "-other")]
class Client:
containers = Containers()
def from_env():
return Client()
"""
def stub_python(where):
"""A venv whose python3 imports the Docker SDK stub; `python3 -I` ignores PYTHONPATH, not a venv."""
subprocess.run(
[sys.executable, "-m", "venv", "--without-pip", str(where)], check=True
)
site = subprocess.run(
[
str(where / "bin" / "python3"),
"-c",
"import sysconfig; print(sysconfig.get_path('purelib'))",
],
check=True,
capture_output=True,
text=True,
).stdout.strip()
site = pathlib.Path(site)
(site / "docker.py").write_text(DOCKER_SDK_STUB)
# PyYAML, and molecule when it is there, from the environment running the tests
outer = {pathlib.Path(yaml.__file__).parents[1]}
if HAS_MOLECULE:
outer.add(pathlib.Path(importlib.util.find_spec("molecule").origin).parents[1])
(site / "outer.pth").write_text("".join(f"{p}\n" for p in outer))
return where / "bin"
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"],
}
def container_names(run_id):
"""Every fixture platform's container name in the run run_id."""
return [f"{run_id}-{n}" for names in PLATFORMS.values() for n in names]
@unittest.skipUnless(shutil.which("bash"), "bash is required")
class RunMoleculeScenariosTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.venv_tmp = tempfile.mkdtemp(prefix="kamino-runmol-venv-")
cls.python_bin = stub_python(pathlib.Path(cls.venv_tmp) / "venv")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.venv_tmp, True)
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": f"{RUN_ID}-{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()
(bin_dir / "molecule").write_text(MOLECULE_STUB)
(bin_dir / "molecule").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}:{self.python_bin}:{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()}
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
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)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
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)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
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().splitlines()
for name in container_names("local"):
self.assertIn(f"list {name} all=True", docker)
self.assertIn(f"remove {name} force=True", docker)
# a filter match by another name is left alone
self.assertFalse(
[line for line in docker if line.endswith("-other force=True")]
)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
def test_the_containers_removed_are_the_run_s_own(self):
proc = self.run_script(list(PLATFORMS), KAMINO_RUN_ID="r7")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
removed = [
line.split()[1]
for line in self.docker_log.read_text().splitlines()
if line.startswith("remove ")
]
self.assertEqual(sorted(removed), sorted(container_names("r7")))
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
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)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
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)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
def test_the_longest_scenarios_start_first(self):
# an unlisted scenario counts as longest; the groups keep the selection order
seconds = listed_seconds()
roles = [d for d in seconds if d.startswith("roles/")]
shortest, longest = min(roles, key=seconds.get), max(roles, key=seconds.get)
for scenario in (shortest, longest):
d = self.root / scenario
d.mkdir(parents=True)
name = f"{RUN_ID}-{scenario.replace('/', '-')}"
platforms = [{"name": name, "image": "${MOLECULE_IMAGE}"}]
(d / "molecule.yml").write_text(yaml.safe_dump({"platforms": platforms}))
smoke = "extensions/molecule/image-smoke"
order = [smoke, shortest, "roles/alpha/molecule/default", longest]
listed = sorted((smoke, shortest, longest), key=seconds.get, reverse=True)
proc = self.run_script(order, MOLECULE_LANES="1")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
spans = self.events()
self.assertEqual(
sorted(spans, key=lambda label: spans[label][0]),
[label(d) for d in ["roles/alpha/molecule/default", *listed]],
)
groups = re.findall(
r"^::group::molecule test: (\S+) ", proc.stdout, re.MULTILINE
)
self.assertEqual(groups, [label(d) for d in order])
def test_the_duration_list_names_existing_scenarios(self):
# a renamed scenario would otherwise drop out of the list unnoticed
listed = listed_seconds()
self.assertTrue(listed)
for scenario in listed:
self.assertTrue((REPO / scenario / "molecule.yml").is_file(), scenario)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
def test_empty_lanes_are_accepted(self):
# the workflow passes an empty value outside a manual dispatch
proc = self.run_script(list(PLATFORMS), MOLECULE_LANES="")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
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(), "")
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
def test_a_scenario_past_its_time_limit_fails_alone(self):
# one lane, and alpha first (both unlisted, so the selection order holds): beta runs only
# if the stalled lane is freed
proc = self.run_script(
["roles/alpha/molecule/default", "roles/beta/molecule/default"],
MOLECULE_LANES="1", MOLECULE_SCENARIO_TIMEOUT="2", STUB_alpha_default="stall",
) # fmt: skip
self.assertEqual(proc.returncode, 1)
self.assertIn("::error::Failed: alpha/default\n", proc.stdout)
self.assertIn("Scenarios run: 2", proc.stdout)
body = proc.stdout.split("::group::molecule test: alpha/default")[1].split(
"::endgroup::"
)[0]
self.assertIn("output of alpha/default", body)
self.assertIn("timed out after 2 s", body)
self.assertIn("output of beta/default", proc.stdout)
self.assertIn(
"remove local-alpha-instance force=True", self.docker_log.read_text()
)
def test_the_default_time_limit_is_inside_the_job_timeout(self):
# a limit past the job's own would let a hang take the job and every log with it
timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["molecule"][
"timeout-minutes"
]
limit = re.findall(r"MOLECULE_SCENARIO_TIMEOUT:-(\d+)\}", SCRIPT.read_text())
self.assertEqual(len(limit), 1)
self.assertLess(int(limit[0]), timeout * 60)
def test_the_time_limit_must_be_a_positive_integer(self):
for limit in ("0", "-1", "ten", "04"):
proc = self.run_script(list(PLATFORMS), MOLECULE_SCENARIO_TIMEOUT=limit)
self.assertEqual(proc.returncode, 2, limit)
self.assertIn(
"MOLECULE_SCENARIO_TIMEOUT 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 listed_seconds():
"""{scenario directory: seconds} from the run script's duration list."""
pairs = re.findall(r"^ \[([^]]+)\]=(\d+)$", SCRIPT.read_text(), re.MULTILINE)
return {d: int(s) for d, s in pairs}
def label(scenario):
"""The run script's label of a scenario directory, as its log groups print it."""
if scenario.startswith("extensions/"):
return scenario.rsplit("/", 1)[1]
parts = scenario.split("/")
return f"{parts[1]}/{parts[3]}"
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, ProcessLookupError): # gone before or during the read
return False
return stat.rsplit(")", 1)[1].split()[0] != "Z"
def label_filters(step_name):
"""The label filters of a workflow step's docker commands, as `--filter label=<key>[=<value>]`."""
return re.findall(r"--filter ['\"]?label=([^'\"\s]+)", step_run(step_name))
def step_run(step_name):
"""The run: block of the Molecule workflow's step named step_name."""
workflow = yaml.safe_load(WORKFLOW.read_text())
steps = [s for job in workflow["jobs"].values() for s in job.get("steps", [])]
return next(s["run"] for s in steps if s.get("name") == step_name)
class ScenarioPlatformsTest(unittest.TestCase):
"""Scenarios run side by side and runs overlap, so each container is named and labelled by its run."""
def test_platforms_are_named_and_labelled_by_the_run(self):
files = sorted(REPO.glob("roles/*/molecule/*/molecule.yml"))
files += sorted(REPO.glob("extensions/molecule/*/molecule.yml"))
self.assertTrue(files)
seen = {}
for path in files:
where = path.relative_to(REPO)
data = yaml.safe_load(path.read_text())
for platform in data["platforms"]:
name = platform["name"]
self.assertTrue(name.startswith(f"{RUN_ID}-"), f"{where}: {name}")
self.assertEqual(
platform.get("labels", {}).get(RUN_LABEL),
RUN_ID,
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)
def test_the_workflow_finds_the_containers_by_the_run_label(self):
# the sweep of earlier runs filters by the key, the cleanup of this run by key and value
self.assertEqual(
set(label_filters("Remove the containers earlier runs left")), {RUN_LABEL}
)
self.assertEqual(
set(label_filters("Remove this run's containers")),
{f"{RUN_LABEL}=$KAMINO_RUN_ID"},
)
def test_the_sweep_spares_containers_younger_than_the_job_timeout(self):
# a shorter bound would remove the containers of a run still going
timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["molecule"][
"timeout-minutes"
]
run = step_run("Remove the containers earlier runs left")
self.assertEqual(
re.findall(r"date -d '(\d+) minutes ago'", run), [str(timeout)]
)
class LanesInputTest(unittest.TestCase):
"""A manual dispatch can set the lane count of the run script inside the run container."""
def test_the_dispatch_input_reaches_the_run_container(self):
workflow = yaml.safe_load(WORKFLOW.read_text())
# yaml reads the `on:` key as True
lanes = workflow[True]["workflow_dispatch"]["inputs"]["lanes"]
self.assertEqual((lanes["type"], lanes["default"]), ("string", ""))
steps = workflow["jobs"]["molecule"]["steps"]
step = next(s for s in steps if s.get("name") == "Run the scenarios")
self.assertEqual(step["env"]["MOLECULE_LANES"], "${{ inputs.lanes }}")
self.assertRegex(step["run"], r"docker run [^<]*-e MOLECULE_LANES\b")
class ScenarioSequenceTest(unittest.TestCase):
"""A role scenario previews the fresh host and the configured host with molecule's check step."""
def test_role_scenarios_run_check_before_and_after_converge(self):
# A check-only scenario has no converge to surround, so it is not held to this.
files = sorted(REPO.glob("roles/*/molecule/*/molecule.yml"))
self.assertTrue(files)
for path in files:
sequence = yaml.safe_load(path.read_text())["scenario"]["test_sequence"]
if "converge" not in sequence:
continue
at = sequence.index("converge")
self.assertEqual(
sequence[at - 1 : at + 3],
["check", "converge", "check", "idempotence"],
path.relative_to(REPO),
)
if __name__ == "__main__":
unittest.main()