The pins check now fails when any file under .gitea/workflows mentions git.rkdr.net/defame1297/, so the environment repo's production images can never appear in the Collection's CI. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
380 lines
18 KiB
Python
380 lines
18 KiB
Python
# 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 subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
|
|
sys.path.insert(0, str(SCRIPTS))
|
|
import check_image_versions as civ # noqa: E402
|
|
|
|
DIGEST = "sha256:" + "a" * 64
|
|
IMAGE_YML = """\
|
|
jobs:
|
|
image:
|
|
strategy:
|
|
matrix:
|
|
include:
|
|
- name: mol
|
|
version: {mol}
|
|
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 ./\nCOPY --from=b /a /b\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_copy_sources_skip_from_stage(self):
|
|
self.assertEqual(civ.copy_sources(CI_DOCKERFILE), ["requirements-dev.txt", ".pre-commit-config.yaml"])
|
|
|
|
def test_copy_sources_json_form_and_directories(self):
|
|
self.assertEqual(civ.copy_sources('COPY ["a.txt", "b/", "/dst/"]\n'), ["a.txt", "b/"])
|
|
self.assertEqual(civ.touched(["conf/x.cfg", "other"], [], ["conf/"]), ["conf/x.cfg"])
|
|
self.assertEqual(civ.touched(["a.txt", "b.txt", "c.md"], [], ["*.txt"]), ["a.txt", "b.txt"])
|
|
self.assertEqual(civ.touched(["anything"], [], ["."]), ["anything"])
|
|
|
|
def test_version_order(self):
|
|
self.assertGreater(civ.parse_version("0.10.0"), civ.parse_version("0.9.0"))
|
|
self.assertGreater(civ.parse_version("1.0.0"), civ.parse_version("1.0.0-rc.1"))
|
|
with self.assertRaises(ValueError):
|
|
civ.parse_version("1.0.0+build")
|
|
|
|
def test_prerelease_precedence_per_semver(self):
|
|
order = ["1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2",
|
|
"1.0.0-beta.11", "1.0.0-rc.1", "1.0.0"]
|
|
keys = [civ.parse_version(v) for v in order]
|
|
self.assertEqual(keys, sorted(keys))
|
|
self.assertEqual(len(set(keys)), len(keys))
|
|
self.assertLess(civ.parse_version("1.0.0-2"), civ.parse_version("1.0.0-10"))
|
|
self.assertLess(civ.parse_version("1.0.0-9"), civ.parse_version("1.0.0-a"))
|
|
with self.assertRaises(ValueError):
|
|
civ.parse_version("1.0.0-a..b")
|
|
|
|
def test_whole_line_comments_are_not_pins(self):
|
|
m = self.matrix()
|
|
text = f"# was git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}\n # see git.rkdr.net/mortis/ci:9.9.9\n"
|
|
self.assertEqual(civ.check_pins(m, {"f": text}), [])
|
|
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"):
|
|
return civ.matrix_of(IMAGE_YML.format(mol=mol, ci=ci))
|
|
|
|
def test_foreign_production_images_are_denied(self):
|
|
for text in ("image: git.rkdr.net/defame1297/gitea-ansible-runner:1@sha256:" + "a" * 64,
|
|
"# GIT.RKDR.NET:443/Defame1297/x", "image: git.rkdr.net/defame1297/y"):
|
|
self.assertEqual(len(civ.check_foreign_images({"w.yml": text})), 1, text)
|
|
for text in ("image: git.rkdr.net/mortis/ci:0.2.0", "https://git.rkdr.net/defame1297x",
|
|
"see Defame1297/ansible-homelab-mono"):
|
|
self.assertEqual(civ.check_foreign_images({"w.yml": text}), [], text)
|
|
|
|
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_pin_ahead_of_matrix_unknown_image_and_malformed(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)
|
|
self.assertEqual(len(civ.check_pins(m, {"f": "git.rkdr.net/mortis/ci:0.2.0"})), 1)
|
|
self.assertEqual(len(civ.check_pins(m, {"f": "git.rkdr.net/mortis/ci@sha256:abc"})), 1)
|
|
|
|
def test_pin_spellings_are_reported(self):
|
|
m = self.matrix()
|
|
spellings = [
|
|
f"Git.rkdr.net/mortis/ci:0.1.0@{DIGEST}",
|
|
f"git.rkdr.net/Mortis/ci:0.1.0@{DIGEST}",
|
|
f"git.rkdr.net:443/mortis/ci:0.1.0@{DIGEST}",
|
|
f"git.rkdr.net/mortis/ci/sub:0.1.0@{DIGEST}",
|
|
f"GIT.RKDR.NET/mortis/CI:0.1.0@{DIGEST}",
|
|
"git.rkdr.net/mortis/ci",
|
|
"git.rkdr.net/mortis/ci:0.1.0",
|
|
]
|
|
for spelling in spellings:
|
|
errors = civ.check_pins(m, {"f": f"image: {spelling}\n"})
|
|
self.assertEqual(len(errors), 1, f"{spelling}: {errors}")
|
|
self.assertIn("not a <name>:<version>@sha256", errors[0])
|
|
valid = f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n"
|
|
self.assertEqual(civ.check_pins(m, {"f": valid}), [])
|
|
|
|
def test_urls_and_ssh_remotes_are_not_pin_mentions(self):
|
|
m = self.matrix()
|
|
text = ("url: https://git.rkdr.net/mortis/kamino\nurl2: http://git.rkdr.net/mortis/kamino.git\n"
|
|
"ssh: [email protected]:mortis/kamino.git\n")
|
|
self.assertEqual(civ.check_pins(m, {"f": text}), [])
|
|
|
|
def test_copy_source_fails_closed(self):
|
|
cases = {
|
|
"COPY $FILE /dst/\n": "'$'",
|
|
'COPY "a b" /dst/\n': "'\"'",
|
|
"COPY 'a' /dst/\n": "\"'\"",
|
|
"COPY a#b /dst/\n": "'#'",
|
|
'COPY ["$X", "/dst/"]\n': "'$'",
|
|
"COPY [\"a\", unquoted]\n": "JSON form",
|
|
"RUN --mount=type=bind,source=src,target=/s make\n": "RUN --mount binds the build context",
|
|
"RUN --mount=source=src,target=/s make\n": "RUN --mount binds the build context",
|
|
"FROM x\nRUN --mount=type=bind,target=/s \\\n make\n": "Dockerfile:2:",
|
|
}
|
|
for text, expected in cases.items():
|
|
with self.assertRaises(civ.CheckError, msg=text) as ctx:
|
|
civ.copy_sources(text, "images/ci/Dockerfile")
|
|
message = str(ctx.exception)
|
|
self.assertIn(expected, message, text)
|
|
self.assertIn("images/ci/Dockerfile:", message)
|
|
self.assertNotIn("\n", message)
|
|
|
|
def test_copy_source_ok_cases_still_pass(self):
|
|
ok = ("RUN --mount=type=cache,target=/c make\nRUN --mount=type=bind,from=b,source=/x,target=/y make\n"
|
|
"# COPY $IGNORED /x\nCOPY --chown=1:1 a b/ /dst/\nCOPY https://example.org/x /dst/\n")
|
|
self.assertEqual(civ.copy_sources(ok), ["a", "b/"])
|
|
|
|
def test_continuation_with_trailing_blanks_is_joined(self):
|
|
text = "COPY a.txt \\ \n b.txt /dst/\n"
|
|
self.assertEqual(civ.copy_sources(text), ["a.txt", "b.txt"])
|
|
text = "COPY a.txt \\\n# a comment\n b.txt /dst/\n"
|
|
self.assertEqual(civ.copy_sources(text), ["a.txt", "b.txt"])
|
|
|
|
def test_empty_or_non_mapping_matrix_file(self):
|
|
for text in ("", "# only a comment\n", "- a\n- b\n", "just a string\n"):
|
|
with self.assertRaises(civ.CheckError, msg=repr(text)) as ctx:
|
|
civ.matrix_of(text)
|
|
self.assertIn("image.yml is empty or not a mapping", str(ctx.exception))
|
|
|
|
def test_semver_is_strict(self):
|
|
for bad in ("0.1.0\n", "01.0.0", "1.02.0", "1.0.00", "1.0.0-01", "1.0.0-rc.01", "1.0.0 ", "v1.0.0"):
|
|
with self.assertRaises(ValueError, msg=repr(bad)):
|
|
civ.parse_version(bad)
|
|
for good in ("0.0.0", "1.0.0-0", "1.0.0-0a", "1.0.0-rc.0", "10.20.30"):
|
|
civ.parse_version(good)
|
|
|
|
def test_pin_followed_by_punctuation_is_parsed(self):
|
|
m = self.matrix()
|
|
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)
|
|
self.assertEqual(len(civ.check_pins(m, {"f": "x: [git.rkdr.net/mortis/ci:0.1.0@sha256:abc, y]"})), 1)
|
|
|
|
def test_matrix_shape_errors(self):
|
|
def doc(include):
|
|
return "jobs:\n image:\n strategy:\n matrix:\n include: " + include + "\n"
|
|
|
|
entry = "{name: a, version: '0.1.0', dockerfile: D"
|
|
cases = {
|
|
"[]": "non-empty list",
|
|
"{}": "non-empty list",
|
|
"[1]": "not a mapping",
|
|
"[{name: 1, version: '0.1.0', dockerfile: D}]": "name must be a non-empty string",
|
|
"[" + entry + ", subpath: 5}]": "subpath must be a string",
|
|
"[" + entry + ", subpath: [x]}]": "subpath must be a string",
|
|
"[{name: a, version: 0.1, dockerfile: D}]": "version must be a string",
|
|
"[" + entry + "}, " + entry + "}]": "duplicate image name 'a'",
|
|
}
|
|
for include, text in cases.items():
|
|
with self.assertRaises(civ.CheckError, msg=include) as ctx:
|
|
civ.matrix_of(doc(include))
|
|
self.assertIn(text, str(ctx.exception))
|
|
self.assertNotIn("\n", str(ctx.exception))
|
|
self.assertEqual(civ.matrix_of(doc("[" + entry + ", subpath: }]"))["a"]["subpath"], "")
|
|
with self.assertRaises(civ.CheckError) as ctx:
|
|
civ.matrix_of("jobs: [unclosed\n")
|
|
self.assertNotIn("\n", str(ctx.exception))
|
|
|
|
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
|
|
|
|
|
|
class GitTest(unittest.TestCase):
|
|
"""Run the script as CI does, in a throwaway repository."""
|
|
|
|
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 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):
|
|
proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), *args],
|
|
cwd=cwd or self.repo, capture_output=True, text=True, check=False)
|
|
return proc.returncode, proc.stderr
|
|
|
|
def assert_clean_failure(self, result, text):
|
|
code, err = result
|
|
self.assertEqual(code, 1, err)
|
|
self.assertNotIn("Traceback", err)
|
|
self.assertIn(text, err)
|
|
self.assertEqual(len(err.strip().splitlines()), 1, err)
|
|
|
|
def test_pins_cli_denies_a_production_image_in_any_workflow(self):
|
|
self.write(".gitea/workflows/lint.yml", "name: Lint\n")
|
|
self.assertEqual(self.bump_args("pins")[0], 0)
|
|
self.write(".gitea/workflows/other.yaml", "container: git.rkdr.net/defame1297/runner:1\n")
|
|
code, err = self.bump_args("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_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_bad_version_in_matrix_is_one_line(self):
|
|
self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2.0"))
|
|
self.commit("bad version")
|
|
self.assert_clean_failure(self.bump(), "'latest' is not MAJOR.MINOR.PATCH")
|
|
|
|
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"))
|
|
self.commit("no version")
|
|
self.assert_clean_failure(self.bump(), "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")
|
|
|
|
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")
|
|
|
|
def test_empty_image_yml_says_so(self):
|
|
self.write(".gitea/workflows/image.yml", "")
|
|
self.commit("empty matrix")
|
|
self.assert_clean_failure(self.bump(), "image.yml is empty or not a mapping")
|
|
|
|
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"],
|
|
cwd=self.repo, capture_output=True, text=True, check=False)
|
|
self.assertEqual(proc.returncode, 1, proc.stdout)
|
|
self.assertIn("lint.yml is missing", proc.stderr)
|
|
self.write(".gitea/workflows/lint.yml", f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n")
|
|
proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "pins"],
|
|
cwd=self.repo, capture_output=True, text=True, check=False)
|
|
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
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()
|