Merge remote-tracking branch 'origin/main' into feature/network/multi-network-serving

# Conflicts:
#	plugins/lookup/email.py
#	tests/unit/python/roles/web-app-prometheus/test_blackbox_targets.py
This commit is contained in:
kevinveenbirkenbach committed 2026-10-15 16:45:18 +02:00
commit 1da2cef95e
107 files changed
+2414 -478

No files matched your search

@@ -0,0 +1,67 @@
from __future__ import annotations
import os
import tempfile
import unittest
from pathlib import Path
from utils.docker.image.discovery import iter_role_images
from utils.roles.mapping import ROLE_FILE_META_SERVICES
SUPPORTED = """---
demo:
image: libretranslate/libretranslate
version: v1.9.6
lifecycle: stable
helper:
image: alpine
version: "3.22"
"""
RETIRED = """---
demo:
image: quay.io/minio/minio
version: RELEASE.2025-09-07T16-13-09Z
lifecycle: eol
client:
image: quay.io/minio/mc
version: RELEASE.2025-08-13T08-35-41Z
"""
UNSTAGED = """---
demo:
image: libretranslate/libretranslate
version: v1.9.6
"""
class TestImageDiscoveryLifecycle(unittest.TestCase):
def _images(self, services_yaml: str, *, relative: bool = False) -> set[str]:
"""Discover the images of one role written into a temporary repository.
Args:
services_yaml: the role's ``meta/services.yml``.
relative: pass the repository root relative to the working directory.
"""
with tempfile.TemporaryDirectory() as tmp:
services = Path(tmp) / "roles" / "web-app-demo" / ROLE_FILE_META_SERVICES
services.parent.mkdir(parents=True)
services.write_text(services_yaml, encoding="utf-8")
root = Path(os.path.relpath(tmp)) if relative else Path(tmp)
return {ref.service for ref in iter_role_images(root)}
def test_a_supported_role_yields_every_service(self) -> None:
self.assertEqual({"demo", "helper"}, self._images(SUPPORTED))
def test_a_retired_role_yields_none_of_its_services(self) -> None:
self.assertEqual(set(), self._images(RETIRED))
def test_a_role_that_names_no_stage_is_kept(self) -> None:
self.assertEqual({"demo"}, self._images(UNSTAGED))
def test_a_relative_root_still_leaves_a_retired_role_out(self) -> None:
self.assertEqual(set(), self._images(RETIRED, relative=True))
if __name__ == "__main__":
unittest.main()
@@ -10,7 +10,7 @@ directories / no junit files / unparseable junit files.
from __future__ import annotations
import datetime
import datetime as dt
import io
import os
import unittest
@@ -56,9 +56,7 @@ def _write(path: Path, content: str) -> Path:
class TestToIsoZ(unittest.TestCase):
def test_utc_datetime_formats_with_z_suffix(self) -> None:
self.assertEqual(
ps._to_iso_z(
datetime.datetime(2026, 5, 17, 12, 34, 56, tzinfo=datetime.UTC)
),
ps._to_iso_z(dt.datetime(2026, 5, 17, 12, 34, 56, tzinfo=dt.UTC)),
"2026-05-17T12:34:56Z",
)
@@ -263,9 +261,7 @@ class TestSummarizeFile(unittest.TestCase):
Path(tmp) / "web-app-foo" / "playwright-junit.xml",
no_timestamp_fixture,
)
target = datetime.datetime(
2025, 5, 17, 5, 34, 56, tzinfo=datetime.UTC
).timestamp()
target = dt.datetime(2025, 5, 17, 5, 34, 56, tzinfo=dt.UTC).timestamp()
os.utime(xml_path, (target, target))
summary = ps._summarize_file(xml_path)
assert summary is not None
@@ -34,12 +34,30 @@ class TestStampLogic(unittest.TestCase):
with (
mock.patch.object(cli, "PROJECT_ROOT", root),
mock.patch.object(cli.shutil, "which", return_value="/usr/bin/x"),
mock.patch.object(
cli.mermaid_cli, "browser_installed", return_value=True
),
mock.patch.object(cli, "_install_all") as inst,
):
rc = cli.main([])
self.assertEqual(rc, 0)
inst.assert_not_called()
def test_missing_mermaid_browser_invalidates_stamp(self) -> None:
with TemporaryDirectory() as tmp:
root = _make_repo_root(tmp, stamp_age_offset=60.0)
with (
mock.patch.object(cli, "PROJECT_ROOT", root),
mock.patch.object(cli.shutil, "which", return_value="/usr/bin/x"),
mock.patch.object(
cli.mermaid_cli, "browser_installed", return_value=False
),
mock.patch.object(cli, "_install_all") as inst,
):
rc = cli.main([])
self.assertEqual(rc, 0)
inst.assert_called_once()
def test_missing_tool_invalidates_stamp(self) -> None:
with TemporaryDirectory() as tmp:
root = _make_repo_root(tmp, stamp_age_offset=60.0)
@@ -81,9 +99,10 @@ class TestStampLogic(unittest.TestCase):
self.assertTrue((root / cli._STAMP).exists())
def test_force_drops_stamp(self) -> None:
with TemporaryDirectory() as tmp:
with TemporaryDirectory() as tmp, TemporaryDirectory() as cache:
root = _make_repo_root(tmp, stamp_age_offset=60.0)
with (
mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}),
mock.patch.object(cli, "PROJECT_ROOT", root),
mock.patch.object(cli, "_install_all") as inst,
):
@@ -91,6 +110,19 @@ class TestStampLogic(unittest.TestCase):
self.assertEqual(rc, 0)
inst.assert_called_once()
def test_force_drops_the_mermaid_browser(self) -> None:
with TemporaryDirectory() as tmp, TemporaryDirectory() as cache:
root = _make_repo_root(tmp, stamp_age_offset=60.0)
browser = Path(cache) / "chrome-headless-shell" / "linux-1"
browser.mkdir(parents=True)
with (
mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}),
mock.patch.object(cli, "PROJECT_ROOT", root),
mock.patch.object(cli, "_install_all"),
):
cli.main(["--force"])
self.assertFalse(browser.exists())
class TestGroupDispatch(unittest.TestCase):
def test_group_only_bypasses_stamp(self) -> None:
@@ -0,0 +1,228 @@
"""Unit tests for :mod:`utils.install.lint.mermaid_cli`."""
from __future__ import annotations
import contextlib
import os
import subprocess
import unittest
import unittest.mock as mock
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING
from utils.install.lint import mermaid_cli
if TYPE_CHECKING:
from collections.abc import Iterator
REVISION = "155.0.8059.39"
def _done(returncode: int) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess([], returncode, stdout="out\n", stderr="err\n")
def _write_core(node_modules: Path, revision: str) -> None:
revisions = node_modules / "puppeteer-core" / "lib" / "puppeteer"
revisions.mkdir(parents=True)
(revisions / "revisions.js").write_text(
f"export const PUPPETEER_REVISIONS = Object.freeze({{\n"
f" chrome: '155.0.8059.39',\n"
f" 'chrome-headless-shell': '{revision}',\n"
f"}});\n",
encoding="utf-8",
)
def _fake_mmdc(
root: Path, *, revision: str | None = REVISION, nested: str | None = None
) -> Path:
"""Lay out a global mermaid-cli install the way npm does.
Args:
root: npm prefix to build the install under.
revision: chrome-headless-shell revision of the puppeteer-core beside
puppeteer, or None to install mmdc without a puppeteer next to it.
nested: revision of a puppeteer-core nested under puppeteer, as npm
lays it out when mermaid-cli pins another puppeteer-core.
Returns:
The ``bin/mmdc`` symlink.
"""
package = root / "lib" / "node_modules" / "@mermaid-js" / "mermaid-cli"
(package / "src").mkdir(parents=True)
(package / "src" / "cli.js").write_text("", encoding="utf-8")
if revision is not None:
(package / "node_modules" / "puppeteer").mkdir(parents=True)
_write_core(package / "node_modules", revision)
if nested is not None:
_write_core(package / "node_modules" / "puppeteer" / "node_modules", nested)
(root / "bin").mkdir()
mmdc = root / "bin" / "mmdc"
mmdc.symlink_to(package / "src" / "cli.js")
return mmdc
def _install_browser(cache: Path, revision: str) -> None:
build = cache / "chrome-headless-shell" / f"linux-{revision}" / "linux64"
build.mkdir(parents=True)
(build / "chrome-headless-shell").write_text("", encoding="utf-8")
@contextlib.contextmanager
def _environment(
*, revision: str | None = REVISION, nested: str | None = None
) -> Iterator[tuple[Path, Path]]:
"""Patch mmdc's location and the puppeteer cache onto temporary dirs.
Args:
revision: passed to :func:`_fake_mmdc`.
nested: passed to :func:`_fake_mmdc`.
Yields:
The npm prefix and the puppeteer cache directory.
"""
with TemporaryDirectory() as prefix, TemporaryDirectory() as cache:
mmdc = _fake_mmdc(Path(prefix), revision=revision, nested=nested)
with (
mock.patch.dict(os.environ, {"PUPPETEER_CACHE_DIR": cache}),
mock.patch.object(mermaid_cli, "which", return_value=True),
mock.patch.object(mermaid_cli.shutil, "which", return_value=str(mmdc)),
):
yield Path(prefix), Path(cache)
class TestBrowserProvisioning(unittest.TestCase):
def provision(self, *, euid: int, results: list[int]) -> tuple[list, list[str]]:
"""Run ``ensure()`` with mmdc present and a stubbed puppeteer.
Args:
euid: effective uid the run pretends to have.
results: exit codes the successive puppeteer calls return.
Returns:
The recorded subprocess calls and the warnings emitted.
"""
warnings: list[str] = []
with (
_environment(),
mock.patch.object(mermaid_cli.os, "geteuid", return_value=euid),
mock.patch.object(mermaid_cli, "warn", side_effect=warnings.append),
mock.patch.object(
mermaid_cli.subprocess,
"run",
side_effect=[_done(code) for code in results],
) as run,
):
mermaid_cli.ensure()
return run.call_args_list, warnings
def test_root_installs_the_browser_with_its_libraries(self) -> None:
calls, warnings = self.provision(euid=0, results=[0])
self.assertEqual(len(calls), 1)
self.assertEqual(
calls[0].args[0][-2:], ["chrome-headless-shell", "--install-deps"]
)
self.assertEqual(warnings, [])
def test_the_browser_comes_from_the_puppeteer_next_to_mmdc(self) -> None:
calls, _ = self.provision(euid=0, results=[0])
self.assertTrue(
calls[0]
.args[0][0]
.endswith("@mermaid-js/mermaid-cli/node_modules/.bin/puppeteer")
)
def test_a_user_installs_the_browser_without_libraries(self) -> None:
calls, _ = self.provision(euid=1000, results=[0])
self.assertNotIn("--install-deps", calls[0].args[0])
def test_the_browser_install_downloads_despite_the_mmdc_skip_flag(self) -> None:
with mock.patch.dict(os.environ, {"PUPPETEER_SKIP_DOWNLOAD": "1"}):
calls, _ = self.provision(euid=0, results=[0])
self.assertNotIn("PUPPETEER_SKIP_DOWNLOAD", calls[0].kwargs["env"])
def test_a_failed_install_clears_its_revision_and_retries_once(self) -> None:
seen: list[tuple[bool, bool]] = []
with _environment() as (_, cache):
partial = cache / "chrome-headless-shell" / f"linux-{REVISION}"
partial.mkdir(parents=True)
other = cache / "chrome-headless-shell" / "linux-155.0.8059.79"
other.mkdir(parents=True)
def run(*_args, **_kwargs):
seen.append((partial.exists(), other.exists()))
return _done(1 if len(seen) == 1 else 0)
with mock.patch.object(mermaid_cli.subprocess, "run", side_effect=run):
mermaid_cli.ensure()
self.assertEqual(seen, [(True, True), (False, True)])
def test_a_second_failure_warns_with_puppeteers_output(self) -> None:
calls, warnings = self.provision(euid=0, results=[1, 1])
self.assertEqual(len(calls), 2)
self.assertEqual(len(warnings), 1)
self.assertIn("out\nerr\n", warnings[0])
def test_the_pinned_browser_is_not_provisioned_again(self) -> None:
with _environment() as (_, cache):
_install_browser(cache, REVISION)
with mock.patch.object(mermaid_cli.subprocess, "run") as run:
mermaid_cli.ensure()
run.assert_not_called()
def test_a_browser_of_another_revision_is_replaced(self) -> None:
with _environment() as (_, cache):
_install_browser(cache, "155.0.8059.79")
with mock.patch.object(
mermaid_cli.subprocess, "run", return_value=_done(0)
) as run:
mermaid_cli.ensure()
run.assert_called_once()
def test_mmdc_without_its_own_puppeteer_warns(self) -> None:
with (
_environment(revision=None),
mock.patch.object(mermaid_cli, "warn") as warn,
mock.patch.object(mermaid_cli.subprocess, "run") as run,
):
mermaid_cli.ensure()
run.assert_not_called()
warn.assert_called_once()
def test_a_timeout_warns_instead_of_raising(self) -> None:
with (
_environment(),
mock.patch.object(
mermaid_cli.subprocess,
"run",
side_effect=subprocess.TimeoutExpired("puppeteer", 900),
),
mock.patch.object(mermaid_cli, "warn") as warn,
):
mermaid_cli.ensure()
warn.assert_called_once()
class TestBrowserInstalled(unittest.TestCase):
def test_only_the_pinned_revision_counts(self) -> None:
with _environment() as (_, cache):
_install_browser(cache, "155.0.8059.79")
self.assertFalse(mermaid_cli.browser_installed())
_install_browser(cache, REVISION)
self.assertTrue(mermaid_cli.browser_installed())
def test_the_revision_is_read_from_mmdcs_puppeteer_core(self) -> None:
with _environment():
self.assertEqual(mermaid_cli.browser_revision(), REVISION)
def test_a_puppeteer_core_nested_under_puppeteer_wins(self) -> None:
with _environment(revision="155.0.8059.79", nested=REVISION) as (_, cache):
self.assertEqual(mermaid_cli.browser_revision(), REVISION)
_install_browser(cache, REVISION)
self.assertTrue(mermaid_cli.browser_installed())
if __name__ == "__main__":
unittest.main()