Files
Kamino/tests/scripts/test_next_image_version.py
Defame1297 30316c5a7d
Build / build (pull_request) Successful in 15s
Lint / lint (pull_request) Successful in 59s
Molecule / molecule (pull_request) Successful in 2s
fix(images): name the registry client and report a refused request
The first Images run after #165 failed: the runner's first registry request
from next_image_version.py got HTTP 403, as a bare traceback, while the same
request works from elsewhere and curl reaches the host in the same job. The
suspected cause, a bot filter refusing Python's default User-Agent, is not
confirmed.

Every registry request, the token request included, now sends its own
User-Agent. Every HTTP error becomes a RegistryError that names the status and
the visible text of the response body, and main prints it as one ::error::
line and exits 1. The client logs in at most once, so an empty token cannot
loop. The script takes the registry URL, so the tests drive it against a local
fake registry.

Refs #165

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 22:13:05 +00:00

225 lines
8.5 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import contextlib
import http.server
import io
import json
import pathlib
import sys
import tempfile
import threading
import unittest
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
sys.path.insert(0, str(SCRIPTS))
import next_image_version as niv
def no_label(tag):
raise AssertionError(f"no label lookup expected, got {tag}")
class NextVersion(unittest.TestCase):
def test_first_version_of_a_base_is_patch_zero(self):
self.assertEqual(
niv.next_version("0.3", ["0.2.38", "latest"], "c1", no_label), "0.3.0"
)
def test_changed_inputs_raise_the_numerically_newest_patch(self):
seen = []
def label_of(tag):
seen.append(tag)
return "old"
tags = ["0.2.9", "0.2.10", "0.20.99", "1.2.11", "0.2.10-rc1", "latest"]
self.assertEqual(niv.next_version("0.2", tags, "new", label_of), "0.2.11")
self.assertEqual(seen, ["0.2.10"])
def test_unchanged_inputs_publish_nothing(self):
self.assertIsNone(
niv.next_version("0.1", ["0.1.4"], "same", lambda tag: "same")
)
def test_an_unlabelled_newest_version_counts_as_changed(self):
self.assertEqual(
niv.next_version("0.1", ["0.1.4"], "c", lambda tag: None), "0.1.5"
)
CI = {"subpath": "", "dockerfile": "images/ci/Dockerfile"}
MOL = {"subpath": "images/mol", "dockerfile": "Dockerfile"}
class InputChecksum(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = pathlib.Path(tmp.name)
self.write("images/ci/Dockerfile", "FROM ubuntu:26.04\nCOPY pins.txt ./\n")
self.write("images/mol/Dockerfile", "FROM ubuntu:24.04\n")
self.write("pins.txt", "a==1\n")
self.write("README.md", "readme\n")
def write(self, path, text):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
def checksum(self, entry):
return niv.input_checksum(self.root, entry)
def test_a_copied_file_is_an_input_and_an_unrelated_file_is_not(self):
before = self.checksum(CI)
self.write("README.md", "changed\n")
self.assertEqual(self.checksum(CI), before)
self.write("pins.txt", "a==2\n")
self.assertNotEqual(self.checksum(CI), before)
def test_the_build_context_of_a_subpath_image_is_its_input(self):
before = self.checksum(MOL)
self.write("pins.txt", "a==2\n")
self.assertEqual(self.checksum(MOL), before)
self.write("images/mol/files/new.conf", "x\n")
self.assertNotEqual(self.checksum(MOL), before)
def test_a_mode_change_is_an_input_change(self):
before = self.checksum(CI)
(self.root / "pins.txt").chmod(0o755)
self.assertNotEqual(self.checksum(CI), before)
def test_a_renamed_input_is_an_input_change(self):
self.write("images/mol/a.conf", "x\n")
before = self.checksum(MOL)
(self.root / "images/mol/a.conf").rename(self.root / "images/mol/b.conf")
self.assertNotEqual(self.checksum(MOL), before)
class FakeRegistry(http.server.BaseHTTPRequestHandler):
"""Asks for a token like the Gitea registry; `refuse` refuses every request, `refuse_token` the token."""
refuse = False
refuse_token = False
no_realm = False
empty_token = False
agents = None # a fresh list per test, set in setUp
def do_GET(self):
self.agents.append(self.headers.get("User-Agent"))
if self.refuse:
page = "<html><head><style>" + "p{margin:0}" * 80 + "</style></head>"
page += "<body><h1>Blocked by the firewall</h1></body></html>"
self.reply(403, page.encode(), "text/html")
elif self.path.startswith("/v2/token") and self.refuse_token:
self.reply(401, b'{"errors":[{"message":"token refused"}]}')
elif self.path.startswith("/v2/token"):
self.reply(
200, json.dumps({"token": "" if self.empty_token else "t"}).encode()
)
elif self.no_realm:
self.reply(401, b"{}", extra={"WWW-Authenticate": "Basic"})
elif self.headers.get("Authorization") != "Bearer t":
realm = f"http://127.0.0.1:{self.server.server_port}/v2/token"
self.reply(
401,
b"{}",
extra={"WWW-Authenticate": f'Bearer realm="{realm}",service="reg"'},
)
else:
self.reply(200, json.dumps({"tags": ["0.1.0"]}).encode())
def reply(self, code, body, kind="application/json", extra=None):
self.send_response(code)
self.send_header("Content-Type", kind)
for key, value in (extra or {}).items():
self.send_header(key, value)
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class QuietServer(http.server.HTTPServer):
def handle_error(self, request, client_address):
"""A client hang-up is not a test failure, and must not write to the captured stderr."""
class RegistryClient(unittest.TestCase):
def setUp(self):
FakeRegistry.refuse = FakeRegistry.refuse_token = FakeRegistry.no_realm = False
FakeRegistry.empty_token = False
FakeRegistry.agents = []
server = QuietServer(("127.0.0.1", 0), FakeRegistry)
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
self.url = f"http://127.0.0.1:{server.server_port}"
self.registry = niv.Registry(self.url, "mortis/ci")
def test_every_request_names_the_client(self):
self.assertEqual(self.registry.tags(), ["0.1.0"])
self.assertTrue(FakeRegistry.agents)
for agent in FakeRegistry.agents:
self.assertTrue(agent.startswith("kamino-"), agent)
def test_a_refused_request_names_its_status_and_body(self):
FakeRegistry.refuse = True
with self.assertRaises(niv.RegistryError) as caught:
self.registry.tags()
self.assertIn("403", str(caught.exception))
self.assertIn("Blocked by the firewall", str(caught.exception))
def test_a_refused_token_is_a_registry_error_with_its_body(self):
FakeRegistry.refuse_token = True
with self.assertRaises(niv.RegistryError) as caught:
self.registry.tags()
self.assertIn("401", str(caught.exception))
self.assertIn("token refused", str(caught.exception))
def test_a_401_without_a_token_realm_is_a_registry_error(self):
FakeRegistry.no_realm = True
with self.assertRaises(niv.RegistryError) as caught:
self.registry.tags()
self.assertIn("401", str(caught.exception))
def test_one_login_only_even_when_the_token_is_empty(self):
FakeRegistry.empty_token = True
with self.assertRaises(niv.RegistryError):
self.registry.tags()
self.assertLessEqual(len(FakeRegistry.agents), 3)
def test_the_cli_reports_a_refusal_as_one_error_line_and_fails(self):
FakeRegistry.refuse = True
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
root = pathlib.Path(tmp.name)
(root / ".gitea/workflows").mkdir(parents=True)
(root / ".gitea/workflows/image.yml").write_text(
"jobs:\n image:\n strategy:\n matrix:\n include:\n"
' - name: ci\n base: "0.1"\n subpath: images/ci\n'
" dockerfile: Dockerfile\n",
encoding="utf-8",
)
(root / "images/ci").mkdir(parents=True)
(root / "images/ci/Dockerfile").write_text(
"FROM ubuntu:26.04\n", encoding="utf-8"
)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = niv.main(["next_image_version.py", str(root), "ci", self.url])
self.assertEqual(code, 1)
self.assertEqual(out.getvalue(), "")
# Only the annotation lines: stderr is process-wide, and other threads may write to it.
errors = [
line for line in err.getvalue().splitlines() if line.startswith("::error::")
]
self.assertEqual(len(errors), 1, err.getvalue())
self.assertIn("Blocked by the firewall", errors[0])
if __name__ == "__main__":
unittest.main()