Files
Kamino/tests/scripts/test_check_image_versions.py
T
Defame1297andClaude Sonnet 5.5 6c85d61827
Molecule / molecule (pull_request) Skipped
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 13s
fix(image): no single quote in a label (kaniko rejects it) and a check for it
Run 2556: the ci image failed at its LABEL step (unexpected end of statement while looking for
matching single-quote) on the apostrophe in 'the distribution's python3'. Docker accepts it,
kaniko's own LABEL parser does not, and the molecule images built only because their labels
have none. The label text is reworded and check_image_versions.py pins now fails on a single
quote in any label. ci 0.2.6 was never pushed; the gate wants a higher version than main's,
so the fix is 0.2.7.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-10-26 19:44:12 +00:00

540 lines
28 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
JOB = f"ubuntu:24.04@{DIGEST}"
IMAGE_YML = """\
jobs:
image:
strategy:
matrix:
include:
- name: mol
version: {mol}
subpath: images/mol
dockerfile: Dockerfile
job_image: """ + JOB + """
- name: ci
version: {ci}
subpath: ""
dockerfile: images/ci/Dockerfile
job_image: """ + JOB + """
container:
image: ${{{{ matrix.job_image }}}}
"""
CI_DOCKERFILE = f"FROM {JOB} AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\nCOPY --from=b /a /b\n"
def labelled(name, body=""):
"""A Dockerfile text with the labels check_image_metadata requires."""
values = {key: "x" for key in civ.REQUIRED_LABELS}
values["org.opencontainers.image.title"] = name
values["org.opencontainers.image.source"] = "https://example.org"
values["org.opencontainers.image.documentation"] = f"https://example.org/src/branch/main/docs/images/{name}.md"
values["org.opencontainers.image.base.name"] = "ubuntu:24.04"
return (f"FROM {JOB}\nLABEL " + " \\\n ".join(f'{k}="{v}"' for k, v in values.items()) + "\n" + body)
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("no jobs.image.strategy.matrix.include list", 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(body):
return "jobs:\n image:\n strategy:\n matrix:\n include:\n" + body
entry = " - name: a\n version: '0.1.0'\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",
entry + " subpath: [x]\n": "cannot read the value",
entry.replace("'0.1.0'", "0.1") + "": "version must be a string",
entry + entry: "duplicate image name 'a'",
entry + " version: '0.2.0'\n": "duplicate key 'version'",
entry.replace("version: '0.1.0'", "version: *anchor"): "cannot read the value",
entry.replace("version: '0.1.0'", "version: \"0\\x2e1.0\""): "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'",
}
for body, text in cases.items():
with self.assertRaises(civ.CheckError, msg=body) as ctx:
civ.matrix_of(doc(body))
self.assertIn(text, str(ctx.exception), body)
self.assertNotIn("\n", str(ctx.exception))
self.assertEqual(civ.matrix_of(doc(entry + " subpath:\n"))["a"]["subpath"], "")
with self.assertRaises(civ.CheckError) as ctx:
civ.matrix_of("jobs: [unclosed\n")
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 = 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")
self.assertEqual(civ.matrix_of(text)["ci"]["version"], "0.2.0")
self.assertEqual(civ.matrix_of(text)["mol"]["subpath"], "images/mol")
def test_matrix_reader_agrees_with_pyyaml_on_the_real_file(self):
# The reader replaces PyYAML in the Renovate image (which has none); here PyYAML is the oracle.
import yaml
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")),
{e["name"]: {"version": e["version"], "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"]})
def test_job_image_must_match_the_dockerfile_release(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
matrix = civ.matrix_of(text)
files = {"images/mol/Dockerfile": f"FROM {JOB}\n",
"images/ci/Dockerfile": f"FROM {JOB} AS os\nFROM os AS build\nFROM os AS final\n"}
def read(path):
return files[path]
self.assertEqual(civ.check_job_images(matrix, read, text), [])
files["images/ci/Dockerfile"] = f"FROM ubuntu:26.04@{DIGEST} AS os\nFROM os AS final\n"
errors = civ.check_job_images(matrix, read, text)
self.assertEqual(len(errors), 1)
self.assertIn("builds on ubuntu:26.04 but its job_image is ubuntu:24.04", errors[0])
files["images/ci/Dockerfile"] = "FROM debian:12\n"
self.assertIn("FROM debian:12 is not an Ubuntu base", civ.check_job_images(matrix, read, text)[0])
files["images/ci/Dockerfile"] = f"FROM {JOB} AS os\n"
self.assertEqual(civ.check_job_images(matrix, read, text.replace("matrix.job_image", "matrix.other")),
[".gitea/workflows/image.yml: the job container must be "
"`image: ${{ matrix.job_image }}`"])
def test_job_image_shape_and_missing_key(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
for bad in (text.replace(f"job_image: {JOB}", "job_image: ubuntu:latest", 1),
text.replace(f" job_image: {JOB}\n", "", 1)):
errors = civ.check_job_images(civ.matrix_of(bad), lambda path: f"FROM {JOB}\n", bad)
self.assertEqual(len(errors), 1, errors)
self.assertIn("job_image in .gitea/workflows/image.yml must be ubuntu:<release>@sha256:<digest>", errors[0])
def test_dockerfile_releases_fail_closed(self):
digest = DIGEST
cases = {
f"FROM --platform=linux/amd64 ubuntu:26.04@{digest} AS a\nFROM a AS b\n": (["26.04"], 0),
f"FROM docker.io/library/ubuntu:24.04@{digest}\n": (["24.04"], 0),
"FROM ubuntu:24.04 AS ubuntu\nFROM ubuntu AS x\n": (["24.04"], 0),
"FROM golang:1.22 AS b\nFROM ubuntu:24.04\n": (["24.04"], 1),
"ARG B=ubuntu:26.04\nFROM ubuntu:24.04 AS a\nFROM ${B} AS b\n": (["24.04"], 1),
"FROM ubuntu:${REL}\n": ([], 1),
"FROM ubuntu:24.04\nRUN <<EOF\necho hi\nEOF\n": (["24.04"], 0),
}
for text, (want_releases, want_problems) in cases.items():
releases, problems = civ.dockerfile_releases(text)
self.assertEqual((releases, len(problems)), (want_releases, want_problems), (text, problems))
def test_container_line_must_sit_under_container(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
lookalike = text.replace(" container:\n image: ${{ matrix.job_image }}\n",
" container:\n image: ubuntu:24.04\n steps:\n - run: |\n"
" image: ${{ matrix.job_image }}\n")
errors = civ.check_job_images(civ.matrix_of(lookalike), lambda path: f"FROM {JOB}\n", lookalike)
self.assertEqual(len(errors), 1, errors)
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(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")
matrix = civ.matrix_of(text)
files = {"images/mol/Dockerfile": labelled("mol"), "images/ci/Dockerfile": labelled("ci")}
sizes = {"docs/images/mol.md": 5, "docs/images/ci.md": 5}
def check():
return civ.check_image_metadata(matrix, lambda path: files[path], sizes.get)
self.assertEqual(check(), [])
files["images/ci/Dockerfile"] = labelled("ci").replace('net.rkdr.mortis.usage="x"', 'net.rkdr.mortis.usage=""')
self.assertIn("lacks the label(s) net.rkdr.mortis.usage", check()[0])
files["images/ci/Dockerfile"] = labelled("ci").replace("docs/images/ci.md", "docs/images/other.md")
self.assertIn("documentation label must be", check()[0])
files["images/ci/Dockerfile"] = labelled("ci").replace("https://example.org/src", "https://evil.example/src")
self.assertIn("documentation label must be", check()[0])
files["images/ci/Dockerfile"] = labelled("renamed")
self.assertTrue(any("expected the image name" in e for e in check()))
files["images/ci/Dockerfile"] = labelled("ci").replace('net.rkdr.mortis.usage="x"', 'net.rkdr.mortis.usage="the distribution\'s tool"')
self.assertIn("contain a single quote", check()[0])
files["images/ci/Dockerfile"] = labelled("ci").replace('base.name="ubuntu:24.04"', 'base.name="ubuntu:22.04"')
self.assertIn("base.name label 'ubuntu:22.04' differs", check()[0])
files["images/ci/Dockerfile"] = labelled("ci")
sizes["docs/images/ci.md"] = 0
self.assertIn("docs/images/ci.md is missing or empty", check()[0])
del sizes["docs/images/ci.md"]
self.assertIn("docs/images/ci.md is missing or empty", check()[0])
del files["images/ci/Dockerfile"]
sizes["docs/images/ci.md"] = 5
with self.assertRaises(KeyError):
check()
def test_dockerfile_labels_parse_like_a_shell(self):
text = ('FROM a AS b\nLABEL builder=1\nFROM c\n'
'LABEL one="x y=z w" two=\'q r\' \\\n three=plain\n'
'LABEL four="PRE_COMMIT_HOME=/opt/pre-commit; done" legacy value\n')
self.assertEqual(civ.dockerfile_labels(text),
{"one": "x y=z w", "two": "q r", "three": "plain", "four": "PRE_COMMIT_HOME=/opt/pre-commit; done"})
self.assertEqual(civ.dockerfile_labels('FROM c\nLABEL a="unbalanced\n'), {})
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())
self.assertEqual(civ.check_image_metadata(matrix, lambda p: (root / p).read_text(),
lambda p: (root / p).stat().st_size if (root / p).is_file() else None), [])
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
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", labelled("ci", CI_DOCKERFILE.split("\n", 1)[1]))
self.write("images/mol/Dockerfile", labelled("mol"))
self.write("docs/images/ci.md", "ci\n")
self.write("docs/images/mol.md", "mol\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_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):
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(), "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"],
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()