Files
nixos-core/tests/unit/test_appctl_engine.py
T

487 lines
15 KiB
Python

from dataclasses import dataclass
from pathlib import Path
from unittest.mock import MagicMock
import appctl_engine as engine
import pytest
# Import appctl engine
# CORE_ROOT = Path(__file__).resolve().parent.parent.parent
# sys.path.insert(0, str(CORE_ROOT / "scripts"))
@dataclass
class AppFactory:
"""Helper class to generate mock app directories and configurations"""
sites_dir: Path
def create(
self,
dir_name: str,
manifest_yaml: str = "",
has_compose: bool = True,
) -> Path:
app_dir: Path = self.sites_dir / dir_name
app_dir.mkdir(parents=True, exist_ok=True)
if manifest_yaml:
(app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8")
if has_compose:
(app_dir / "docker-compose.yml").write_text(
"services: {}\n", encoding="utf-8"
)
return app_dir
@pytest.fixture
def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it"""
sites = tmp_path / "Sites"
monkeypatch.setattr(engine, "SITES_DIR", str(sites))
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test")
return sites
@pytest.fixture
def app_factory(mock_sites_dir: Path) -> AppFactory:
"""Fixture that provides the AppFactory instance to test"""
return AppFactory(mock_sites_dir)
@pytest.fixture
def mock_core_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Fixture that creates an isolated Core directory and points engine.CORE_DIR to it"""
core = tmp_path / "CORE"
core.mkdir(parents=True, exist_ok=True)
return core
## GREEN TEST: Existing implementation should not break
def test_resolve_app_hierarchy(app_factory: AppFactory):
"""Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix"""
app_factory.create(
dir_name="homelab-jellyfin",
manifest_yaml="""
name: media-server
aliases:
- movies
""",
)
apps = engine.get_sites_apps()
assert engine.resolve_app("media-server", apps) is not None
assert engine.resolve_app("movies", apps) is not None
assert engine.resolve_app("homelab-jellyfin", apps) is not None
assert engine.resolve_app("unknown", apps) is None
def test_manifest_data_overrides_default_values(app_factory: AppFactory):
"""Ensure app.yaml values successfully override the system defaults"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: custom-app
domain: custom.roadtotech.local
auth: false
visible: false
networks:
- custom-net
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("custom-app", apps)
assert app is not None
assert app.domain == "custom.roadtotech.local"
assert app.auth is False
assert app.networks == ["custom-net"]
def test_sites_app_normalization(app_factory: AppFactory):
"""Ensure missing or badly typed manifest fields are safely normalized"""
app_factory.create(
dir_name="homelab-custom",
manifest_yaml="""
name: testapp
# Missing domain - should fallback to <name>.<HOMELAB_DOMAIN>
aliases: single-string-alias # should become a list[str]
auth: "False" # should evaluate based on boolean casting
homepage:
weight: "99" # this should be casted as an int
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("testapp", apps)
assert app is not None
assert app.name == "testapp"
assert app.domain == "testapp.mydomain.test"
assert app.aliases == ["single-string-alias"]
assert app.auth is True
assert app.homepage is not None
assert app.homepage.weight == 99
def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
"""Ensure source provenance block is correctly parsed into SourceConfig"""
# 1. Source-backed app with explicit ref
app_factory.create(
dir_name="homelab-bitetrack",
manifest_yaml="""
name: bitetrack
source:
type: git
url: https://git.example.com/operator/bitetrack.git
ref: v1.2.0
""",
)
# 2. Source-backed app with default ref (main)
app_factory.create(
dir_name="homelab-doc2site",
manifest_yaml="""
name: doc2site
source:
url: https://git.example.com/operator/doc2site.git
""",
)
# 3. Image-only app (no source block)
app_factory.create(
dir_name="homelab-jellyfin",
manifest_yaml="""
name: jellyfin
""",
)
apps = engine.get_sites_apps()
bitetrack = engine.resolve_app("bitetrack", apps)
assert bitetrack is not None
assert bitetrack.source is not None
assert bitetrack.source.type == "git"
assert bitetrack.source.url == "https://git.example.com/operator/bitetrack.git"
assert bitetrack.source.ref == "v1.2.0"
assert bitetrack.to_dict()["source"]["ref"] == "v1.2.0"
doc2site = engine.resolve_app("doc2site", apps)
assert doc2site is not None
assert doc2site.source is not None
assert doc2site.source.ref == "main"
jellyfin = engine.resolve_app("jellyfin", apps)
assert jellyfin is not None
assert jellyfin.source is None
assert jellyfin.to_dict()["source"] is None
# 4. App with illegal source transport (e.g. file://)
app_factory.create(
dir_name="homelab-malformed",
manifest_yaml="""
name: malformed
source:
url: file:///etc/passwd
""",
)
apps_updated = engine.get_sites_apps()
malformed = engine.resolve_app("malformed", apps_updated)
assert malformed is not None
assert malformed.source is None
assert malformed.manifest_error is not None
assert "Invalid source.url scheme" in malformed.manifest_error
## RED TESTS: TDD Goals for next implementation
def test_docker_status_parser_running(monkeypatch):
"""Ensure get_docker_status reports running compose stack when all containers are running."""
def mock_run(args, **kwargs):
mock = MagicMock()
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "true\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🟢 Running (1)"
def test_docker_status_parser_stopped(monkeypatch):
"""Ensure get_docker_status reports stopped when no containers exist."""
def mock_run(args, **kwargs):
mock = MagicMock()
if "ps" in args:
mock.stdout = ""
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🔴 Stopped"
def test_docker_status_parser_degraded(monkeypatch):
"""Ensure get_docker_status reports degraded when partial containers are running."""
def mock_run(args, **kwargs):
mock = MagicMock()
if "ps" in args:
mock.stdout = "c1\nc2\n"
if "inspect" in args:
mock.stdout = "true\nfalse\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
status = engine.get_docker_status("/fake/dir")
assert status == "🟡 Degraded (1/2)"
def test_docker_status_parser_not_stack(tmp_path: Path):
"""Ensure get_docker_status reports Not Stack for real directory without compose file."""
empty_dir = tmp_path / "empty_service"
empty_dir.mkdir()
assert engine.get_docker_status(empty_dir) == "⚪ Not Stack"
def test_docker_status_single_container(monkeypatch):
"""Ensure get_docker_status inspects single Core container by name."""
def mock_run(args, **kwargs):
mock = MagicMock()
if "authelia" in args:
mock.stdout = "true\n"
else:
mock.stdout = "false\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("", container_name="authelia") == "🟢 Running (1)"
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
def test_docker_status_error_handling(monkeypatch):
"""Ensure get_docker_status handles subprocess failures gracefully."""
def mock_err(*args, **kwargs):
raise OSError("Docker socket unreachable")
monkeypatch.setattr("subprocess.run", mock_err)
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
def test_docker_image_revision_extraction(monkeypatch):
"""Ensure get_docker_image_revision extracts org.opencontainers.image.revision."""
def mock_run(args, **kwargs):
mock = MagicMock()
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "9d82577f489f0d478e465a36077538d0ded16ba5\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run)
assert (
engine.get_docker_image_revision("/fake/dir")
== "9d82577f489f0d478e465a36077538d0ded16ba5"
)
def mock_run_empty(args, **kwargs):
mock = MagicMock()
if "ps" in args:
mock.stdout = "container123\n"
if "inspect" in args:
mock.stdout = "<no value>\n"
return mock
monkeypatch.setattr("subprocess.run", mock_run_empty)
assert engine.get_docker_image_revision("/fake/dir") is None
def test_homepage_sync_groups_and_sorts_correctly(
mock_core_dir: Path, app_factory: AppFactory, monkeypatch
):
"""
TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure.
It must group by `homepage.group` and sort by `homepage.weight`.
"""
hp_config_dir = mock_core_dir / "config" / "homepage"
hp_config_dir.mkdir(parents=True, exist_ok=True)
app_factory.create(
dir_name="homelab-app1",
manifest_yaml="""
name: App1
domain: app1.local.test
homepage:
title: App1
group: Group B
weight: 20
""",
)
app_factory.create(
dir_name="homelab-app2",
manifest_yaml="""
name: App2
domain: app2.local.test
homepage:
title: App2
group: Group A
weight: 10
""",
)
monkeypatch.setattr(engine, "get_core_services", list)
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
output_file = hp_config_dir / "services.yaml"
assert output_file.exists(), "The services.yaml file must be generated"
content = output_file.read_text()
assert content.find("- Group A") < content.find(
"- Group B"
) # Group A should appear before Group B
assert "App2" in content # App 2 is in the file
def test_homepage_sync_core_services_domain_isolation(
mock_core_dir: Path,
monkeypatch,
):
"""
Ensure Core Infrastructure services use HOMELAB_DOMAIN and do not leak
an application's domain if DOMAIN is overridden by appctl.
"""
hp_config_dir = mock_core_dir / "config" / "homepage"
hp_config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "example.com")
monkeypatch.setenv("DOMAIN", "mermaid.example.com")
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
output_file = hp_config_dir / "services.yaml"
assert output_file.exists()
content = output_file.read_text()
assert "https://dashboard.example.com" in content
assert "https://traefik.example.com" in content
assert "https://auth.example.com" in content
assert "mermaid.example.com" not in content
def test_resolve_core_stack_type():
"""
Ensure resolving 'core' returns app_type='core' (entire stack),
while individual core services return app_type='core_service'.
"""
core = engine.resolve_app("core")
assert core is not None
assert core.to_dict()["type"] == "core"
assert core.container == ""
traefik = engine.resolve_app("traefik")
assert traefik is not None
assert traefik.to_dict()["type"] == "core_service"
assert traefik.container == "traefik"
def test_manifest_parsing_delegates_to_core_manifest_and_validates_env(
app_factory: AppFactory,
):
"""Ensure manifest parsing uses core_manifest and catches invalid env keys."""
app_factory.create(
dir_name="homelab-badenv",
manifest_yaml="""
name: badenv
env:
PATH: /override/bin
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("badenv", apps)
assert app is not None
assert app.manifest_error is not None
assert "Invalid or reserved environment variable key" in app.manifest_error
def test_cmd_resolve_fails_closed_on_manifest_error(
app_factory: AppFactory, capsys: pytest.CaptureFixture
):
"""Ensure cmd_resolve exits with non-zero on workload with manifest errors."""
app_factory.create(
dir_name="homelab-corrupt",
manifest_yaml="""
name: corrupt
env:
ILLEGAL-KEY: forbidden
""",
)
with pytest.raises(SystemExit) as exc_info:
engine.cmd_resolve(["corrupt"])
assert exc_info.value.code != 0
captured = capsys.readouterr()
assert "invalid manifest" in captured.err.lower() or "error" in captured.err.lower()
def test_cmd_resolve_fails_closed_on_missing_app_yaml(mock_sites_dir: Path):
"""Ensure cmd_resolve exits with non-zero if workload has no app.yaml."""
no_manifest_dir = mock_sites_dir / "homelab-nomanifest"
no_manifest_dir.mkdir(parents=True, exist_ok=True)
with pytest.raises(SystemExit) as exc_info:
engine.cmd_resolve(["nomanifest"])
assert exc_info.value.code != 0
def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
"""Ensure SitesApp uses core_manifest SourceConfig and HomepageConfig."""
import core_manifest
app_factory.create(
dir_name="homelab-unified",
manifest_yaml="""
name: unified
source:
url: https://git.example.com/operator/unified.git
ref: v1.0.0
homepage:
title: Unified App
weight: 30
""",
)
apps = engine.get_sites_apps()
app = engine.resolve_app("unified", apps)
assert app is not None
assert isinstance(app.source, core_manifest.SourceConfig)
assert isinstance(app.homepage, core_manifest.HomepageConfig)
assert app.source.ref_type == core_manifest.RefType.TAG
assert app.source.transport == core_manifest.TransportScheme.HTTPS
def test_cmd_list_flags_manifest_error(
app_factory: AppFactory, capsys: pytest.CaptureFixture
):
"""Ensure cmd_list flags workloads with manifest errors instead of swallowing them."""
app_factory.create(
dir_name="homelab-broken",
manifest_yaml="""
name: broken
env:
SHELL: /bin/sh
""",
)
engine.cmd_list([])
captured = capsys.readouterr()
assert "Manifest Error" in captured.out