From 7e1c2d1273d1546830b2d77592f5095d626f0733 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 5 Oct 2026 20:34:19 +0200 Subject: [PATCH] test(gpu): make the lookup's consumers assert wiring instead of passing vacuously Collapsing the three GPU call sites into one lookup moved the whole decision behind lookup('gpu', ...), but both consumers' tests still stubbed lookup with a constant. One test per file went red; three more kept passing for the wrong reason, because the stub's {} is falsy and every negative case was therefore true no matter what the template did. The stubs now branch on the lookup name and record what they were asked, so each file guards what it still owns: the answer reaches the compose key or the role variable, and the lookup is asked for this service. The declared-flag-times-device matrix stays with the lookup's own tests, which is also where the boolean() over bool() rationale now lives, checked rather than written beside the call it protects. Co-Authored-By: Claude Opus 5 (1M context) --- plugins/lookup/gpu.py | 5 -- .../sys-svc-container/test_gpu_runtime.py | 74 ++++++++----------- .../web-svc-libretranslate/test_gpu_gate.py | 56 +++++++++----- 3 files changed, 67 insertions(+), 68 deletions(-) diff --git a/plugins/lookup/gpu.py b/plugins/lookup/gpu.py index d72e80422e..acddfba125 100644 --- a/plugins/lookup/gpu.py +++ b/plugins/lookup/gpu.py @@ -74,9 +74,4 @@ class LookupModule(LookupBase): ).run([], variables=variables)[0] wanted = resource_filter(applications, application_id, "gpu", service_name, False) - # Exception: boolean(), not bool(). The call sites this replaces read - # the flag through Jinja's `| bool`, which answers False for the - # strings "false", "False", "0" and "no" where bool() answers True. A - # templated declaration renders to such a string, and the difference - # would attach a GPU runtime nothing asked for. return [boolean(wanted, strict=False) and _device_present(variables)] diff --git a/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py b/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py index fc7ddeccfb..25ab2c9004 100644 --- a/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py +++ b/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py @@ -1,3 +1,10 @@ +"""The ``runtime: nvidia`` key of the shared resource template. + +The template asks the ``gpu`` lookup and decides nothing itself: combining +the declared flag with the host's device is that lookup's job, and its own +tests own the matrix. +""" + import unittest from pathlib import Path @@ -23,14 +30,8 @@ BASE = { } -def _ansible_bool(value): - if isinstance(value, str): - return value.strip().lower() in {"y", "yes", "true", "on", "1"} - return bool(value) - - class TestGpuRuntimeRegistration(unittest.TestCase): - def _render(self, *, wants_gpu, host_has_gpu): + def _render(self, *, gpu): env = Environment( loader=FileSystemLoader(str(TEMPLATES)), trim_blocks=True, @@ -38,49 +39,32 @@ class TestGpuRuntimeRegistration(unittest.TestCase): undefined=StrictUndefined, autoescape=select_autoescape(), ) - env.filters["bool"] = _ansible_bool - env.filters["resource_filter"] = lambda _apps, _id, key, _svc, default, **_k: ( - wants_gpu if key == "gpu" else default - ) - env.globals["lookup"] = lambda name, *a, **k: {} - device = {"stat": {"exists": host_has_gpu}} - return env.get_template("resource.yml.j2").render( - {**BASE, "sys_svc_container_nvidia_device": device} + env.filters["resource_filter"] = ( + lambda _apps, _id, _key, _svc, default, **_k: default ) + self.asked = [] + + def _lookup(name, *terms, **_kwargs): + self.asked.append((name, terms)) + return gpu if name == "gpu" else {} + + env.globals["lookup"] = _lookup + return env.get_template("resource.yml.j2").render(BASE) + + def test_the_lookups_yes_reaches_the_runtime_key(self): + self.assertIn("runtime: nvidia", self._render(gpu=True)) + + def test_the_lookups_no_leaves_the_runtime_key_out(self): + self.assertNotIn("runtime:", self._render(gpu=False)) + + def test_the_lookup_is_asked_for_this_service(self): + self._render(gpu=True) - def test_a_gpu_service_on_a_gpu_host_gets_the_nvidia_runtime(self): self.assertIn( - "runtime: nvidia", - self._render(wants_gpu=True, host_has_gpu=True), + ("gpu", ("web-svc-libretranslate", "libretranslate")), + self.asked, ) - def test_a_gpu_service_on_a_host_without_a_card_gets_no_runtime(self): - self.assertNotIn("runtime:", self._render(wants_gpu=True, host_has_gpu=False)) - - def test_a_plain_service_never_gets_the_nvidia_runtime(self): - for host_has_gpu in (True, False): - with self.subTest(host_has_gpu=host_has_gpu): - self.assertNotIn( - "runtime:", - self._render(wants_gpu=False, host_has_gpu=host_has_gpu), - ) - - def test_a_missing_device_fact_is_treated_as_no_gpu(self): - env = Environment( - loader=FileSystemLoader(str(TEMPLATES)), - trim_blocks=True, - lstrip_blocks=False, - undefined=StrictUndefined, - autoescape=select_autoescape(), - ) - env.filters["bool"] = _ansible_bool - env.filters["resource_filter"] = lambda _apps, _id, key, _svc, default, **_k: ( - True if key == "gpu" else default - ) - env.globals["lookup"] = lambda name, *a, **k: {} - - self.assertNotIn("runtime:", env.get_template("resource.yml.j2").render(BASE)) - if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/web-svc-libretranslate/test_gpu_gate.py b/tests/unit/python/roles/web-svc-libretranslate/test_gpu_gate.py index 12ce89af85..4b48cda070 100644 --- a/tests/unit/python/roles/web-svc-libretranslate/test_gpu_gate.py +++ b/tests/unit/python/roles/web-svc-libretranslate/test_gpu_gate.py @@ -1,8 +1,10 @@ """The gpu gate of web-svc-libretranslate. -`resource_filter` reads the flag where `lookup('config', ...)` returned false -for the same declaration, which silently shipped a CPU image twice. The image -tag and the assert task both hang off this one expression. +`lookup('config', ...)` returned false for the same declaration the service +carries, which silently shipped a CPU image twice. The image tag and the +assert task both hang off this one expression, so what it asks and which +service key it names is what this guards. Whether a declared flag and a +present device add up to a yes belongs to the ``gpu`` lookup's own tests. """ from __future__ import annotations @@ -13,12 +15,12 @@ from typing import ClassVar from jinja2 import Environment, StrictUndefined -from plugins.filter.resource_filter import resource_filter from utils import PROJECT_ROOT from utils.cache.yaml import load_yaml from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN ROLE = "web-svc-libretranslate" +SERVICE = "libretranslate" ROLE_DIR = Path(PROJECT_ROOT) / "roles" / ROLE VARS = ROLE_DIR / ROLE_FILE_VARS_MAIN SERVICES = ROLE_DIR / ROLE_FILE_META_SERVICES @@ -33,30 +35,48 @@ def _ansible_bool(value) -> bool: class TestGpuGate(unittest.TestCase): services: ClassVar[dict] = load_yaml(str(SERVICES)) - def _render(self, expression: str, applications: dict) -> str: + def _render(self, expression: str, answer) -> tuple[str, list]: + """Render ``expression`` against a recording ``lookup``. + + Args: + expression: the var expression to render. + answer: what the ``gpu`` lookup answers. + + Returns: + The rendered string and the ``(name, terms)`` of every lookup. + """ + asked: list = [] env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - renders an ansible var expression, not markup - env.filters["resource_filter"] = resource_filter env.filters["bool"] = _ansible_bool - env.globals["lookup"] = lambda name, *a, **k: applications - return env.from_string(expression).render(application_id=ROLE) + + def _lookup(name, *terms, **_kwargs): + asked.append((name, terms)) + return answer if name == "gpu" else {} + + env.globals["lookup"] = _lookup + return env.from_string(expression).render(application_id=ROLE), asked def test_the_role_declares_the_gpu_flag(self) -> None: - self.assertTrue(self.services["libretranslate"].get("gpu")) + self.assertTrue(self.services[SERVICE].get("gpu")) - def test_the_declared_flag_reaches_the_gate(self) -> None: + def test_the_gate_asks_the_gpu_lookup_for_this_service(self) -> None: expression = load_yaml(str(VARS))["LIBRETRANSLATE_GPU"] - rendered = self._render(expression, {ROLE: {"services": self.services}}) + + _rendered, asked = self._render(expression, True) + + self.assertIn(("gpu", (ROLE, SERVICE)), asked) + + def test_a_yes_from_the_lookup_opens_the_gate(self) -> None: + expression = load_yaml(str(VARS))["LIBRETRANSLATE_GPU"] + + rendered, _asked = self._render(expression, True) self.assertTrue(_ansible_bool(rendered)) - def test_a_service_without_the_flag_keeps_the_gate_closed(self) -> None: + def test_a_no_from_the_lookup_keeps_the_gate_closed(self) -> None: expression = load_yaml(str(VARS))["LIBRETRANSLATE_GPU"] - plain = { - "libretranslate": { - k: v for k, v in self.services["libretranslate"].items() if k != "gpu" - } - } - rendered = self._render(expression, {ROLE: {"services": plain}}) + + rendered, _asked = self._render(expression, False) self.assertFalse(_ansible_bool(rendered))