ci(images): assign image versions in CI and open the pin PR right after a push
Build / build (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s

The image.yml matrix holds a hand-edited base (MAJOR.MINOR) per image instead
of a version. On main, scripts/next_image_version.py compares a checksum of the
image's inputs with the inputs-sha256 label of the newest published <base>.N
and the job publishes <base>.N+1 when they differ, or builds nothing when they
match. A published tag is still never moved.

renovate.yml runs live on the successful completion of Images (workflow_run),
so the pin pull request opens minutes after a push instead of on the schedule.

Removed: bump_image_versions.py and its tests, check_image_versions.py bump,
Lint's bump step, Renovate's postUpgradeTasks, and the bot-diff allowance for
matrix version lines.

Closes #165

Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
Defame1297 committed 2026-11-23 21:15:16 +00:00
1 parent 8da65bd08e
commit b12c990b6a
23 files changed
+484 -1064

No files matched your search

-299
View File
@@ -1,299 +0,0 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
sys.path.insert(0, str(SCRIPTS))
import bump_image_versions as biv
IMAGE_YML = """\
# header comment
jobs:
image:
strategy:
matrix:
include:
- name: mol
version: {mol} # keep me
subpath: images/mol
dockerfile: Dockerfile
- name: ci
version: "{ci}"
subpath: ""
dockerfile: images/ci/Dockerfile
"""
CI_DOCKERFILE = "FROM x AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\n"
def run(cwd, *cmd):
return subprocess.run(
cmd,
cwd=cwd,
check=True,
capture_output=True,
text=True,
env={
**os.environ,
"GIT_CONFIG_GLOBAL": "/dev/null",
"GIT_CONFIG_SYSTEM": "/dev/null",
},
)
class PureTest(unittest.TestCase):
def test_next_patch(self):
self.assertEqual(biv.next_patch("0.2.9"), "0.2.10")
self.assertEqual(biv.next_patch("1.0.0-rc.1"), "1.0.1")
with self.assertRaises(ValueError):
biv.next_patch("latest")
def test_rewrite_changes_only_the_version_line(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
out = biv.rewrite(text, {"mol": "0.1.1", "ci": "0.2.1"})
self.assertEqual(out, IMAGE_YML.format(mol="0.1.1", ci="0.2.1"))
self.assertIn("version: 0.1.1 # keep me\n", out)
self.assertIn('version: "0.2.1"\n', out)
def test_rewrite_unknown_image_fails(self):
with self.assertRaises(biv.civ.CheckError):
biv.rewrite(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"), {"nope": "1.0.0"})
SHUFFLED_YML = """\
jobs:
image:
strategy:
matrix:
include:
- version: {mol}
subpath: images/mol
name: mol
dockerfile: Dockerfile
- subpath: ""
version: "{ci}"
dockerfile: images/ci/Dockerfile
name: ci
"""
class EntryAttributionTest(unittest.TestCase):
def test_version_before_name_is_attributed_to_its_own_entry(self):
text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0")
out = biv.rewrite(text, {"ci": "0.2.1"})
self.assertEqual(out, SHUFFLED_YML.format(mol="0.1.0", ci="0.2.1"))
out = biv.rewrite(text, {"mol": "0.1.1"})
self.assertEqual(out, SHUFFLED_YML.format(mol="0.1.1", ci="0.2.0"))
def test_entry_without_its_own_version_never_borrows_another(self):
text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0").replace(
' version: "0.2.0"\n', ""
)
with self.assertRaises(biv.civ.CheckError):
biv.rewrite(text, {"mol": "0.1.1"})
def test_flow_style_entry_is_refused(self):
text = (
SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0")
+ " - {name: x, version: 1.0.0}\n"
)
with self.assertRaises(biv.civ.CheckError):
biv.rewrite(text, {"ci": "0.2.1"})
class RepoTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.repo = pathlib.Path(self.tmp.name)
self.addCleanup(self.tmp.cleanup)
run(self.repo, "git", "init", "-q", "-b", "main")
run(self.repo, "git", "config", "user.email", "[email protected]")
run(self.repo, "git", "config", "user.name", "t")
self.write(
".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
)
self.write("images/ci/Dockerfile", CI_DOCKERFILE)
self.write("images/mol/Dockerfile", "FROM x\n")
self.write("requirements-dev.txt", "a==1\n")
self.write(".pre-commit-config.yaml", "repos: []\n")
self.commit("base")
run(self.repo, "git", "checkout", "-q", "-b", "feature")
def write(self, rel, text):
p = self.repo / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
def commit(self, msg):
run(self.repo, "git", "add", "-A")
run(self.repo, "git", "commit", "-q", "-m", msg)
def script(self, name, *args):
proc = subprocess.run(
[sys.executable, str(SCRIPTS / name), *args],
cwd=self.repo,
capture_output=True,
text=True,
check=False,
)
return proc.returncode, proc.stdout, proc.stderr
def bump(self, *args):
return self.script("bump_image_versions.py", *(args or ("main",)))
def versions(self):
return (self.repo / ".gitea/workflows/image.yml").read_text()
def test_nothing_changed(self):
code, out, _unused = self.bump()
self.assertEqual((code, out), (0, "image versions: nothing to bump\n"))
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.0"))
def test_bumps_exactly_the_changed_image_and_check_passes(self):
self.write("requirements-dev.txt", "a==2\n") # an input of ci only
code, out, err = self.bump()
self.assertEqual(code, 0, err)
self.assertEqual(out, "image versions: bumped ci 0.2.0 -> 0.2.1\n")
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.1"))
self.commit("deps and bump")
self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0)
def test_check_fails_without_the_bump(self):
self.write("images/mol/Dockerfile", "FROM y\n")
self.commit("input only")
self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 1)
self.assertEqual(self.bump()[0], 0)
self.commit("bump")
self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0)
def test_idempotent_and_committed_changes_count(self):
self.write("images/mol/Dockerfile", "FROM y\n")
self.commit("input")
first = self.bump()
self.assertEqual(first[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n")
second = self.bump()
self.assertEqual(second[1], "image versions: nothing to bump\n")
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.1", ci="0.2.0"))
def test_higher_version_already_present_is_kept(self):
self.write("images/mol/Dockerfile", "FROM y\n")
self.write(
".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.3.0", ci="0.2.0")
)
self.assertEqual(self.bump()[1], "image versions: nothing to bump\n")
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.3.0", ci="0.2.0"))
def test_both_images_and_untracked_input(self):
self.write("images/mol/new-file", "x\n") # untracked
self.write("requirements-dev.txt", "a==2\n")
out = self.bump()[1]
self.assertEqual(
out, "image versions: bumped ci 0.2.0 -> 0.2.1, mol 0.1.0 -> 0.1.1\n"
)
def test_bad_base_ref_is_a_clean_failure(self):
for ref in ("--output=x", "nope"):
code, _unused, err = self.bump(ref)
self.assertEqual(code, 1)
self.assertNotIn("Traceback", err)
self.assertEqual(len(err.strip().splitlines()), 1, err)
def test_shuffled_key_order_bumps_the_right_entry_end_to_end(self):
self.write(
".gitea/workflows/image.yml", SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0")
)
self.commit("shuffle")
self.write("requirements-dev.txt", "a==2\n") # an input of ci only
code, out, err = self.bump()
self.assertEqual(
(code, out), (0, "image versions: bumped ci 0.2.0 -> 0.2.1\n"), err
)
self.assertEqual(self.versions(), SHUFFLED_YML.format(mol="0.1.0", ci="0.2.1"))
def test_unparseable_entry_is_a_one_line_failure(self):
flow = (
SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0")
+ " - {name: x, version: 1.0.0}\n"
)
self.write(".gitea/workflows/image.yml", flow)
self.commit("flow")
self.write("requirements-dev.txt", "a==2\n")
code, _unused, err = self.bump()
self.assertEqual(code, 1)
self.assertEqual(len(err.strip().splitlines()), 1, err)
self.assertEqual(self.versions(), flow)
def test_crlf_line_endings_are_preserved(self):
crlf = (
IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
.replace("\n", "\r\n")
.encode("utf-8")
)
path = self.repo / ".gitea/workflows/image.yml"
path.write_bytes(crlf)
self.commit("crlf")
self.write("requirements-dev.txt", "a==2\n")
self.assertEqual(self.bump()[0], 0)
self.assertEqual(path.read_bytes(), crlf.replace(b'"0.2.0"', b'"0.2.1"'))
def test_ignored_cache_under_images_is_not_an_input(self):
self.write(".gitignore", "__pycache__/\n")
self.commit("ignore")
self.write("images/mol/__pycache__/x.pyc", "cache\n")
self.assertEqual(self.bump()[1], "image versions: nothing to bump\n")
self.write("images/mol/real-file", "x\n")
self.assertEqual(self.bump()[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n")
def test_shallow_clone_names_the_fix(self):
clone = self.repo.parent / (self.repo.name + "-shallow")
self.addCleanup(shutil.rmtree, clone, True)
self.write("images/mol/Dockerfile", "FROM y\n")
self.commit("two")
self.write("images/mol/Dockerfile", "FROM z\n")
self.commit("three")
run(
self.repo.parent,
"git",
"clone",
"-q",
"--depth",
"1",
"--branch",
"feature",
f"file://{self.repo}",
str(clone),
)
run(
clone,
"git",
"fetch",
"-q",
"--depth",
"1",
"origin",
"main:refs/remotes/origin/main",
)
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "bump_image_versions.py"), "origin/main"],
cwd=clone,
capture_output=True,
text=True,
check=False,
)
self.assertEqual(proc.returncode, 1)
self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr)
self.assertIn("git fetch --unshallow", proc.stderr)
def test_usage(self):
self.assertEqual(self.bump("a", "b")[0], 2)
if __name__ == "__main__":
unittest.main()
+20 -36
View File
@@ -23,7 +23,7 @@ FILES = {
"images/molecule-ubuntu2404/Dockerfile": f"FROM ubuntu:24.04@{D1}\n",
".gitea/workflows/image.yml": (
f"jobs:\n image:\n matrix:\n include:\n - name: ci\n"
f" version: 0.2.0\n job_image: ubuntu:24.04@{D1}\n"
f' base: "0.2"\n job_image: ubuntu:24.04@{D1}\n'
" container:\n image: ${{ matrix.job_image }}\n"
" steps:\n - run: echo ok\n"
),
@@ -121,11 +121,6 @@ class RuleTest(unittest.TestCase):
"RUN pip install uv==0.13.5 \\",
"RUN pip install uv==0.14.0 \\",
),
(
".gitea/workflows/image.yml",
" version: 0.2.0",
" version: 0.2.1",
),
(
".gitea/workflows/image.yml",
f" job_image: ubuntu:24.04@{D1}",
@@ -239,7 +234,7 @@ class RuleTest(unittest.TestCase):
line = f" job_image: ubuntu:24.04@{D1}"
for old, new in (
(line, ""),
(" version: 0.2.0", f" version: 0.2.0\n{line}"),
(' base: "0.2"', f' base: "0.2"\n{line}'),
(" steps:", f" steps:\n{line}"),
):
self.assertIsNotNone(self.problem(path, old, new), (old, new))
@@ -301,25 +296,19 @@ class RuleTest(unittest.TestCase):
for path, old, new in cases:
self.assertIsNotNone(self.problem(path, old, new), (path, old, new))
def test_version_lines_stay_in_place_and_rise(self):
v = " version: {}"
self.assertIsNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.1"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(9, v.format("0.2.1"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.1"))], [(5, v.format("0.2.0"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.0"))])
)
swapped = cbd.version_problem(
[(5, v.format("0.1.0")), (9, v.format("0.2.0"))],
[(5, v.format("0.2.0")), (9, v.format("0.1.0"))],
)
self.assertIsNotNone(swapped)
def test_matrix_version_and_base_lines_are_refused(self):
# CI assigns image versions and a human edits `base:`; the bot changes neither.
path = ".gitea/workflows/image.yml"
for old, new in (
(" version: 0.2.0", " version: 0.2.1"),
(' base: "0.2"', ' base: "0.3"'),
):
self.assertIsNotNone(self.problem(path, old, new), (old, new))
def test_changed_lines_stay_in_place(self):
line = f" job_image: ubuntu:24.04@{D1}"
self.assertIsNone(cbd.moved_problem([(7, line)], [(7, line)]))
self.assertIsNotNone(cbd.moved_problem([(7, line)], [(3, line)]))
def test_unequal_line_counts_are_refused(self):
self.assertIsNotNone(
@@ -471,23 +460,18 @@ class RepoTest(unittest.TestCase):
)
self.assertEqual(proc.returncode, 0, proc.stderr)
def test_lowering_a_matrix_version_fails_and_raising_it_passes(self):
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.1.9")
self.commit("lower")
def test_a_matrix_base_change_is_refused(self):
self.edit(".gitea/workflows/image.yml", 'base: "0.2"', 'base: "0.3"')
self.commit("base")
code, _unused, err = self.gate()
self.assertEqual(code, 1, err)
self.assertIn("version", err)
run(self.repo, "git", "checkout", "-q", "main")
run(self.repo, "git", "checkout", "-q", "-b", "renovate/ok")
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1")
self.commit("raise")
self.assertEqual(self.gate(head="renovate/ok")[0], 0)
self.assertIn(".gitea/workflows/image.yml", err)
def test_a_realistic_bot_pr_passes(self):
self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0")
self.edit(".pre-commit-config.yaml", "v1.0.0", "v1.1.0")
self.edit("images/ci/Dockerfile", "uv==0.13.5", "uv==0.14.0")
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1")
self.edit(".gitea/workflows/image.yml", D1, D2)
self.edit(".gitea/workflows/molecule.yml", D1, D2)
self.commit("bot")
code, out, err = self.gate()
+69 -214
View File
@@ -23,14 +23,14 @@ jobs:
matrix:
include:
- name: mol
version: {mol}
base: "{mol}"
subpath: images/mol
dockerfile: Dockerfile
job_image: """
+ JOB
+ """
- name: ci
version: {ci}
base: "{ci}"
subpath: ""
dockerfile: images/ci/Dockerfile
job_image: """
@@ -126,7 +126,7 @@ class PureTest(unittest.TestCase):
both = text + f"image: git.rkdr.net/mortis/zzz:0.1.0@{DIGEST} # trailing\n"
self.assertEqual(len(civ.check_pins(m, {"f": both})), 1)
def matrix(self, mol="0.1.0", ci="0.2.0"):
def matrix(self, mol="0.1", ci="0.2"):
return civ.matrix_of(IMAGE_YML.format(mol=mol, ci=ci))
def test_images_of_the_denied_namespace_are_refused(self):
@@ -153,15 +153,13 @@ class PureTest(unittest.TestCase):
"must not use or name",
)
def test_pins_ok_and_lagging(self):
pin = f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n"
self.assertEqual(civ.check_pins(self.matrix(), {"lint.yml": pin}), [])
def test_pins_of_a_matrix_image_pass_whatever_their_version(self):
for version in ("0.1.0", "0.2.7", "0.3.0"):
pin = f"image: git.rkdr.net/mortis/ci:{version}@{DIGEST}\n"
self.assertEqual(civ.check_pins(self.matrix(), {"lint.yml": pin}), [])
def test_pin_ahead_of_matrix_unknown_image_and_malformed(self):
def test_unknown_image_and_malformed_pins(self):
m = self.matrix()
self.assertEqual(
len(civ.check_pins(m, {"f": f"git.rkdr.net/mortis/ci:0.3.0@{DIGEST}"})), 1
)
self.assertEqual(
len(civ.check_pins(m, {"f": f"git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}"})), 1
)
@@ -260,8 +258,8 @@ class PureTest(unittest.TestCase):
for tail in (",", ")", "]", "}", "'", '"', ";"):
text = f"x: [git.rkdr.net/mortis/ci:0.1.0@{DIGEST}{tail if tail != ';' else ''} y]\n"
self.assertEqual(civ.check_pins(m, {"f": text}), [], tail)
ahead = f"x: (git.rkdr.net/mortis/ci:0.3.0@{DIGEST}), z\n"
self.assertEqual(len(civ.check_pins(m, {"f": ahead})), 1)
unknown = f"x: (git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}), z\n"
self.assertEqual(len(civ.check_pins(m, {"f": unknown})), 1)
self.assertEqual(
len(
civ.check_pins(
@@ -278,26 +276,32 @@ class PureTest(unittest.TestCase):
+ body
)
entry = " - name: a\n version: '0.1.0'\n dockerfile: D\n"
entry = (
" - name: a\n base: '0.1'\n dockerfile: D\n"
)
cases = {
"": "non-empty list",
" []\n": "non-empty block list",
" - 1\n": "not a mapping",
" - name: 1\n version: '0.1.0'\n dockerfile: D\n": "name must be a non-empty string",
" - name: 1\n base: '0.1'\n dockerfile: D\n": "name must be a non-empty string",
entry + " subpath: [x]\n": "cannot read the value",
entry.replace("'0.1.0'", "0.1") + "": "version must be a string",
entry.replace("'0.1'", "0.1"): "base must be a string",
entry + entry: "duplicate image name 'a'",
entry + " version: '0.2.0'\n": "duplicate key 'version'",
entry + " base: '0.2'\n": "duplicate key 'base'",
entry.replace("base: '0.1'", "base: *anchor"): "cannot read the value",
entry.replace(
"version: '0.1.0'", "version: *anchor"
): "cannot read the value",
entry.replace(
"version: '0.1.0'", 'version: "0\\x2e1.0"'
"base: '0.1'", 'base: "0\\x2e1"'
): "cannot read the quoted value",
entry.replace(
" - name: a\n", " - name: ''\n"
): "name must be a non-empty string",
" - name: a\n dockerfile: D\n": "lacks the key 'version'",
" - name: a\n dockerfile: D\n": "lacks the key 'base'",
entry.replace("'0.1'", "'0.2.3'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "'v1.0'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "'01.2'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "'1.02'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "''"): "base must be a string",
entry + " version: '0.1.0'\n": "key 'version' is not allowed",
}
for body, text in cases.items():
with self.assertRaises(civ.CheckError, msg=body) as ctx:
@@ -312,13 +316,13 @@ class PureTest(unittest.TestCase):
self.assertNotIn("\n", str(ctx.exception))
def test_matrix_reader_accepts_comments_quotes_and_key_order(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
text = text.replace(
" - name: ci\n version: 0.2.0\n",
' # the ci image\n - version: "0.2.0" # bumped by the bot\n'
' - name: ci\n base: "0.2"\n',
" # the ci image\n - base: '0.2' # minor of the next build\n"
" name: ci\n",
)
self.assertEqual(civ.matrix_of(text)["ci"]["version"], "0.2.0")
self.assertEqual(civ.matrix_of(text)["ci"]["base"], "0.2")
self.assertEqual(civ.matrix_of(text)["mol"]["subpath"], "images/mol")
def test_matrix_reader_agrees_with_pyyaml_on_the_real_file(self):
@@ -328,35 +332,26 @@ class PureTest(unittest.TestCase):
real = (
pathlib.Path(__file__).resolve().parents[2] / civ.MATRIX_FILE
).read_text()
want = {
e["name"]: {
"version": e["version"],
"subpath": e.get("subpath") or "",
"dockerfile": e["dockerfile"],
"job_image": e["job_image"],
}
for e in yaml.safe_load(real)["jobs"]["image"]["strategy"]["matrix"][
"include"
]
}
self.assertEqual(civ.matrix_of(real), want)
self.assertEqual(
civ.matrix_of(IMAGE_YML.format(mol="0.1.0", ci="0.2.0")),
{
def oracle(text):
return {
e["name"]: {
"version": e["version"],
"base": e["base"],
"subpath": e.get("subpath") or "",
"dockerfile": e["dockerfile"],
"job_image": e["job_image"],
}
for e in yaml.safe_load(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"))[
"jobs"
]["image"]["strategy"]["matrix"]["include"]
},
)
for e in yaml.safe_load(text)["jobs"]["image"]["strategy"]["matrix"][
"include"
]
}
self.assertEqual(civ.matrix_of(real), oracle(real))
fixture = IMAGE_YML.format(mol="0.1", ci="0.2")
self.assertEqual(civ.matrix_of(fixture), oracle(fixture))
def test_job_image_must_match_the_dockerfile_release(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
matrix = civ.matrix_of(text)
files = {
"images/mol/Dockerfile": f"FROM {JOB}\n",
@@ -394,7 +389,7 @@ class PureTest(unittest.TestCase):
)
def test_job_image_shape_and_missing_key(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
for bad in (
text.replace(f"job_image: {JOB}", "job_image: ubuntu:latest", 1),
text.replace(f" job_image: {JOB}\n", "", 1),
@@ -434,7 +429,7 @@ class PureTest(unittest.TestCase):
)
def test_container_line_must_sit_under_container(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
lookalike = text.replace(
" container:\n image: ${{ matrix.job_image }}\n",
" container:\n image: ubuntu:24.04\n steps:\n - run: |\n"
@@ -447,14 +442,14 @@ class PureTest(unittest.TestCase):
self.assertIn("the job container must be", errors[0])
def test_quoted_job_image_is_refused(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0").replace(
text = IMAGE_YML.format(mol="0.1", ci="0.2").replace(
f"job_image: {JOB}", f'job_image: "{JOB}"', 1
)
with self.assertRaises(civ.CheckError):
civ.matrix_of(text)
def test_image_metadata_labels_and_documentation(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
matrix = civ.matrix_of(text)
files = {
"images/mol/Dockerfile": labelled("mol"),
@@ -528,45 +523,10 @@ class PureTest(unittest.TestCase):
[],
)
def test_scripts_do_not_import_yaml(self):
# The bump step runs in the Renovate image, whose python3 has no PyYAML (dry run 2453).
for script in ("check_image_versions.py", "bump_image_versions.py"):
source = (
pathlib.Path(__file__).resolve().parents[2] / "scripts" / script
).read_text()
self.assertNotRegex(source, r"(?m)^\s*(import|from)\s+yaml\b", script)
def test_bump_logic(self):
def read(_path):
return CI_DOCKERFILE
base = self.matrix()
same = self.matrix()
for path in (
"images/mol/Dockerfile",
"images/ci/Dockerfile",
"requirements-dev.txt",
".pre-commit-config.yaml",
):
self.assertTrue(civ.check_bump(base, same, [path], read), path)
self.assertEqual(
civ.check_bump(
base,
same,
["README.md", "images/other/x", ".gitea/workflows/lint.yml"],
read,
),
[],
)
self.assertEqual(
civ.check_bump(
base, self.matrix(ci="0.2.1"), ["requirements-dev.txt"], read
),
[],
)
self.assertTrue(
civ.check_bump(base, self.matrix(ci="0.1.9"), [], read)
) # backwards
def test_script_does_not_import_yaml(self):
# Its importers run in job containers whose python3 has no PyYAML.
source = (SCRIPTS / "check_image_versions.py").read_text()
self.assertNotRegex(source, r"(?m)^\s*(import|from)\s+yaml\b")
class PythonPinTest(unittest.TestCase):
@@ -669,9 +629,7 @@ class GitTest(unittest.TestCase):
run(self.repo, "git", "init", "-q", "-b", "main")
run(self.repo, "git", "config", "user.email", "[email protected]")
run(self.repo, "git", "config", "user.name", "t")
self.write(
".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
)
self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1", ci="0.2"))
self.write(
"images/ci/Dockerfile",
labelled(
@@ -700,20 +658,10 @@ class GitTest(unittest.TestCase):
run(self.repo, "git", "add", "-A")
run(self.repo, "git", "commit", "-q", "-m", msg)
def bump(self):
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "check_image_versions.py"), "bump", "main"],
cwd=self.repo,
capture_output=True,
text=True,
check=False,
)
return proc.returncode, proc.stderr
def bump_args(self, *args, cwd=None):
def script(self, *args):
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "check_image_versions.py"), *args],
cwd=cwd or self.repo,
cwd=self.repo,
capture_output=True,
text=True,
check=False,
@@ -729,101 +677,48 @@ class GitTest(unittest.TestCase):
def test_pins_cli_refuses_the_denied_namespace_in_any_workflow(self):
self.write(".gitea/workflows/lint.yml", "name: Lint\n")
self.assertEqual(self.bump_args("pins")[0], 0)
self.assertEqual(self.script("pins")[0], 0)
self.write(
".gitea/workflows/other.yaml",
"container: git.rkdr.net/defame1297/runner:1\n",
)
code, err = self.bump_args("pins")
code, err = self.script("pins")
self.assertEqual(code, 1)
self.assertIn("other.yaml: mentions git.rkdr.net/defame1297/", err)
def test_moved_input_out_of_the_set_fails(self):
run(self.repo, "git", "mv", "images/mol/Dockerfile", "elsewhere.dockerfile")
self.commit("move out")
code, err = self.bump()
self.assertEqual(code, 1)
self.assertIn("image 'mol'", err)
def test_bump_mode_is_gone(self):
self.write(".gitea/workflows/lint.yml", "name: Lint\n")
self.assertEqual(self.script("bump", "main")[0], 2)
def test_renamed_pinned_input_fails(self):
run(self.repo, "git", "mv", "requirements-dev.txt", "req2.txt")
self.commit("rename")
code, err = self.bump()
self.assertEqual(code, 1)
self.assertIn("image 'ci'", err)
def test_option_like_base_ref_is_rejected(self):
for ref in ("--output=/tmp/x", "-h", "a b", "main\n"):
self.assert_clean_failure(
self.bump_args("bump", ref), "not a plain ref name"
)
def test_unknown_base_ref_is_one_line(self):
self.assert_clean_failure(
self.bump_args("bump", "nope"), "git merge-base failed"
)
def test_git_errors_are_decoded_text_not_a_bytes_repr(self):
code, err = self.bump_args("bump", "nope")
self.assertEqual(code, 1)
self.assertNotIn("b'", err)
self.assertNotIn('b"', err)
self.assertIn("fatal:", err)
def test_bad_version_in_matrix_is_one_line(self):
def test_bad_base_in_matrix_is_one_line(self):
self.write(
".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2.0")
".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2")
)
self.commit("bad version")
self.assert_clean_failure(self.bump(), "'latest' is not MAJOR.MINOR.PATCH")
self.assert_clean_failure(self.script("pins"), "base must be MAJOR.MINOR")
def test_missing_matrix_keys_is_one_line(self):
self.write(
".gitea/workflows/image.yml",
IMAGE_YML.replace(" version: {mol}\n", "").format(
mol="", ci="0.2.0"
IMAGE_YML.replace(' base: "{mol}"\n', "").format(
mol="", ci="0.2"
),
)
self.commit("no version")
self.assert_clean_failure(self.bump(), "lacks the key")
self.assert_clean_failure(self.script("pins"), "lacks the key")
self.write(".gitea/workflows/image.yml", "jobs: {}\n")
self.commit("no matrix")
self.assert_clean_failure(self.bump(), "no jobs.image.strategy.matrix.include")
self.assert_clean_failure(
self.script("pins"), "no jobs.image.strategy.matrix.include"
)
def test_pins_mode_missing_matrix_file_is_one_line(self):
run(self.repo, "git", "rm", "-q", ".gitea/workflows/image.yml")
self.assert_clean_failure(self.bump_args("pins"), "cannot read a file")
def test_non_ascii_input_path_counts(self):
self.write("images/mol/caf\u00e9", "x\n")
self.commit("non-ascii input")
code, err = self.bump()
self.assertEqual(code, 1, err)
self.assertIn("image 'mol'", err)
self.assertIn("caf\u00e9", err)
def test_non_utf8_path_in_the_diff_is_named(self):
path = os.fsencode(str(self.repo)) + b"/images/mol/caf\xe9"
try:
with open(path, "wb") as handle:
handle.write(b"x\n")
except OSError:
self.skipTest("the file system does not accept a non-UTF-8 name")
self.commit("non-utf8 input")
self.assert_clean_failure(self.bump(), "path is not valid UTF-8")
self.assert_clean_failure(self.script("pins"), "cannot read a file")
def test_empty_image_yml_says_so(self):
self.write(".gitea/workflows/image.yml", "")
self.commit("empty matrix")
self.assert_clean_failure(
self.bump(), "no jobs.image.strategy.matrix.include list"
self.script("pins"), "no jobs.image.strategy.matrix.include list"
)
def test_unsupported_dockerfile_source_fails_with_file_and_line(self):
self.write("images/ci/Dockerfile", "FROM x\nCOPY $SRC ./\n")
self.commit("variable source")
self.assert_clean_failure(self.bump(), "images/ci/Dockerfile:2:")
def test_pins_mode_requires_lint_yml_and_lists_checked_consumers(self):
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "check_image_versions.py"), "pins"],
@@ -849,46 +744,6 @@ class GitTest(unittest.TestCase):
self.assertIn("(checked: .gitea/workflows/lint.yml)", proc.stdout)
self.assertNotIn("build.yml", proc.stdout)
def test_unrelated_change_passes(self):
self.write("README.md", "x\n")
self.commit("docs")
self.assertEqual(self.bump()[0], 0)
def test_pinned_input_without_bump_fails(self):
self.write("requirements-dev.txt", "a==2\n")
self.commit("deps")
code, err = self.bump()
self.assertEqual(code, 1)
self.assertIn("image 'ci'", err)
self.assertNotIn("image 'mol'", err)
def test_pinned_input_with_bump_passes(self):
self.write("requirements-dev.txt", "a==2\n")
self.write(
".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.1")
)
self.commit("deps and bump")
self.assertEqual(self.bump()[0], 0)
def test_dockerfile_change_of_molecule_image_fails(self):
self.write("images/mol/Dockerfile", "FROM y\n")
self.commit("mol")
code, err = self.bump()
self.assertEqual(code, 1)
self.assertIn("image 'mol'", err)
def test_bump_survives_main_moving_on(self):
run(self.repo, "git", "checkout", "-q", "main")
self.write("README.md", "newer main\n")
self.commit("main moves")
run(self.repo, "git", "checkout", "-q", "feature")
self.write("images/mol/Dockerfile", "FROM y\n")
self.write(
".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.2.0", ci="0.2.0")
)
self.commit("mol with bump")
self.assertEqual(self.bump()[0], 0)
if __name__ == "__main__":
unittest.main()
+96
View File
@@ -0,0 +1,96 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import pathlib
import sys
import tempfile
import unittest
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
sys.path.insert(0, str(SCRIPTS))
import next_image_version as niv
def no_label(tag):
raise AssertionError(f"no label lookup expected, got {tag}")
class NextVersion(unittest.TestCase):
def test_first_version_of_a_base_is_patch_zero(self):
self.assertEqual(
niv.next_version("0.3", ["0.2.38", "latest"], "c1", no_label), "0.3.0"
)
def test_changed_inputs_raise_the_numerically_newest_patch(self):
seen = []
def label_of(tag):
seen.append(tag)
return "old"
tags = ["0.2.9", "0.2.10", "0.20.99", "1.2.11", "0.2.10-rc1", "latest"]
self.assertEqual(niv.next_version("0.2", tags, "new", label_of), "0.2.11")
self.assertEqual(seen, ["0.2.10"])
def test_unchanged_inputs_publish_nothing(self):
self.assertIsNone(
niv.next_version("0.1", ["0.1.4"], "same", lambda tag: "same")
)
def test_an_unlabelled_newest_version_counts_as_changed(self):
self.assertEqual(
niv.next_version("0.1", ["0.1.4"], "c", lambda tag: None), "0.1.5"
)
CI = {"subpath": "", "dockerfile": "images/ci/Dockerfile"}
MOL = {"subpath": "images/mol", "dockerfile": "Dockerfile"}
class InputChecksum(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = pathlib.Path(tmp.name)
self.write("images/ci/Dockerfile", "FROM ubuntu:26.04\nCOPY pins.txt ./\n")
self.write("images/mol/Dockerfile", "FROM ubuntu:24.04\n")
self.write("pins.txt", "a==1\n")
self.write("README.md", "readme\n")
def write(self, path, text):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
def checksum(self, entry):
return niv.input_checksum(self.root, entry)
def test_a_copied_file_is_an_input_and_an_unrelated_file_is_not(self):
before = self.checksum(CI)
self.write("README.md", "changed\n")
self.assertEqual(self.checksum(CI), before)
self.write("pins.txt", "a==2\n")
self.assertNotEqual(self.checksum(CI), before)
def test_the_build_context_of_a_subpath_image_is_its_input(self):
before = self.checksum(MOL)
self.write("pins.txt", "a==2\n")
self.assertEqual(self.checksum(MOL), before)
self.write("images/mol/files/new.conf", "x\n")
self.assertNotEqual(self.checksum(MOL), before)
def test_a_mode_change_is_an_input_change(self):
before = self.checksum(CI)
(self.root / "pins.txt").chmod(0o755)
self.assertNotEqual(self.checksum(CI), before)
def test_a_renamed_input_is_an_input_change(self):
self.write("images/mol/a.conf", "x\n")
before = self.checksum(MOL)
(self.root / "images/mol/a.conf").rename(self.root / "images/mol/b.conf")
self.assertNotEqual(self.checksum(MOL), before)
if __name__ == "__main__":
unittest.main()