Files
computer-playbook/tests/unit/python/utils/docker/test_registry_healthcheck.py
T
kevinveenbirkenbachandClaude Opus 5 575a5a87ac refactor(layout): sort shipped scripts by language and split the unit suite
Every script a role ships now lives under `files/<language>/`, and the unit
suite is split the same way: `tests/unit/python/` beside new sibling trees for
the other languages. `tests/lint/filesystem/test_role_files_layout.py` keeps it
that way; directories whose shape is dictated from outside carry a `.nocheck`
naming the constraint (Docker build contexts, WordPress mu-plugins, the Joomla
extension, Odoo addons, Playwright suites, the `files/test/test.sh` harness
that `test-e2e-cli` resolves generically).

This cannot be applied in halves. Moving a file and repointing what names it
are the same change: 14 references resolve only at deploy time, so the tree is
green either before or after, never between.

Those 14 were found by static resolution over every reference class, not by the
test suite -- a full `make quality-high` was green while all of them were
broken:

  * 7 `src:` values built from a role variable holding a bare filename
    (svc-bkp-remote-2-local, decidim, espocrm, friendica, joomla, pixelfed x2).
    The variable doubles as the destination name inside the container, so the
    language segment belongs at the call site, not in the variable.
  * `sys-service/tasks/04_base.yml` resolved every consumer's systemd script
    through `first_found(..., errors='strict')` over `files/script.{sh,py}`.
    18 roles ship exactly that and have no template fallback: the play would
    have died on each.
  * `sys-front-inj-javascript` fell back to `<role>/files/javascript.js`; the
    interface now reads `files/javascript/javascript.js`.
  * `sys-front-inj-logout/templates/head_sub.j2` built the cache-busting mtime
    path through `path_absolute(... 'files', ...)`.
  * 4 `ansible.builtin.script:` invocations naming a bare command
    (pull.py, prune.sh, set_postgres_superuser_password.sh, ganesha-serve.sh).
  * `dev-python/files/shell/install.sh` pointed at a sibling role's script.

Depth-dependent paths inside the moved trees were bumped accordingly: 59
`parents[N]` computations, 12 relative climbs, and the per-role recover CLI,
whose path `cli/administration/recover/recoverers.py` still assembled from the
pre-move location.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 01:31:09 +02:00

125 lines
4.7 KiB
Python

"""image_healthcheck must separate "declares none" from "could not tell".
A sweep that reads an indeterminate answer as an absent probe reports every
image as a gap the moment the network hiccups.
"""
from __future__ import annotations
import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from utils.docker import registry
MANIFEST = {"config": {"digest": "sha256:cfg"}, "layers": [{"size": 1}]}
INDEX = {
"manifests": [
{"platform": {"os": "linux", "architecture": "amd64"}, "digest": "sha256:amd"}
]
}
PROBE = {"Test": ["CMD-SHELL", "dig @127.0.0.1 || exit 1"]}
class _Isolated:
def setUp(self) -> None:
super().setUp()
cache = tempfile.TemporaryDirectory()
self.addCleanup(cache.cleanup)
for patcher in (
mock.patch.object(registry, "_CACHE_ROOT", Path(cache.name)),
mock.patch.dict(os.environ, {"INFINITO_GHCR_MIRROR_PREFIX": ""}),
):
patcher.start()
self.addCleanup(patcher.stop)
def serve(self, manifest, config):
"""Answer manifest requests with *manifest* and blob requests with *config*."""
def _request(url, repo, method, accept):
if "/blobs/" in url:
return (200, {}, json.dumps(config).encode()) if config else None
return (200, {}, json.dumps(manifest).encode()) if manifest else None
return mock.patch.object(registry, "_request", side_effect=_request)
class TestImageHealthcheck(_Isolated, unittest.TestCase):
def test_a_declared_probe_comes_back(self) -> None:
with self.serve(MANIFEST, {"config": {"Healthcheck": PROBE}}):
self.assertEqual(registry.image_healthcheck("redis", "alpine"), PROBE)
def test_an_image_without_one_answers_with_an_empty_mapping(self) -> None:
with self.serve(MANIFEST, {"config": {}}):
self.assertEqual(registry.image_healthcheck("redis", "alpine"), {})
def test_an_unreachable_registry_is_indeterminate_not_absent(self) -> None:
with mock.patch.object(registry, "_request", return_value=None):
self.assertIsNone(registry.image_healthcheck("redis", "alpine"))
def test_a_multi_platform_index_is_resolved_to_the_platform(self) -> None:
seen = []
def _request(url, repo, method, accept):
seen.append(url)
if "/blobs/" in url:
return (
200,
{},
json.dumps({"config": {"Healthcheck": PROBE}}).encode(),
)
body = MANIFEST if "sha256%3Aamd" in url else INDEX
return (200, {}, json.dumps(body).encode())
with mock.patch.object(registry, "_request", side_effect=_request):
self.assertEqual(registry.image_healthcheck("redis", "alpine"), PROBE)
self.assertTrue(any("sha256%3Aamd" in url for url in seen))
def test_an_index_without_the_platform_is_indeterminate(self) -> None:
with (
self.serve(INDEX, {"config": {}}),
mock.patch.object(registry, "_platform_digest", return_value=None),
):
self.assertIsNone(registry.image_healthcheck("redis", "alpine"))
def test_a_determinate_answer_is_cached(self) -> None:
calls = []
def _request(url, repo, method, accept):
calls.append(url)
if "/blobs/" in url:
return (200, {}, json.dumps({"config": {}}).encode())
return (200, {}, json.dumps(MANIFEST).encode())
with mock.patch.object(registry, "_request", side_effect=_request):
registry.image_healthcheck("redis", "alpine")
before = len(calls)
registry.image_healthcheck("redis", "alpine")
self.assertEqual(len(calls), before, "the second read must come from cache")
class TestProbeSource(_Isolated, unittest.TestCase):
def test_the_source_says_where_the_answer_came_from(self) -> None:
with self.serve(MANIFEST, {"config": {}}):
_found, source = registry.image_healthcheck_probed("redis", "alpine")
self.assertEqual(source, "upstream")
def test_a_cached_answer_says_so(self) -> None:
with self.serve(MANIFEST, {"config": {}}):
registry.image_healthcheck_probed("redis", "alpine")
_found, source = registry.image_healthcheck_probed("redis", "alpine")
self.assertEqual(source, "cache")
def test_an_unreachable_registry_reports_none(self) -> None:
with mock.patch.object(registry, "_request", return_value=None):
found, source = registry.image_healthcheck_probed("redis", "alpine")
self.assertIsNone(found)
self.assertEqual(source, "none")
if __name__ == "__main__":
unittest.main()