feat(UI): fix migration, errors happening in local deploy and swarm integraton + merged main

This commit is contained in:
Alejandro Roman committed 2026-08-30 21:39:52 +04:00
commit 333079cc2a
3520 files changed
+50658 -17900

No files matched your search

@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[7]
@@ -0,0 +1,21 @@
"""Shared test fixtures for the inventory unit tests.
Kept tiny and centralised so the per-submodule test files stay focused
on their own assertions while reusing the same `DevInventorySpec`
defaults.
"""
from __future__ import annotations
from cli.administration.deploy.development.inventory import DevInventorySpec
def make_spec(**overrides) -> DevInventorySpec:
base = {
"inventory_dir": "/tmp/inv",
"include": ("web-app-keycloak", "web-app-nextcloud"),
"storage_constrained": False,
"runtime": "dev",
}
base.update(overrides)
return DevInventorySpec(**base)
@@ -0,0 +1,327 @@
"""Unit tests for `cli.administration.deploy.development.inventory.builder`."""
from __future__ import annotations
import json
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from cli.administration.deploy.development.common import DEV_INVENTORY_VARS_FILE
from cli.administration.deploy.development.inventory import (
build_dev_inventory,
build_dev_inventory_matrix,
)
from ._fixtures import make_spec
class TestBuildDevInventory(unittest.TestCase):
def setUp(self) -> None:
self.compose = MagicMock()
self.compose.repo_root = Path("/tmp/infinito-nexus")
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={
"web-app-keycloak": [{}],
"web-app-nextcloud": [{}],
},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=False,
)
def test_invokes_infinito_inventory_provision_with_spot_vars_file(
self,
_mirrors_mock: MagicMock,
_variants_mock: MagicMock,
) -> None:
build_dev_inventory(self.compose, make_spec())
self.assertEqual(self.compose.exec.call_count, 2)
first_cmd = self.compose.exec.call_args_list[0].args[0]
self.assertEqual(
first_cmd[0:4],
["infinito", "administration", "inventory", "provision"],
)
vars_file_index = first_cmd.index("--vars-file") + 1
self.assertEqual(first_cmd[vars_file_index], DEV_INVENTORY_VARS_FILE)
include_index = first_cmd.index("--include") + 1
self.assertEqual(first_cmd[include_index], "web-app-keycloak,web-app-nextcloud")
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={
"web-app-multi": [
{"server": {"domains": {"canonical": ["multi.example"]}}},
{
"server": {
"domains": {"canonical": ["blog.multi.example"]},
},
"services": {"x": {"flag": True}},
},
],
},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=False,
)
def test_active_variant_one_is_baked_into_applications_overrides(
self,
_mirrors_mock: MagicMock,
_variants_mock: MagicMock,
) -> None:
spec = make_spec(
include=("web-app-multi",),
active_variants={"web-app-multi": 1},
)
build_dev_inventory(self.compose, spec)
first_cmd = self.compose.exec.call_args_list[0].args[0]
vars_index = first_cmd.index("--vars") + 1
baked = json.loads(first_cmd[vars_index])
self.assertEqual(
baked["applications"]["web-app-multi"]["server"]["domains"]["canonical"],
["blog.multi.example"],
)
self.assertEqual(
baked["applications"]["web-app-multi"]["services"]["x"],
{"flag": True},
)
self.assertEqual(baked["STORAGE_CONSTRAINED"], False)
self.assertEqual(baked["RUNTIME"], "dev")
@patch(
"cli.administration.deploy.development.inventory.builder.generate_ci_mirrors_file",
autospec=True,
return_value="/etc/mirrors.yml",
)
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={"web-app-keycloak": [{}], "web-app-nextcloud": [{}]},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=True,
)
def test_appends_mirror_arg_on_ci(
self,
_mirrors_active_mock: MagicMock,
_variants_mock: MagicMock,
mirrors_file_mock: MagicMock,
) -> None:
build_dev_inventory(self.compose, make_spec())
first_cmd = self.compose.exec.call_args_list[0].args[0]
mirror_index = first_cmd.index("--mirror") + 1
self.assertEqual(first_cmd[mirror_index], "/etc/mirrors.yml")
mirrors_file_mock.assert_called_once_with(
self.compose, inventory_dir="/tmp/inv"
)
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={"web-app-keycloak": [{}], "web-app-nextcloud": [{}]},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=False,
)
def test_propagates_services_disabled_into_extra_env(
self,
_mirrors_mock: MagicMock,
_variants_mock: MagicMock,
) -> None:
build_dev_inventory(
self.compose, make_spec(services_disabled="svc-foo,svc-bar")
)
first_kwargs = self.compose.exec.call_args_list[0].kwargs
self.assertEqual(
first_kwargs.get("extra_env"),
{"disable": "svc-foo,svc-bar"},
)
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={"web-app-keycloak": [{}], "web-app-nextcloud": [{}]},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=False,
)
def test_omits_extra_env_when_services_disabled_unset(
self,
_mirrors_mock: MagicMock,
_variants_mock: MagicMock,
) -> None:
build_dev_inventory(self.compose, make_spec())
first_kwargs = self.compose.exec.call_args_list[0].kwargs
self.assertIsNone(first_kwargs.get("extra_env"))
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={
"svc-bkp-volume-2-local": [{}, {}, {}],
},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=False,
)
def test_passes_app_variants_when_round_pins_variants(
self,
_mirrors_mock: MagicMock,
_variants_mock: MagicMock,
) -> None:
spec = make_spec(
include=("svc-bkp-volume-2-local",),
active_variants={"svc-bkp-volume-2-local": 2},
)
build_dev_inventory(self.compose, spec)
first_cmd = self.compose.exec.call_args_list[0].args[0]
self.assertIn("--app-variants", first_cmd)
variants_index = first_cmd.index("--app-variants") + 1
self.assertEqual(
json.loads(first_cmd[variants_index]),
{"svc-bkp-volume-2-local": 2},
)
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={"web-app-keycloak": [{}], "web-app-nextcloud": [{}]},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=False,
)
def test_omits_app_variants_when_round_has_none(
self,
_mirrors_mock: MagicMock,
_variants_mock: MagicMock,
) -> None:
build_dev_inventory(self.compose, make_spec())
first_cmd = self.compose.exec.call_args_list[0].args[0]
self.assertNotIn("--app-variants", first_cmd)
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
return_value={"web-app-keycloak": [{}], "web-app-nextcloud": [{}]},
)
@patch(
"cli.administration.deploy.development.inventory.builder.should_use_mirrors",
autospec=True,
return_value=False,
)
def test_runs_password_file_ensure_step(
self,
_mirrors_mock: MagicMock,
_variants_mock: MagicMock,
) -> None:
build_dev_inventory(self.compose, make_spec(inventory_dir="/srv/inv/"))
password_cmd = self.compose.exec.call_args_list[1].args[0]
self.assertEqual(password_cmd[0], "sh")
self.assertEqual(password_cmd[1], "-lc")
shell_script = password_cmd[2]
self.assertIn("mkdir -p /srv/inv", shell_script)
self.assertIn("/srv/inv/.password", shell_script)
class TestBuildDevInventoryMatrix(unittest.TestCase):
def setUp(self) -> None:
self.compose = MagicMock()
self.compose.repo_root = Path("/tmp/infinito-nexus")
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include",
autospec=True,
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._build_services_overrides_for_round",
autospec=True,
return_value={},
)
@patch(
"cli.administration.deploy.development.inventory.builder.build_dev_inventory",
autospec=True,
)
@patch(
"cli.administration.deploy.development.inventory.planner.get_variants",
autospec=True,
return_value={
"web-app-multi": [{"v": 0}, {"v": 1}],
"web-app-keycloak": [{}],
},
)
def test_builds_one_inventory_per_round_and_returns_plan(
self,
_variants_mock: MagicMock,
build_inventory_mock: MagicMock,
_overrides_mock: MagicMock,
resolve_include_mock: MagicMock,
) -> None:
resolve_include_mock.side_effect = [
("web-app-multi", "web-app-keycloak"),
("web-app-multi", "web-app-keycloak"),
]
plan = build_dev_inventory_matrix(
self.compose,
base_inventory_dir="/srv/inv",
primary_apps=("web-app-multi",),
storage_constrained=False,
runtime="dev",
)
self.assertEqual(
[(idx, inv, vs, inc, purge) for idx, inv, vs, inc, purge in plan],
[
(
0,
"/srv/inv-0",
{"web-app-multi": 0, "web-app-keycloak": 0},
("web-app-multi", "web-app-keycloak"),
("web-app-multi", "web-app-keycloak"),
),
(
1,
"/srv/inv-1",
{"web-app-multi": 1, "web-app-keycloak": 0},
("web-app-multi", "web-app-keycloak"),
("web-app-multi", "web-app-keycloak"),
),
],
)
self.assertEqual(build_inventory_mock.call_count, 2)
for (_round_idx, inv_dir, round_vars, round_include, _purge), call in zip(
plan, build_inventory_mock.call_args_list, strict=False
):
spec_arg = call.args[1]
self.assertEqual(spec_arg.inventory_dir, inv_dir)
self.assertEqual(dict(spec_arg.active_variants or {}), round_vars)
self.assertEqual(tuple(spec_arg.include), round_include)
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,83 @@
"""Unit tests for `prune_orphans_after_disable` (legacy_resolver).
The graph walk is exercised against a fake `CombinedResolver` so the
cut-node and cross-parent semantics are pinned independently of the
real role topology.
"""
from __future__ import annotations
import unittest
from types import SimpleNamespace
from unittest.mock import patch
from cli.administration.deploy.development.inventory import (
prune_orphans_after_disable,
)
class _FakeResolver:
def __init__(self, edges: dict[str, list[str]], **_kwargs: object) -> None:
self._edges = edges
def edges_for(self, node: str) -> SimpleNamespace:
return SimpleNamespace(
dependencies=[],
services=self._edges.get(node, []),
run_after=[],
)
_GRAPH = {
"A": ["M", "P"],
"M": ["K"],
"P": ["K"],
"K": ["DB"],
"N": ["DB"],
}
_RESOLVER_PATH = (
"cli.meta.roles.applications.resolution.combined.resolver.CombinedResolver"
)
class TestPruneOrphansAfterDisable(unittest.TestCase):
def _prune(self, include, primaries, disabled):
with patch(
_RESOLVER_PATH,
side_effect=lambda **kw: _FakeResolver(_GRAPH, **kw),
):
return prune_orphans_after_disable(
include=include,
primary_apps=primaries,
disabled_app_ids=disabled,
services_overrides={},
)
def test_sole_root_disable_collapses_subtree(self) -> None:
kept, pruned = self._prune(
include=("DB", "K", "M", "P", "A"),
primaries=["A"],
disabled={"M", "P"},
)
self.assertEqual(kept, ("A",))
self.assertEqual(sorted(pruned), ["DB", "K"])
def test_no_disable_is_identity(self) -> None:
include = ("DB", "K", "M", "P", "A")
kept, pruned = self._prune(include=include, primaries=["A"], disabled=set())
self.assertEqual(kept, include)
self.assertEqual(pruned, ())
def test_shared_dep_kept_when_another_primary_parents_it(self) -> None:
kept, pruned = self._prune(
include=("DB", "K", "M", "P", "A", "N"),
primaries=["A", "N"],
disabled={"M"},
)
self.assertIn("DB", kept)
self.assertNotIn("M", kept)
self.assertEqual(pruned, ())
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,92 @@
"""Unit tests for `cli.administration.deploy.development.inventory.payload`."""
from __future__ import annotations
import unittest
from unittest.mock import MagicMock, patch
from cli.administration.deploy.development.inventory import (
_bake_overrides,
_resolve_variant_payloads,
)
class TestResolveVariantPayloads(unittest.TestCase):
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
)
def test_app_without_meta_collapses_to_variant_zero_payload(
self, get_overrides_mock: MagicMock
) -> None:
get_overrides_mock.return_value = {"web-app-foo": [{}]}
resolved = _resolve_variant_payloads(
roles_dir="/roles",
include=["web-app-foo"],
active_variants={},
)
self.assertEqual(resolved, {"web-app-foo": {}})
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
)
def test_active_variants_picks_named_variant(
self, get_overrides_mock: MagicMock
) -> None:
get_overrides_mock.return_value = {
"web-app-multi": [{"variant": 0}, {"variant": 1}],
}
resolved = _resolve_variant_payloads(
roles_dir="/roles",
include=["web-app-multi"],
active_variants={"web-app-multi": 1},
)
self.assertEqual(resolved, {"web-app-multi": {"variant": 1}})
@patch(
"cli.administration.deploy.development.inventory.payload.get_variant_overrides_only",
autospec=True,
)
def test_out_of_range_index_falls_back_to_variant_zero(
self, get_overrides_mock: MagicMock
) -> None:
get_overrides_mock.return_value = {
"web-app-multi": [{"variant": 0}, {"variant": 1}],
}
resolved = _resolve_variant_payloads(
roles_dir="/roles",
include=["web-app-multi"],
active_variants={"web-app-multi": 99},
)
self.assertEqual(resolved, {"web-app-multi": {"variant": 0}})
class TestBakeOverrides(unittest.TestCase):
def test_user_supplied_applications_override_wins_over_variant_payload(self):
baked = _bake_overrides(
base_overrides={
"STORAGE_CONSTRAINED": False,
"RUNTIME": "dev",
"applications": {
"web-app-foo": {"feature_flag": True},
},
},
variant_payloads={
"web-app-foo": {"feature_flag": False, "image": "v1"},
},
)
self.assertEqual(
baked["applications"]["web-app-foo"],
{"feature_flag": True, "image": "v1"},
)
def test_no_variant_payloads_yields_unchanged_base(self):
base = {"STORAGE_CONSTRAINED": False, "RUNTIME": "dev"}
baked = _bake_overrides(base_overrides=base, variant_payloads={})
self.assertEqual(baked, base)
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,259 @@
"""Unit tests for `cli.administration.deploy.development.inventory.planner`.
Covers ``plan_dev_inventory_matrix`` (mocking ``legacy_resolver``) and
``filter_plan_to_variants``.
"""
from __future__ import annotations
import unittest
from typing import ClassVar
from unittest.mock import MagicMock, patch
from cli.administration.deploy.development.inventory import (
filter_plan_to_variants,
plan_dev_inventory_matrix,
)
class TestPlanDevInventoryMatrix(unittest.TestCase):
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include",
autospec=True,
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._build_services_overrides_for_round",
autospec=True,
return_value={},
)
@patch(
"cli.administration.deploy.development.inventory.planner.get_variants",
autospec=True,
)
def test_single_variant_apps_share_one_unsuffixed_folder(
self,
get_variants_mock: MagicMock,
_overrides_mock: MagicMock,
resolve_include_mock: MagicMock,
) -> None:
get_variants_mock.return_value = {
"web-app-foo": [{}],
"web-app-bar": [{}],
}
resolve_include_mock.return_value = ("web-app-foo", "web-app-bar")
plan = plan_dev_inventory_matrix(
roles_dir="/roles",
primary_apps=["web-app-foo", "web-app-bar"],
base_inventory_dir="/srv/inv",
)
self.assertEqual(
plan,
[
(
0,
"/srv/inv",
{"web-app-foo": 0, "web-app-bar": 0},
("web-app-foo", "web-app-bar"),
("web-app-foo", "web-app-bar"),
)
],
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include",
autospec=True,
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._build_services_overrides_for_round",
autospec=True,
return_value={},
)
@patch(
"cli.administration.deploy.development.inventory.planner.get_variants",
autospec=True,
)
def test_two_variant_primary_drives_two_suffixed_folders(
self,
get_variants_mock: MagicMock,
_overrides_mock: MagicMock,
resolve_include_mock: MagicMock,
) -> None:
get_variants_mock.return_value = {
"web-app-multi": [{"variant": 0}, {"variant": 1}],
"web-app-keycloak": [{}],
}
resolve_include_mock.side_effect = [
("web-app-multi", "web-app-keycloak"),
("web-app-multi", "web-app-keycloak"),
]
plan = plan_dev_inventory_matrix(
roles_dir="/roles",
primary_apps=["web-app-multi"],
base_inventory_dir="/srv/inv",
)
self.assertEqual(
plan,
[
(
0,
"/srv/inv-0",
{"web-app-multi": 0, "web-app-keycloak": 0},
("web-app-multi", "web-app-keycloak"),
("web-app-multi", "web-app-keycloak"),
),
(
1,
"/srv/inv-1",
{"web-app-multi": 1, "web-app-keycloak": 0},
("web-app-multi", "web-app-keycloak"),
("web-app-multi", "web-app-keycloak"),
),
],
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include",
autospec=True,
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._build_services_overrides_for_round",
autospec=True,
return_value={},
)
@patch(
"cli.administration.deploy.development.inventory.planner.get_variants",
autospec=True,
)
def test_round_count_driven_by_primary_max_variants(
self,
get_variants_mock: MagicMock,
_overrides_mock: MagicMock,
resolve_include_mock: MagicMock,
) -> None:
get_variants_mock.return_value = {
"web-app-three": [{}, {}, {}],
"web-app-two": [{}, {}],
}
resolve_include_mock.side_effect = [
("web-app-three", "web-app-two"),
("web-app-three", "web-app-two"),
("web-app-three", "web-app-two"),
]
plan = plan_dev_inventory_matrix(
roles_dir="/roles",
primary_apps=["web-app-three", "web-app-two"],
base_inventory_dir="/srv/inv",
)
self.assertEqual(
plan,
[
(
0,
"/srv/inv-0",
{"web-app-three": 0, "web-app-two": 0},
("web-app-three", "web-app-two"),
("web-app-three", "web-app-two"),
),
(
1,
"/srv/inv-1",
{"web-app-three": 1, "web-app-two": 1},
("web-app-three", "web-app-two"),
("web-app-three", "web-app-two"),
),
(
2,
"/srv/inv-2",
{"web-app-three": 2, "web-app-two": 0},
("web-app-three", "web-app-two"),
("web-app-three", "web-app-two"),
),
],
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include",
autospec=True,
)
@patch(
"cli.administration.deploy.development.inventory.legacy_resolver._build_services_overrides_for_round",
autospec=True,
return_value={},
)
@patch(
"cli.administration.deploy.development.inventory.planner.get_variants",
autospec=True,
)
def test_purge_set_is_union_when_variants_differ(
self,
get_variants_mock: MagicMock,
_overrides_mock: MagicMock,
resolve_include_mock: MagicMock,
) -> None:
get_variants_mock.return_value = {
"web-app-nextcloud": [{"shared_coturn": True}, {"shared_coturn": False}],
}
resolve_include_mock.side_effect = [
("web-app-nextcloud", "web-svc-coturn"),
("web-app-nextcloud",),
]
plan = plan_dev_inventory_matrix(
roles_dir="/roles",
primary_apps=["web-app-nextcloud"],
base_inventory_dir="/srv/inv",
)
self.assertEqual(plan[0][3], ("web-app-nextcloud", "web-svc-coturn"))
self.assertEqual(plan[1][3], ("web-app-nextcloud",))
union = ("web-app-nextcloud", "web-svc-coturn")
self.assertEqual(plan[0][4], union)
self.assertEqual(plan[1][4], union)
def test_empty_primary_apps_rejected(self):
with self.assertRaises(ValueError):
plan_dev_inventory_matrix(
roles_dir="/roles",
primary_apps=[],
base_inventory_dir="/srv/inv",
)
class TestFilterPlanToVariants(unittest.TestCase):
PLAN: ClassVar[list[tuple]] = [
(i, f"/srv/inv-{i}", {"web-app-multi": i}, ("web-app-multi",), ())
for i in range(5)
]
def test_none_returns_full_plan(self):
self.assertEqual(filter_plan_to_variants(self.PLAN, None), self.PLAN)
def test_subset_keeps_only_listed_rounds_in_plan_order(self):
self.assertEqual(
filter_plan_to_variants(self.PLAN, [0, 1, 2]),
self.PLAN[:3],
)
self.assertEqual(
filter_plan_to_variants(self.PLAN, [3, 4]),
self.PLAN[3:],
)
def test_a_gap_in_the_selection_drops_only_the_rounds_it_skips(self):
"""The tor axis' ``exclusive`` mode hands over a bundle with holes: a
role whose middle variant cannot take an onion yields ``0,2``."""
self.assertEqual(
filter_plan_to_variants(self.PLAN, [0, 2, 4]),
[self.PLAN[0], self.PLAN[2], self.PLAN[4]],
)
def test_order_follows_plan_not_argument(self):
self.assertEqual(
filter_plan_to_variants(self.PLAN, [4, 0]),
[self.PLAN[0], self.PLAN[4]],
)
def test_out_of_range_raises_value_error(self):
with self.assertRaisesRegex(ValueError, r"variants \[7\] out of range"):
filter_plan_to_variants(self.PLAN, [0, 7])
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,63 @@
"""Unit tests for `cli.administration.deploy.development.inventory.spec`."""
from __future__ import annotations
import unittest
from cli.administration.deploy.development.inventory import DevInventorySpec
from ._fixtures import make_spec
class TestDevInventorySpec(unittest.TestCase):
def test_empty_include_rejected(self):
with self.assertRaises(ValueError):
DevInventorySpec(
inventory_dir="/tmp/inv",
include=(),
storage_constrained=False,
runtime="dev",
)
def test_list_include_normalised_to_tuple(self):
spec = DevInventorySpec(
inventory_dir="/tmp/inv",
include=["web-app-keycloak"],
storage_constrained=True,
runtime="dev",
)
self.assertIsInstance(spec.include, tuple)
self.assertEqual(spec.include, ("web-app-keycloak",))
def test_overrides_default(self):
spec = make_spec(storage_constrained=True, runtime="prod")
self.assertEqual(
spec.overrides(),
{"STORAGE_CONSTRAINED": True, "RUNTIME": "prod"},
)
def test_extra_vars_win_over_implicit_overrides(self):
spec = make_spec(
storage_constrained=False,
runtime="dev",
extra_vars={"STORAGE_CONSTRAINED": True, "FOO": "bar"},
)
self.assertEqual(
spec.overrides(),
{"STORAGE_CONSTRAINED": True, "RUNTIME": "dev", "FOO": "bar"},
)
def test_inventory_root_strips_trailing_slash(self):
spec = make_spec(inventory_dir="/tmp/inv///")
self.assertEqual(spec.inventory_root(), "/tmp/inv")
def test_variant_selectors_default_to_empty_dict(self):
self.assertEqual(make_spec().variant_selectors(), {})
def test_variant_selectors_returned_as_plain_dict(self):
spec = make_spec(active_variants={"web-app-keycloak": 2})
self.assertEqual(spec.variant_selectors(), {"web-app-keycloak": 2})
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,294 @@
# tests/cli/administration/deploy/development/test_compose.py
from __future__ import annotations
import os
import subprocess
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from cli.administration.deploy.development.compose import Compose
class TestComposeUpRetries(unittest.TestCase):
def _compose(self) -> Compose:
return Compose(repo_root=Path("/tmp/infinito-nexus"), distro="arch")
@patch("time.sleep", autospec=True)
def test_compose_up_with_retries_succeeds_after_transient_failures(
self, sleep_mock: MagicMock
) -> None:
compose = self._compose()
compose.run = MagicMock(
side_effect=[
subprocess.CalledProcessError(1, ["docker", "compose"], "out1", "err1"),
subprocess.CalledProcessError(1, ["docker", "compose"], "out2", "err2"),
subprocess.CompletedProcess(
["docker", "compose"], 0, stdout="", stderr=""
),
]
)
args = [
"up",
"-d",
"--no-build",
"coredns",
"infinito",
]
compose._compose_up_with_retries(args, attempts=6, delay_s=30)
self.assertEqual(compose.run.call_count, 3)
self.assertEqual(sleep_mock.call_count, 2)
sleep_mock.assert_any_call(30)
self.assertTrue(all(call.args == (30,) for call in sleep_mock.call_args_list))
@patch("time.sleep", autospec=True)
def test_compose_up_with_retries_raises_after_exhausting_attempts(
self, sleep_mock: MagicMock
) -> None:
compose = self._compose()
compose.run = MagicMock(
side_effect=subprocess.CalledProcessError(
1, ["docker", "compose"], "out", "err"
)
)
args = ["up", "-d", "coredns", "infinito"]
with self.assertRaises(subprocess.CalledProcessError):
compose._compose_up_with_retries(args, attempts=6, delay_s=30)
self.assertEqual(compose.run.call_count, 6)
self.assertEqual(sleep_mock.call_count, 5)
self.assertTrue(all(call.args == (30,) for call in sleep_mock.call_args_list))
@patch("time.sleep", autospec=True)
def test_compose_up_with_retries_no_sleep_if_first_try_succeeds(
self, sleep_mock: MagicMock
) -> None:
compose = self._compose()
compose.run = MagicMock(
return_value=subprocess.CompletedProcess(
["docker", "compose"], 0, stdout="", stderr=""
)
)
args = ["up", "-d", "coredns", "infinito"]
compose._compose_up_with_retries(args, attempts=6, delay_s=30)
self.assertEqual(compose.run.call_count, 1)
sleep_mock.assert_not_called()
@patch.dict(
os.environ,
{
"INFINITO_IMAGE": "test-image/arch",
"GITHUB_ACTIONS": "true",
"INFINITO_RUNNING_ON_GITHUB": "true",
"CI": "true",
"INFINITO_GIT_COMMON_DIR": "",
"INFINITO_CACHE_NETWORK": "",
"INFINITO_CACHE_STACK": "",
},
clear=False,
)
@patch("subprocess.run", autospec=True)
def test_run_skips_cache_override_on_github_runner(
self, run_mock: MagicMock
) -> None:
compose = self._compose()
run_mock.return_value = subprocess.CompletedProcess(
["docker", "compose", "ps", "-q", "infinito"],
0,
stdout="cid\n",
stderr="",
)
r = compose.run(["ps", "-q", "infinito"], check=False, capture=True)
self.assertEqual(r.returncode, 0)
self.assertEqual(run_mock.call_count, 1)
cmd = run_mock.call_args.args[0]
env = run_mock.call_args.kwargs["env"]
self.assertEqual(
cmd,
[
"docker",
"compose",
"-f",
"compose.yml",
"ps",
"-q",
"infinito",
],
)
self.assertEqual(env["INFINITO_DISTRO"], "arch")
self.assertNotIn("COMPOSE_PROFILES", env)
@patch.dict(
os.environ,
{
"INFINITO_IMAGE": "test-image/arch",
"GITHUB_ACTIONS": "",
"INFINITO_RUNNING_ON_GITHUB": "",
"CI": "",
"INFINITO_GIT_COMMON_DIR": "",
"INFINITO_CACHE_NETWORK": "",
"INFINITO_CACHE_STACK": "",
},
clear=False,
)
@patch("subprocess.run", autospec=True)
def test_run_layers_cache_override_locally(self, run_mock: MagicMock) -> None:
compose = self._compose()
run_mock.return_value = subprocess.CompletedProcess(
["docker", "compose"], 0, stdout="", stderr=""
)
compose.run(["ps", "-q", "infinito"], check=False, capture=True)
cmd = run_mock.call_args.args[0]
env = run_mock.call_args.kwargs["env"]
self.assertEqual(
cmd,
[
"docker",
"compose",
"-f",
"compose.yml",
"-f",
"compose/cache.override.yml",
"ps",
"-q",
"infinito",
],
)
self.assertEqual(
env["INFINITO_CACHE_REGISTRY_PROXY_CONF"], # nocheck: test-fixture
"./compose/registry-cache/proxy.conf",
)
self.assertTrue(
env["INFINITO_CACHE_PACKAGE_FRONTEND_CA_FILE"].endswith(
"/ca.crt"
) # nocheck: test-fixture
)
@patch.dict(
os.environ,
{
"INFINITO_BUILD": "1",
"INFINITO_IMAGE": "infinito-debian",
"INFINITO_PULL_POLICY": "never",
"CI": "true",
"GITHUB_ACTIONS": "true",
"INFINITO_RUNNING_ON_GITHUB": "true",
"INFINITO_CACHE_STACK": "",
},
clear=False,
)
def test_up_builds_when_build_flag_is_enabled(self) -> None:
compose = self._compose()
compose._render_coredns_corefile = MagicMock()
compose._compose_up_with_retries = MagicMock()
compose.wait_for_healthy = MagicMock()
compose.up(run_entry_init=False)
compose._compose_up_with_retries.assert_called_once_with(
["up", "-d", "coredns", "infinito"],
attempts=6,
delay_s=30,
)
compose.wait_for_healthy.assert_called_once_with()
@patch.dict(
os.environ,
{
"INFINITO_BUILD": "0",
"INFINITO_IMAGE": "test-image/arch",
"CI": "true",
"GITHUB_ACTIONS": "true",
"INFINITO_RUNNING_ON_GITHUB": "true",
"INFINITO_CACHE_STACK": "",
},
clear=False,
)
def test_up_skips_build_when_build_flag_is_disabled(self) -> None:
compose = self._compose()
compose._render_coredns_corefile = MagicMock()
compose._compose_up_with_retries = MagicMock()
compose.wait_for_healthy = MagicMock()
compose.up(run_entry_init=False)
compose._compose_up_with_retries.assert_called_once_with(
[
"up",
"-d",
"--no-build",
"coredns",
"infinito",
],
attempts=6,
delay_s=30,
)
compose.wait_for_healthy.assert_called_once_with()
@patch.dict(
os.environ,
{
"INFINITO_BUILD": "1",
"INFINITO_IMAGE": "infinito-debian",
"INFINITO_PULL_POLICY": "never",
"CI": "",
"GITHUB_ACTIONS": "",
"INFINITO_RUNNING_ON_GITHUB": "",
"INFINITO_GIT_COMMON_DIR": "",
"INFINITO_CACHE_NETWORK": "",
"INFINITO_CACHE_STACK": "",
},
clear=False,
)
def test_up_includes_cache_services_when_local(self) -> None:
compose = self._compose()
compose._render_coredns_corefile = MagicMock()
compose._compose_up_with_retries = MagicMock()
compose.wait_for_healthy = MagicMock()
compose._bootstrap_package_cache = MagicMock()
compose._generate_package_frontend_certs = MagicMock()
compose._install_package_frontend_ca_in_runner = MagicMock()
compose.up(run_entry_init=False)
compose._compose_up_with_retries.assert_called_once_with(
[
"up",
"-d",
"registry-cache",
"package-cache",
"package-cache-frontend",
"coredns",
"infinito",
],
attempts=6,
delay_s=30,
)
compose.wait_for_healthy.assert_called_once_with()
compose._bootstrap_package_cache.assert_called_once()
compose._generate_package_frontend_certs.assert_called_once()
compose._install_package_frontend_ca_in_runner.assert_called_once()
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,48 @@
"""Pins the inner-Docker-root wipe: it escalates, and a surviving root is fatal."""
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from cli.administration.deploy.development.down import _wipe_docker_root
class TestWipeDockerRoot(unittest.TestCase):
@patch("cli.administration.deploy.development.down.subprocess.run", autospec=True)
def test_the_wipe_escalates(self, run_mock: MagicMock) -> None:
with tempfile.TemporaryDirectory() as tmp:
docker_root = Path(tmp) / "docker"
docker_root.mkdir()
_wipe_docker_root(docker_root)
commands = [call.args[0] for call in run_mock.call_args_list]
self.assertEqual(commands[0], ["sudo", "rm", "-rf", str(docker_root)])
self.assertTrue(all(cmd[0] == "sudo" for cmd in commands))
@patch("cli.administration.deploy.development.down.subprocess.run", autospec=True)
def test_a_surviving_docker_root_is_a_hard_error(self, run_mock: MagicMock) -> None:
with tempfile.TemporaryDirectory() as tmp:
docker_root = Path(tmp) / "docker"
docker_root.mkdir()
(docker_root / "containers").mkdir()
with self.assertRaises(RuntimeError) as ctx:
_wipe_docker_root(docker_root)
self.assertIn("containers", str(ctx.exception))
self.assertTrue(run_mock.called)
@patch("cli.administration.deploy.development.down.subprocess.run", autospec=True)
def test_a_missing_docker_root_is_not_wiped(self, run_mock: MagicMock) -> None:
with tempfile.TemporaryDirectory() as tmp:
_wipe_docker_root(Path(tmp) / "absent")
run_mock.assert_not_called()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,103 @@
"""Unit tests for compose_file_args.
Pins which override files each runtime context layers on compose.yml. Every
override is gated on the resource it needs rather than on the instance slot,
because an unsatisfied `:?` guard inside one of them aborts the whole stack.
"""
from __future__ import annotations
import os
import unittest
from unittest.mock import patch
from cli.administration.deploy.development.env import compose_file_args
_LOCAL_PRIMARY = {
"GITHUB_ACTIONS": "",
"INFINITO_RUNNING_ON_GITHUB": "",
"CI": "",
"INFINITO_INSTANCE": "0",
"INFINITO_GIT_COMMON_DIR": "",
"INFINITO_CACHE_NETWORK": "",
"INFINITO_CACHE_STACK": "",
"INFINITO_PUBLISH_PORTS": "",
}
_WORKTREE = {
**_LOCAL_PRIMARY,
"INFINITO_INSTANCE": "2",
"INFINITO_GIT_COMMON_DIR": "/repo/.git",
"INFINITO_CACHE_NETWORK": "primary_default",
}
class TestComposeFileArgs(unittest.TestCase):
@patch.dict(os.environ, _LOCAL_PRIMARY, clear=False)
def test_primary_instance_loads_the_cache_stack(self) -> None:
self.assertEqual(
compose_file_args(),
["-f", "compose.yml", "-f", "compose/cache.override.yml"],
)
@patch.dict(os.environ, _WORKTREE, clear=False)
def test_worktree_adds_the_git_and_shared_cache_overrides(self) -> None:
self.assertEqual(
compose_file_args(),
[
"-f",
"compose.yml",
"-f",
"compose/worktree.override.yml",
"-f",
"compose/cache.override.yml",
"-f",
"compose/cache.shared.override.yml",
],
)
@patch.dict(os.environ, {**_LOCAL_PRIMARY, "INFINITO_INSTANCE": "5"}, clear=False)
def test_a_stray_slot_alone_changes_nothing(self) -> None:
self.assertEqual(
compose_file_args(),
["-f", "compose.yml", "-f", "compose/cache.override.yml"],
)
@patch.dict(os.environ, {**_LOCAL_PRIMARY, "INFINITO_GIT_COMMON_DIR": "/repo/.git"})
def test_a_shared_git_dir_alone_adds_only_the_worktree_override(self) -> None:
self.assertEqual(
compose_file_args(),
[
"-f",
"compose.yml",
"-f",
"compose/worktree.override.yml",
"-f",
"compose/cache.override.yml",
],
)
@patch.dict(os.environ, {**_WORKTREE, "CI": "true"}, clear=False)
def test_ci_keeps_the_git_mount_but_drops_every_cache_override(self) -> None:
self.assertEqual(
compose_file_args(),
["-f", "compose.yml", "-f", "compose/worktree.override.yml"],
)
@patch.dict(os.environ, {**_LOCAL_PRIMARY, "CI": "true"}, clear=False)
def test_ci_loads_no_override_at_all(self) -> None:
self.assertEqual(compose_file_args(), ["-f", "compose.yml"])
@patch.dict(
os.environ,
{**_LOCAL_PRIMARY, "INFINITO_PUBLISH_PORTS": "false"},
clear=False,
)
def test_unpublished_ports_append_the_noports_override(self) -> None:
self.assertEqual(
compose_file_args()[-2:], ["-f", "compose/noports.override.yml"]
)
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,163 @@
from __future__ import annotations
import argparse
import os
import unittest
import unittest.mock
from cli.administration.deploy.development import exec as exec_cmd
def _args(
*,
distro: str = "debian",
cmd: list[str] | None = None,
env: list[str] | None = None,
) -> argparse.Namespace:
return argparse.Namespace(
distro=distro,
cmd=cmd if cmd is not None else [],
env=env if env is not None else [],
)
class TestDevelopmentExec(unittest.TestCase):
def test_handler_forwards_services_disabled(self):
compose = unittest.mock.Mock()
compose.exec.return_value.returncode = 0
with (
unittest.mock.patch(
"cli.administration.deploy.development.exec.make_compose",
return_value=compose,
),
unittest.mock.patch.dict(os.environ, {"disable": "email"}, clear=False),
):
rc = exec_cmd.handler(_args(cmd=["--", "sh", "-lc", "true"]))
self.assertEqual(rc, 0)
compose.exec.assert_called_once_with(
["sh", "-lc", "true"],
check=False,
extra_env={"disable": "email"},
)
def test_handler_omits_extra_env_when_services_disabled_unset(self):
compose = unittest.mock.Mock()
compose.exec.return_value.returncode = 0
env = {**os.environ, "disable": ""}
with (
unittest.mock.patch(
"cli.administration.deploy.development.exec.make_compose",
return_value=compose,
),
unittest.mock.patch.dict(os.environ, env, clear=True),
):
rc = exec_cmd.handler(_args(cmd=["echo", "hi"]))
self.assertEqual(rc, 0)
compose.exec.assert_called_once_with(
["echo", "hi"], check=False, extra_env=None
)
def test_handler_requires_command(self):
with self.assertRaises(SystemExit):
exec_cmd.handler(_args(cmd=[]))
def test_env_pairs_are_injected_into_extra_env(self):
compose = unittest.mock.Mock()
compose.exec.return_value.returncode = 0
env = {**os.environ, "disable": ""}
with (
unittest.mock.patch(
"cli.administration.deploy.development.exec.make_compose",
return_value=compose,
),
unittest.mock.patch.dict(os.environ, env, clear=True),
):
rc = exec_cmd.handler(
_args(
cmd=["bash", "/opt/helper.sh"],
env=[
"INFINITO_INVENTORY_FILE=/srv/inv/devices.yml",
"apps=web-app-foo",
],
)
)
self.assertEqual(rc, 0)
compose.exec.assert_called_once_with(
["bash", "/opt/helper.sh"],
check=False,
extra_env={
"INFINITO_INVENTORY_FILE": "/srv/inv/devices.yml",
"apps": "web-app-foo",
},
)
def test_env_pair_with_equals_in_value_is_preserved(self):
compose = unittest.mock.Mock()
compose.exec.return_value.returncode = 0
env = {**os.environ, "disable": ""}
with (
unittest.mock.patch(
"cli.administration.deploy.development.exec.make_compose",
return_value=compose,
),
unittest.mock.patch.dict(os.environ, env, clear=True),
):
exec_cmd.handler(_args(cmd=["true"], env=["EXTRA_VARS=a=1 b=2"]))
compose.exec.assert_called_once_with(
["true"],
check=False,
extra_env={"EXTRA_VARS": "a=1 b=2"},
)
def test_env_pair_overrides_implicit_services_disabled(self):
compose = unittest.mock.Mock()
compose.exec.return_value.returncode = 0
with (
unittest.mock.patch(
"cli.administration.deploy.development.exec.make_compose",
return_value=compose,
),
unittest.mock.patch.dict(os.environ, {"disable": "from-env"}, clear=False),
):
exec_cmd.handler(_args(cmd=["true"], env=["disable=from-cli"]))
compose.exec.assert_called_once_with(
["true"],
check=False,
extra_env={"disable": "from-cli"},
)
def test_env_pair_without_equals_is_rejected(self):
compose = unittest.mock.Mock()
with (
unittest.mock.patch(
"cli.administration.deploy.development.exec.make_compose",
return_value=compose,
),
self.assertRaisesRegex(SystemExit, "expects KEY=VALUE"),
):
exec_cmd.handler(_args(cmd=["true"], env=["BARE"]))
def test_env_pair_with_empty_key_is_rejected(self):
compose = unittest.mock.Mock()
with (
unittest.mock.patch(
"cli.administration.deploy.development.exec.make_compose",
return_value=compose,
),
self.assertRaisesRegex(SystemExit, "KEY is empty"),
):
exec_cmd.handler(_args(cmd=["true"], env=["=value"]))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,100 @@
"""Drift guard for the development inventory vars-file SPOT.
The literal path "inventories/development/default.yml" is exposed in
TWO places that must stay in lockstep:
* `default.env` — `INFINITO_INVENTORY_VARS_FILE` (SPOT-of-record for callers
that go through `make dotenv` / the bash deploy chain).
* `cli/administration/deploy/development/common.DEV_INVENTORY_VARS_FILE`
— fallback for direct/test invocations that bypass the bash chain.
If they ever drift, init.py and the shell deploy scripts would point at
different files and CI would silently start producing the wrong inventory.
This test parses the env file and asserts the Python constant matches.
"""
from __future__ import annotations
import re
import unittest
from pathlib import Path
from cli.administration.deploy.development.common import DEV_INVENTORY_VARS_FILE
from utils.cache.files import iter_project_files, read_text
from . import PROJECT_ROOT
STATIC_ENV = PROJECT_ROOT / "default.env"
def _parse_env_default(file_text: str) -> str:
pattern = re.compile(
r'^\s*INFINITO_INVENTORY_VARS_FILE=(?P<value>"[^"]*"|\'[^\']*\'|[^\s#]+)\s*(#.*)?$',
re.MULTILINE,
)
match = pattern.search(file_text)
if not match:
raise AssertionError(
"Could not find INFINITO_INVENTORY_VARS_FILE assignment in "
f"{STATIC_ENV}; pattern was tightened intentionally so any "
"rewrite of that line forces a matching update here."
)
value = match.group("value")
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
value = value[1:-1]
return value
class TestInventoryVarsFileSpotDriftGuard(unittest.TestCase):
def test_env_default_matches_python_fallback(self):
env_default = _parse_env_default(read_text(str(STATIC_ENV)))
self.assertEqual(
env_default,
DEV_INVENTORY_VARS_FILE,
"INFINITO_INVENTORY_VARS_FILE default in default.env drifted from "
"cli.administration.deploy.development.common.DEV_INVENTORY_VARS_FILE. "
"Update both literals (or, better, rebase one on the other).",
)
def test_no_other_caller_hardcodes_the_literal(self):
literal = "inventories/development/default.yml"
allowed_relative = {
"default.env",
"cli/administration/deploy/development/common.py",
Path(__file__).relative_to(PROJECT_ROOT).as_posix(),
"docs/administration/deploy.md",
"roles/web-app-odoo/tasks/03_oidc.yml",
"inventories/development/default.yml",
"tests/lint/filesystem/env/test_no_ansible_env_lookups.py",
}
offenders: list[str] = []
scan_extensions = (".py", ".sh", ".yml", ".yaml", ".j2", ".md")
for path_str in iter_project_files(extensions=scan_extensions):
path = Path(path_str)
try:
rel = path.relative_to(PROJECT_ROOT).as_posix()
except ValueError:
continue
if rel in allowed_relative:
continue
if any(rel.startswith(prefix + "/") for prefix in (".mypy_cache",)):
continue
if rel.startswith("docs/requirements/"):
continue
try:
text = read_text(path_str)
except (OSError, UnicodeDecodeError):
continue
if literal in text:
offenders.append(rel)
self.assertFalse(
offenders,
"The development inventory vars-file path is hardcoded in "
"files outside the SPOT whitelist; either route them through "
"the SPOT or extend the whitelist with a justification: "
f"{offenders}",
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,610 @@
"""Unit tests for the deploy-side matrix iteration: each round deploys its own
variant-closure (``include``); between rounds the wrapper wipes the union
(``purge_set``).
deploy.handler reads the running container name strictly via
cli.administration.deploy.development.common.resolve_container (which is
sourced from scripts/meta/env/load.sh, the single SPOT for the formula).
That resolver is patched for the whole test module instead of duplicating
the formula or hard-coding INFINITO_CONTAINER in os.environ. The tests
below do not assert on the returned value; the sentinel is purely an
opaque fixture string.
"""
from __future__ import annotations
import argparse
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
_RESOLVE_CONTAINER_PATCHER = patch(
"cli.administration.deploy.development.deploy.cli.resolve_container",
return_value="<unit-test fixture>",
)
_RESOLVE_CONTAINER_PATCHER.start()
from cli.administration.deploy.development.deploy import handler # noqa: E402
def _args(
*,
apps: list[str] | None = None,
variant: list[int] | None = None,
full_cycle: bool = False,
) -> argparse.Namespace:
"""Namespace fixture for handler(). `distro` is intentionally absent:
deploy.handler no longer consumes it (the --distro arg was retired in
favour of resolve_distro() reading INFINITO_DISTRO env strictly)."""
return argparse.Namespace(
inventory_dir="/srv/inv",
apps=None,
id=apps,
debug=False,
variant=variant,
full_cycle=full_cycle,
ansible_args=[],
)
def _entry(
round_index: int,
inv_dir: str,
round_variants: dict[str, int],
include: tuple[str, ...] | None = None,
purge_set: tuple[str, ...] | None = None,
) -> tuple[int, str, dict[str, int], tuple[str, ...], tuple[str, ...]]:
"""5-tuple plan entry. Defaults: include=round_variants.keys(), purge_set=include — pass purge_set explicitly when round closures differ."""
if include is None:
include = tuple(round_variants.keys())
if purge_set is None:
purge_set = include
return (round_index, inv_dir, round_variants, include, purge_set)
def _make_compose_mock() -> MagicMock:
compose = MagicMock()
compose.repo_root = Path("/tmp/infinito-nexus")
return compose
class TestHandlerMatrixDeploy(unittest.TestCase):
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_single_round_skips_matrix_loop(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""Single deploy against the unsuffixed folder, no cleanup."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv", {"web-app-jira": 0, "web-app-keycloak": 0}),
]
run_deploy_mock.return_value = 0
rc = handler(_args(apps=["web-app-jira", "web-app-keycloak"]))
self.assertEqual(rc, 0)
run_deploy_mock.assert_called_once()
self.assertEqual(run_deploy_mock.call_args.kwargs["inventory_dir"], "/srv/inv")
purge_mock.assert_not_called()
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_every_round_redeploys_full_include_after_purge(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""Variant 0 covers BOTH apps, variant 1 only exists for WordPress.
Each round starts from a clean host (the previous round's full
include is purged), so round 1 redeploys the full round-1 include,
Keycloak included even though it stays on variant 0, because the
round-0 baseline was just purged away. Purge runs once between
rounds with the FULL previous round include, not just
variant-changed apps."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-wordpress": 0, "web-app-keycloak": 0}),
_entry(1, "/srv/inv-1", {"web-app-wordpress": 1, "web-app-keycloak": 0}),
]
run_deploy_mock.return_value = 0
rc = handler(_args(apps=["web-app-wordpress", "web-app-keycloak"]))
self.assertEqual(rc, 0)
self.assertEqual(run_deploy_mock.call_count, 2)
round_one_deploy_ids = run_deploy_mock.call_args_list[1].kwargs["deploy_ids"]
self.assertEqual(
sorted(round_one_deploy_ids),
["web-app-keycloak", "web-app-wordpress"],
)
purge_mock.assert_called_once()
self.assertEqual(
sorted(purge_mock.call_args.kwargs["app_ids"]),
["web-app-keycloak", "web-app-wordpress"],
)
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_two_round_plan_deploys_each_folder_in_order(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""Between rounds the FULL previous-round include is purged so
round 1 starts from a clean host, keycloak too, even though it
stays on variant 0."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0, "web-app-keycloak": 0}),
_entry(1, "/srv/inv-1", {"web-app-multi": 1, "web-app-keycloak": 0}),
]
run_deploy_mock.return_value = 0
rc = handler(_args(apps=["web-app-multi", "web-app-keycloak"]))
self.assertEqual(rc, 0)
self.assertEqual(run_deploy_mock.call_count, 2)
self.assertEqual(
[c.kwargs["inventory_dir"] for c in run_deploy_mock.call_args_list],
["/srv/inv-0", "/srv/inv-1"],
)
purge_mock.assert_called_once()
self.assertEqual(
sorted(purge_mock.call_args.kwargs["app_ids"]),
["web-app-keycloak", "web-app-multi"],
)
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_three_round_plan_redeploys_full_include_each_round(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""WordPress 2 variants, Discourse 3 variants, Keycloak 1 variant.
Each round starts from a clean host (full-include purge) and
therefore redeploys ITS OWN full include, keycloak too, even
though it has no later variants. Purge runs between rounds with
the FULL previous-round include."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(
0,
"/srv/inv-0",
{"web-app-wordpress": 0, "web-app-discourse": 0, "web-app-keycloak": 0},
),
_entry(
1,
"/srv/inv-1",
{"web-app-wordpress": 1, "web-app-discourse": 1, "web-app-keycloak": 0},
),
_entry(
2,
"/srv/inv-2",
{"web-app-wordpress": 0, "web-app-discourse": 2, "web-app-keycloak": 0},
),
]
run_deploy_mock.return_value = 0
rc = handler(
_args(
apps=[
"web-app-wordpress",
"web-app-discourse",
"web-app-keycloak",
]
)
)
self.assertEqual(rc, 0)
self.assertEqual(run_deploy_mock.call_count, 3)
full_include = ["web-app-discourse", "web-app-keycloak", "web-app-wordpress"]
per_round_deploy_ids = [
sorted(c.kwargs["deploy_ids"]) for c in run_deploy_mock.call_args_list
]
for round_index, deploy_ids in enumerate(per_round_deploy_ids):
self.assertEqual(
deploy_ids, full_include, f"round {round_index} deploy_ids drifted"
)
self.assertEqual(purge_mock.call_count, 2)
for call in purge_mock.call_args_list:
self.assertEqual(sorted(call.kwargs["app_ids"]), full_include)
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_round_transition_purges_union_when_variant_closures_differ(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""Round 1 must deploy only its own closure (no coturn), yet the
inter-round purge must wipe the union (coturn included)."""
make_compose_mock.return_value = _make_compose_mock()
union = ("web-app-nextcloud", "web-svc-coturn")
plan_mock.return_value = [
_entry(
0,
"/srv/inv-0",
{"web-app-nextcloud": 0},
include=("web-app-nextcloud", "web-svc-coturn"),
purge_set=union,
),
_entry(
1,
"/srv/inv-1",
{"web-app-nextcloud": 1},
include=("web-app-nextcloud",),
purge_set=union,
),
]
run_deploy_mock.return_value = 0
rc = handler(_args(apps=["web-app-nextcloud"]))
self.assertEqual(rc, 0)
self.assertEqual(run_deploy_mock.call_count, 2)
round_zero_deploy_ids = run_deploy_mock.call_args_list[0].kwargs["deploy_ids"]
round_one_deploy_ids = run_deploy_mock.call_args_list[1].kwargs["deploy_ids"]
self.assertEqual(
sorted(round_zero_deploy_ids),
["web-app-nextcloud", "web-svc-coturn"],
)
self.assertEqual(round_one_deploy_ids, ["web-app-nextcloud"])
purge_mock.assert_called_once()
self.assertEqual(
sorted(purge_mock.call_args.kwargs["app_ids"]),
["web-app-nextcloud", "web-svc-coturn"],
)
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_failure_in_round_one_aborts_before_round_two(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""Round 1 ran and failed, round 2 must NOT have been attempted."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0}),
_entry(1, "/srv/inv-1", {"web-app-multi": 1}),
]
run_deploy_mock.return_value = 17
rc = handler(_args(apps=["web-app-multi"]))
self.assertEqual(rc, 17)
run_deploy_mock.assert_called_once()
purge_mock.assert_not_called()
class TestHandlerVariantPin(unittest.TestCase):
"""`--variant <idx>` (or variant env-var) pins the deploy to one
specific round's folder, skipping inter-round cleanup. Use case:
redeploying one variant without iterating the whole matrix."""
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_variant_one_runs_only_that_round_no_cleanup(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""Only the picked round runs; no cleanup because there is no
previous round to diff against in single-round mode."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0}),
_entry(1, "/srv/inv-1", {"web-app-multi": 1}),
]
run_deploy_mock.return_value = 0
rc = handler(_args(apps=["web-app-multi"], variant=[1]))
self.assertEqual(rc, 0)
run_deploy_mock.assert_called_once()
self.assertEqual(
run_deploy_mock.call_args.kwargs["inventory_dir"], "/srv/inv-1"
)
purge_mock.assert_not_called()
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_variant_out_of_range_exits_with_clean_message(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
_purge_mock: MagicMock,
) -> None:
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0}),
_entry(1, "/srv/inv-1", {"web-app-multi": 1}),
]
with self.assertRaisesRegex(SystemExit, r"variants \[7\] out of range"):
handler(_args(apps=["web-app-multi"], variant=[7]))
run_deploy_mock.assert_not_called()
class TestHandlerFullCycle(unittest.TestCase):
"""`--full-cycle` runs an async re-deploy IMMEDIATELY after each
round's sync deploy (Pass 2 stays co-located with Pass 1 on the
same variant). Without `--full-cycle` only Pass 1 runs per round."""
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_full_cycle_runs_pass2_after_each_round(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
"""Two rounds, two passes each = 4 deploy calls, per-variant
interleave: round-0 sync, round-0 async, then round-1 sync,
round-1 async. Every call carries the zero-based VARIANT_INDEX so
consumers like the test-e2e-playwright role can namespace their
artifacts, plus PRIMARY_APPS so role-owned tests can tell a deploy
target from a pulled-in dependency. Cleanup still runs once between
rounds with the full previous-round include."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0}),
_entry(1, "/srv/inv-1", {"web-app-multi": 1}),
]
run_deploy_mock.return_value = 0
rc = handler(_args(apps=["web-app-multi"], full_cycle=True))
self.assertEqual(rc, 0)
self.assertEqual(run_deploy_mock.call_count, 4)
sequence = [
(call.kwargs["inventory_dir"], call.kwargs.get("extra_ansible_vars"))
for call in run_deploy_mock.call_args_list
]
self.assertEqual(
sequence,
[
("/srv/inv-0", {"VARIANT_INDEX": 0, "PRIMARY_APPS": ["web-app-multi"]}),
(
"/srv/inv-0",
{
"ASYNC_ENABLED": True,
"VARIANT_INDEX": 0,
"PRIMARY_APPS": ["web-app-multi"],
},
),
("/srv/inv-1", {"VARIANT_INDEX": 1, "PRIMARY_APPS": ["web-app-multi"]}),
(
"/srv/inv-1",
{
"ASYNC_ENABLED": True,
"VARIANT_INDEX": 1,
"PRIMARY_APPS": ["web-app-multi"],
},
),
],
)
purge_mock.assert_called_once()
self.assertEqual(purge_mock.call_args.kwargs["app_ids"], ["web-app-multi"])
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_full_cycle_aborts_when_pass1_fails_skipping_pass2(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
_purge_mock: MagicMock,
) -> None:
"""PASS 1 of round 0 fails. PASS 2 of round 0 and the entire round
1 must be skipped to surface the failure cleanly."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0}),
_entry(1, "/srv/inv-1", {"web-app-multi": 1}),
]
run_deploy_mock.return_value = 11
rc = handler(_args(apps=["web-app-multi"], full_cycle=True))
self.assertEqual(rc, 11)
run_deploy_mock.assert_called_once()
@patch(
"cli.administration.deploy.development.deploy.cli._purge_app_entities",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli._run_deploy", autospec=True
)
@patch(
"cli.administration.deploy.development.deploy.cli.plan_dev_inventory_matrix",
autospec=True,
)
@patch(
"cli.administration.deploy.development.deploy.cli.make_compose", autospec=True
)
def test_full_cycle_with_variant_pin_runs_only_one_round_with_both_passes(
self,
make_compose_mock: MagicMock,
plan_mock: MagicMock,
run_deploy_mock: MagicMock,
purge_mock: MagicMock,
) -> None:
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0}),
_entry(1, "/srv/inv-1", {"web-app-multi": 1}),
]
run_deploy_mock.return_value = 0
rc = handler(_args(apps=["web-app-multi"], variant=[1], full_cycle=True))
self.assertEqual(rc, 0)
self.assertEqual(run_deploy_mock.call_count, 2)
sequence = [
(call.kwargs["inventory_dir"], call.kwargs.get("extra_ansible_vars"))
for call in run_deploy_mock.call_args_list
]
self.assertEqual(
sequence,
[
("/srv/inv-1", {"VARIANT_INDEX": 1, "PRIMARY_APPS": ["web-app-multi"]}),
(
"/srv/inv-1",
{
"ASYNC_ENABLED": True,
"VARIANT_INDEX": 1,
"PRIMARY_APPS": ["web-app-multi"],
},
),
],
)
purge_mock.assert_not_called()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,46 @@
from __future__ import annotations
import unittest
from unittest.mock import MagicMock, patch
from cli.administration.deploy.development.mirrors import generate_ci_mirrors_file
class TestGenerateCiMirrorsFile(unittest.TestCase):
@patch.dict(
"os.environ",
{
"INFINITO_RUNNING_ON_GITHUB": "true",
"GITHUB_REPOSITORY_OWNER": "kevinveenbirkenbach",
"GITHUB_REPOSITORY": "kevinveenbirkenbach/infinito-nexus",
"INFINITO_GHCR_MIRROR_PREFIX": "mirror",
},
clear=False,
)
def test_uses_container_python_from_env_with_fallback(self) -> None:
compose = MagicMock()
out = generate_ci_mirrors_file(compose, inventory_dir="/tmp/inventory")
self.assertEqual(out, "/tmp/inventory/mirrors.yml")
compose.exec.assert_called_once()
called_cmd = compose.exec.call_args.args[0]
self.assertEqual(called_cmd[0:2], ["bash", "-lc"])
self.assertIn(
'"${PYTHON:-python3}" -m cli.contributing.mirror.resolver', called_cmd[2]
)
self.assertNotIn("python3 -m cli.contributing.mirror.resolver", called_cmd[2])
@patch.dict("os.environ", {}, clear=True)
def test_raises_on_missing_required_env(self) -> None:
compose = MagicMock()
with self.assertRaises(RuntimeError):
generate_ci_mirrors_file(compose, inventory_dir="/tmp/inventory")
compose.exec.assert_not_called()
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,47 @@
from __future__ import annotations
import os
import unittest
from unittest.mock import MagicMock, patch
from cli.administration.deploy.development.network import detect_outer_network_mtu
class TestDetectOuterNetworkMtu(unittest.TestCase):
@patch.dict(os.environ, {"INFINITO_OUTER_NETWORK_MTU": "1300"}, clear=False)
def test_prefers_explicit_outer_network_mtu_env(self) -> None:
self.assertEqual(detect_outer_network_mtu(), "1300")
@patch.dict(os.environ, {"INFINITO_OUTER_NETWORK_MTU": ""}, clear=True)
@patch("cli.administration.deploy.development.network.Path.exists", autospec=True)
@patch(
"cli.administration.deploy.development.network.Path.read_text", autospec=True
)
def test_reads_outer_network_mtu_from_host_docker_daemon(
self,
read_text_mock: MagicMock,
exists_mock: MagicMock,
) -> None:
exists_mock.side_effect = lambda path: str(path) == "/etc/docker/daemon.json"
read_text_mock.return_value = '{"mtu": 1400}'
self.assertEqual(detect_outer_network_mtu(), "1400")
@patch.dict(os.environ, {"INFINITO_OUTER_NETWORK_MTU": ""}, clear=True)
@patch("cli.administration.deploy.development.network.Path.exists", autospec=True)
@patch(
"cli.administration.deploy.development.network.Path.read_text", autospec=True
)
def test_ignores_invalid_daemon_config(
self,
read_text_mock: MagicMock,
exists_mock: MagicMock,
) -> None:
exists_mock.side_effect = lambda path: str(path) == "/etc/docker/daemon.json"
read_text_mock.return_value = '{"mtu": 64}'
self.assertIsNone(detect_outer_network_mtu())
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,156 @@
"""Unit tests for Profile."""
from __future__ import annotations
import os
import unittest
from unittest.mock import patch
from cli.administration.deploy.development.profile import Profile
_BLANK_CI_ENV = {
"GITHUB_ACTIONS": "",
"INFINITO_RUNNING_ON_GITHUB": "",
"CI": "",
"INFINITO_INSTANCE": "0",
"INFINITO_GIT_COMMON_DIR": "",
"INFINITO_CACHE_NETWORK": "",
"INFINITO_CACHE_STACK": "",
}
class TestProfileIsCI(unittest.TestCase):
@patch.dict(os.environ, _BLANK_CI_ENV, clear=False)
def test_is_ci_false_when_no_signals_set(self) -> None:
self.assertFalse(Profile().is_ci())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "GITHUB_ACTIONS": "true"}, clear=False)
def test_is_ci_true_when_github_actions_signal_set(self) -> None:
self.assertTrue(Profile().is_ci())
@patch.dict(
os.environ, {**_BLANK_CI_ENV, "INFINITO_RUNNING_ON_GITHUB": "true"}, clear=False
)
def test_is_ci_true_when_running_on_github_signal_set(self) -> None:
self.assertTrue(Profile().is_ci())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "CI": "true"}, clear=False)
def test_is_ci_true_when_generic_ci_signal_set(self) -> None:
self.assertTrue(Profile().is_ci())
@patch.dict(
os.environ,
{**_BLANK_CI_ENV, "GITHUB_ACTIONS": "1"},
clear=False,
)
def test_is_ci_false_when_signal_value_is_one(self) -> None:
self.assertFalse(Profile().is_ci())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "GITHUB_ACTIONS": "false"}, clear=False)
def test_is_ci_false_when_signal_value_is_explicit_false(self) -> None:
self.assertFalse(Profile().is_ci())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "GITHUB_ACTIONS": "yes"}, clear=False)
def test_is_ci_false_when_signal_value_is_yes(self) -> None:
self.assertFalse(Profile().is_ci())
class TestProfileCacheStackEnabled(unittest.TestCase):
@patch.dict(os.environ, _BLANK_CI_ENV, clear=False)
def test_active_locally_when_no_ci_signal_set(self) -> None:
self.assertTrue(Profile().cache_stack_enabled())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "GITHUB_ACTIONS": "true"}, clear=False)
def test_inactive_under_github_actions(self) -> None:
self.assertFalse(Profile().cache_stack_enabled())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "CI": "true"}, clear=False)
def test_inactive_under_generic_ci_signal(self) -> None:
self.assertFalse(Profile().cache_stack_enabled())
@patch.dict(
os.environ, {**_BLANK_CI_ENV, "INFINITO_RUNNING_ON_GITHUB": "true"}, clear=False
)
def test_defaults_to_the_inverse_of_is_ci(self) -> None:
p = Profile()
self.assertEqual(p.cache_stack_enabled(), not p.is_ci())
_ON_CI = {**_BLANK_CI_ENV, "GITHUB_ACTIONS": "true"}
class TestProfileDeclaredCapabilities(unittest.TestCase):
@patch.dict(os.environ, {**_ON_CI, "INFINITO_CACHE_STACK": "true"}, clear=False)
def test_declaration_wins_over_the_ci_default(self) -> None:
p = Profile()
self.assertTrue(p.is_ci())
self.assertTrue(p.cache_stack_enabled())
@patch.dict(os.environ, {**_ON_CI, "INFINITO_CACHE_STACK": "yes"}, clear=False)
def test_a_non_boolean_declaration_falls_back_to_the_default(self) -> None:
self.assertFalse(Profile().cache_stack_enabled())
@patch.dict(os.environ, _ON_CI, clear=False)
def test_act_gets_no_mirrors_and_keeps_its_docker_root(self) -> None:
p = Profile()
self.assertTrue(p.is_ci())
self.assertFalse(p.runs_on_github())
self.assertFalse(p.cache_stack_enabled())
self.assertFalse(p.image_mirror_enabled())
self.assertFalse(p.docker_root_ephemeral())
@patch.dict(
os.environ,
{**_BLANK_CI_ENV, "INFINITO_RUNNING_ON_GITHUB": "true"},
clear=False,
)
def test_a_real_github_runner_mirrors_and_wipes(self) -> None:
p = Profile()
self.assertTrue(p.runs_on_github())
self.assertFalse(p.cache_stack_enabled())
self.assertTrue(p.image_mirror_enabled())
self.assertTrue(p.docker_root_ephemeral())
class TestProfileInstance(unittest.TestCase):
@patch.dict(os.environ, {**_BLANK_CI_ENV, "INFINITO_INSTANCE": ""}, clear=False)
def test_unset_instance_is_primary(self) -> None:
self.assertEqual(Profile().instance(), 0)
@patch.dict(os.environ, {**_BLANK_CI_ENV, "INFINITO_INSTANCE": "7"}, clear=False)
def test_numeric_instance_is_parsed(self) -> None:
self.assertEqual(Profile().instance(), 7)
@patch.dict(os.environ, {**_BLANK_CI_ENV, "INFINITO_INSTANCE": " 3 "}, clear=False)
def test_surrounding_whitespace_is_tolerated(self) -> None:
self.assertEqual(Profile().instance(), 3)
@patch.dict(os.environ, {**_BLANK_CI_ENV, "INFINITO_INSTANCE": "abc"}, clear=False)
def test_garbage_falls_back_to_primary(self) -> None:
self.assertEqual(Profile().instance(), 0)
class TestProfileOwnsCacheStack(unittest.TestCase):
@patch.dict(os.environ, _BLANK_CI_ENV, clear=False)
def test_owns_the_stack_when_no_network_was_handed_over(self) -> None:
self.assertTrue(Profile().owns_cache_stack())
@patch.dict(
os.environ, {**_BLANK_CI_ENV, "INFINITO_CACHE_NETWORK": "primary_default"}
)
def test_shares_instead_of_owning_when_a_network_is_named(self) -> None:
p = Profile()
self.assertFalse(p.owns_cache_stack())
self.assertTrue(p.cache_stack_enabled())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "INFINITO_INSTANCE": "7"}, clear=False)
def test_a_stray_slot_alone_does_not_give_the_stack_away(self) -> None:
self.assertTrue(Profile().owns_cache_stack())
@patch.dict(os.environ, {**_BLANK_CI_ENV, "CI": "true"}, clear=False)
def test_ci_never_owns_the_stack(self) -> None:
self.assertFalse(Profile().owns_cache_stack())
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,71 @@
"""Unit tests for the shared variant-selection helpers."""
from __future__ import annotations
import argparse
import os
import unittest
from typing import ClassVar
from unittest.mock import patch
from cli.administration.deploy.development import variant_select as vs
class TestParseVariantCsv(unittest.TestCase):
def test_parses_and_drops_blank_tokens(self) -> None:
self.assertEqual(vs.parse_variant_csv("0,1,2"), [0, 1, 2])
self.assertEqual(vs.parse_variant_csv(" 3 , 4 "), [3, 4])
self.assertEqual(vs.parse_variant_csv("2"), [2])
self.assertEqual(vs.parse_variant_csv(""), [])
self.assertEqual(vs.parse_variant_csv(","), [])
def test_non_integer_raises_argument_type_error(self) -> None:
with self.assertRaises(argparse.ArgumentTypeError):
vs.parse_variant_csv("0,x")
class TestEnvVariant(unittest.TestCase):
def test_single_and_csv(self) -> None:
with patch.dict(os.environ, {"variant": "2"}):
self.assertEqual(vs.env_variant(), [2])
with patch.dict(os.environ, {"variant": "0,1,2"}):
self.assertEqual(vs.env_variant(), [0, 1, 2])
def test_blank_is_none(self) -> None:
with patch.dict(os.environ, {"variant": ""}):
self.assertIsNone(vs.env_variant())
with patch.dict(os.environ, {"variant": " "}):
self.assertIsNone(vs.env_variant())
def test_bad_value_exits(self) -> None:
with patch.dict(os.environ, {"variant": "0,x"}), self.assertRaises(SystemExit):
vs.env_variant()
class TestApplyVariantFilter(unittest.TestCase):
PLAN: ClassVar[list[tuple]] = [(i, f"inv-{i}", {}, (), ()) for i in range(5)]
def _args(self, *, variant=None) -> argparse.Namespace:
return argparse.Namespace(variant=variant)
def test_none_returns_full_plan(self) -> None:
self.assertEqual(vs.apply_variant_filter(self.PLAN, self._args()), self.PLAN)
def test_single_index_pins_one_round(self) -> None:
out = vs.apply_variant_filter(self.PLAN, self._args(variant=[1]))
self.assertEqual([e[0] for e in out], [1])
def test_subset_keeps_listed_rounds(self) -> None:
self.assertEqual(
vs.apply_variant_filter(self.PLAN, self._args(variant=[3, 4])),
self.PLAN[3:],
)
def test_empty_list_falls_back_to_full_matrix(self) -> None:
self.assertEqual(
vs.apply_variant_filter(self.PLAN, self._args(variant=[])), self.PLAN
)
if __name__ == "__main__":
unittest.main()