style(scripts): format the scripts and their tests with ruff
Output of `ruff format` and nothing else, in its own commit so the diff is reviewable (#112). The ruff-check hook is skipped for this commit only: its findings are fixed in the next one. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
This commit is contained in:
1 parent
557f573df2
commit
db1c1e176f
12 files changed
+1520
-427
No files matched your search
@@ -1,6 +1,7 @@
|
||||
# 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
|
||||
@@ -14,7 +15,8 @@ import check_image_versions as civ # noqa: E402
|
||||
|
||||
DIGEST = "sha256:" + "a" * 64
|
||||
JOB = f"ubuntu:24.04@{DIGEST}"
|
||||
IMAGE_YML = """\
|
||||
IMAGE_YML = (
|
||||
"""\
|
||||
jobs:
|
||||
image:
|
||||
strategy:
|
||||
@@ -24,15 +26,20 @@ jobs:
|
||||
version: {mol}
|
||||
subpath: images/mol
|
||||
dockerfile: Dockerfile
|
||||
job_image: """ + JOB + """
|
||||
job_image: """
|
||||
+ JOB
|
||||
+ """
|
||||
- name: ci
|
||||
version: {ci}
|
||||
subpath: ""
|
||||
dockerfile: images/ci/Dockerfile
|
||||
job_image: """ + JOB + """
|
||||
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"
|
||||
|
||||
|
||||
@@ -41,24 +48,50 @@ def labelled(name, body=""):
|
||||
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.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)
|
||||
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"})
|
||||
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"])
|
||||
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.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):
|
||||
@@ -68,8 +101,16 @@ class PureTest(unittest.TestCase):
|
||||
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"]
|
||||
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))
|
||||
@@ -89,11 +130,17 @@ class PureTest(unittest.TestCase):
|
||||
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"):
|
||||
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"):
|
||||
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):
|
||||
@@ -102,10 +149,18 @@ class PureTest(unittest.TestCase):
|
||||
|
||||
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)
|
||||
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()
|
||||
@@ -127,18 +182,20 @@ class PureTest(unittest.TestCase):
|
||||
|
||||
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: git@git.rkdr.net:mortis/kamino.git\n")
|
||||
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' /dst/\n": '"\'"',
|
||||
"COPY a#b /dst/\n": "'#'",
|
||||
'COPY ["$X", "/dst/"]\n': "'$'",
|
||||
"COPY [\"a\", unquoted]\n": "JSON form",
|
||||
'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:",
|
||||
@@ -152,8 +209,10 @@ class PureTest(unittest.TestCase):
|
||||
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")
|
||||
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):
|
||||
@@ -166,10 +225,21 @@ class PureTest(unittest.TestCase):
|
||||
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))
|
||||
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"):
|
||||
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"):
|
||||
@@ -182,11 +252,21 @@ class PureTest(unittest.TestCase):
|
||||
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)
|
||||
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
|
||||
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 = {
|
||||
@@ -198,9 +278,15 @@ class PureTest(unittest.TestCase):
|
||||
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",
|
||||
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():
|
||||
@@ -208,112 +294,188 @@ class PureTest(unittest.TestCase):
|
||||
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"], "")
|
||||
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")
|
||||
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"]}
|
||||
|
||||
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"]})
|
||||
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"}
|
||||
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"
|
||||
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])
|
||||
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])
|
||||
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 }}`"])
|
||||
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)
|
||||
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])
|
||||
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 --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),
|
||||
"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))
|
||||
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)
|
||||
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)
|
||||
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")}
|
||||
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=""')
|
||||
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")
|
||||
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")
|
||||
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"')
|
||||
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"')
|
||||
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
|
||||
@@ -326,23 +488,40 @@ class PureTest(unittest.TestCase):
|
||||
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"})
|
||||
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), [])
|
||||
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()
|
||||
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):
|
||||
@@ -351,11 +530,31 @@ class PureTest(unittest.TestCase):
|
||||
|
||||
base = self.matrix()
|
||||
same = self.matrix()
|
||||
for path in ("images/mol/Dockerfile", "images/ci/Dockerfile", "requirements-dev.txt", ".pre-commit-config.yaml"):
|
||||
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
|
||||
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):
|
||||
@@ -368,8 +567,12 @@ 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("images/ci/Dockerfile", labelled("ci", CI_DOCKERFILE.split("\n", 1)[1]))
|
||||
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")
|
||||
@@ -388,13 +591,23 @@ class GitTest(unittest.TestCase):
|
||||
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)
|
||||
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)
|
||||
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):
|
||||
@@ -407,7 +620,10 @@ class GitTest(unittest.TestCase):
|
||||
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")
|
||||
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)
|
||||
@@ -428,10 +644,14 @@ class GitTest(unittest.TestCase):
|
||||
|
||||
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")
|
||||
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")
|
||||
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")
|
||||
@@ -441,13 +661,19 @@ class GitTest(unittest.TestCase):
|
||||
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.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.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")
|
||||
@@ -479,7 +705,9 @@ class GitTest(unittest.TestCase):
|
||||
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.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")
|
||||
@@ -487,13 +715,26 @@ class GitTest(unittest.TestCase):
|
||||
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)
|
||||
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.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)
|
||||
@@ -513,7 +754,9 @@ class GitTest(unittest.TestCase):
|
||||
|
||||
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.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)
|
||||
|
||||
@@ -530,7 +773,9 @@ class GitTest(unittest.TestCase):
|
||||
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.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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user