ci(molecule): run Molecule from the ci image instead of the runner's venv

Pin molecule and its Docker driver in requirements-dev.txt and bake them,
with the driver's collection, into the ci image. The Molecule job runs
docker run on the pinned ci image with the Docker socket and the checkout
mounted at the same path, as the runner user. A pull request whose pins
differ from the image installs its own pins first, so a core bump runs its
scenarios on the new core. gitea_runner no longer installs the molecule
venv and collections.

Closes #225

Assisted-by: Claude Code
This commit is contained in:
Defame1297 committed 2026-11-24 07:14:19 +00:00
1 parent d9be7b7dc8
commit 2e32016c43
25 files changed
+292 -275

No files matched your search

@@ -511,6 +511,12 @@ class PureTest(unittest.TestCase):
)
self.assertEqual(civ.dockerfile_labels('FROM c\nLABEL a="unbalanced\n'), {})
def test_the_molecule_collections_are_an_input_of_the_ci_image(self):
root = pathlib.Path(__file__).resolve().parents[2]
entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text())["ci"]
_, files = civ.inputs_of(entry, (root / entry["dockerfile"]).read_text())
self.assertIn("extensions/molecule/requirements.yml", files)
def test_real_dockerfiles_carry_the_metadata(self):
root = pathlib.Path(__file__).resolve().parents[2]
matrix = civ.matrix_of((root / civ.MATRIX_FILE).read_text())
+75 -15
View File
@@ -1,6 +1,6 @@
# 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.
"""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
"""
@@ -11,6 +11,7 @@ import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import unittest
@@ -42,15 +43,62 @@ 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
# 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 from the environment running the tests
(site / "outer.pth").write_text(str(pathlib.Path(yaml.__file__).parents[1]) + "\n")
return where / "bin"
PLATFORMS = {
"roles/alpha/molecule/default": ["alpha-instance"],
"roles/beta/molecule/default": ["beta-instance", "beta2-instance"],
@@ -61,6 +109,15 @@ PLATFORMS = {
@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)
@@ -73,15 +130,14 @@ class RunMoleculeScenariosTest(unittest.TestCase):
(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)
(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}:{os.environ['PATH']}",
"PATH": f"{bin_dir}:{self.python_bin}:{os.environ['PATH']}",
"HOME": str(self.tmp),
"STUB_ROOT": str(self.root),
"STUB_LOG": str(self.log),
@@ -160,10 +216,14 @@ class RunMoleculeScenariosTest(unittest.TestCase):
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()
docker = self.docker_log.read_text().splitlines()
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)
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")]
)
def test_molecule_gets_no_stdin(self):
proc = self.run_script(list(PLATFORMS), STUB_alpha_default="stdin")