# 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_ 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" """ # 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) 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 label_filters(step_name): """The label filters of a workflow step's docker commands, as `--filter label=[=]`.""" 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") == step_name) return re.findall(r"--filter ['\"]?label=([^'\"\s]+)", run) 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( label_filters("Remove the containers earlier runs left"), [RUN_LABEL] ) self.assertEqual( label_filters("Remove this run's containers"), [f"{RUN_LABEL}=$KAMINO_RUN_ID"], ) if __name__ == "__main__": unittest.main()