prole/tests/installer/test_deploy_helpers.py
chrisfu dba8a2d1dc feat(installer): TDD stabilization for k3d install path; dual-cluster GKE TUI
Junie's session targeted the prompt "stabilize ./install.py -c conf/k3d.cfg
using strict TDD" — broad installer-side work, not the k3d-mirror Phase 3
brief I had filed (which she didn't pick up; phase-3 brief stays open). All
750 installer tests pass post-change.

What Junie produced:

  install.py                          (NEW) Top-level CLI entry point. Was
                                            imagined by the prompt but didn't
                                            exist; this commit makes it real.
  knoe/deployment.py                  (NEW) `KnoeDeployment` orchestrator for
                                            the k3s service-mode deploy pipeline.
                                            Wraps Ansible kubeconfig fetch,
                                            opentofu apply, init_*.sh post-apply
                                            scripts, and (optionally) supabase/
                                            deploy.sh.
  knoe/ui/screens/cluster.py          Dual-cluster GKE kubecontext UI: prod env
  knoe/ui/screens/cfg.py              now shows separate "App Cluster:" and
                                       "DB Cluster:" dropdowns instead of a
                                       single "Kubernetes Context:" combo.
                                       New _app_kubectx_combo + _db_kubectx_combo
                                       widgets; new app/db_cluster_kubecontext
                                       tk.StringVars.
  knoe/core/{actions,env,milestones}.py
  knoe/core/ops/storage.py
  knoe/config.py, knoe/knoe_conf.py   Plumbing changes for the dual-cluster
                                       kubecontext flow + storage-class topology
                                       detection cleanup.
  knoe/tools/cleanup_cnpg_storage.py  (NEW) Stand-alone cleanup utility.
  tools/dashboard.sh                  (NEW) Dashboard helper.
  conf/knoe.cfg                       (NEW) Master cfg generated by knoe_conf.
  conf/dev/                           (NEW) Dev-mode cfg directory.
  conf/port-mapping.cfg               Port mapping tweaks for k3d.
  tests/installer/* (8 files)         New + extended tests for the dual-cluster
  tests/test_database_options.py      TUI, kubecontext save flow, storage ops,
                                       topology detection, deploy helpers,
                                       database-options screen.

Issues found in Junie's working state and fixed here:

  1. install.py was a 11-line import shim with no shebang, no `chmod +x`,
     no `if __name__ == '__main__'` block. `./install.py -c conf/k3d.cfg`
     returned `Permission denied` and `python install.py` did nothing.
     Added `#!/usr/bin/env python3`, `chmod +x`, and a __main__ block
     that delegates to `knoe.ui.screens.main()`. `./install.py --help`
     now prints the canonical argparse help.

  2. knoe/deployment.py had FIVE `subprocess.run()` call sites with no
     `timeout=` argument (`_run_script`, `_run_cmd`, the Ansible playbook
     fetch, `tofu init`, `tofu apply`). A hung child process — typical
     failure mode is a script waiting on stdin or a stalled network
     call — would lock up the installer indefinitely. Added timeouts:
       - Ansible kubeconfig fetch: 120s
       - tofu init: 300s
       - tofu apply, _run_script, _run_cmd: bounded by new module
         constant `_MILESTONE_TIMEOUT` (default 1800s = 30 min, override
         via `KNOE_MILESTONE_TIMEOUT_SECONDS` env var).
     `subprocess.TimeoutExpired` is caught explicitly; on timeout the
     run helpers return exit code 124 (conventional timeout code).

  3. `conf/k3d.cfg` was corrupted with MagicMock string-reprs on disk:
        KNOE_CONF = <MagicMock name='Canvas().tk.call().strip()' id='4743999712'>
        argocd.node_selector = <MagicMock name='mock.StringVar().get().strip()' id='...'>
     Likely path: Junie ran `./install.py -c conf/k3d.cfg` interactively
     in a non-Tk environment (or with a partially-mocked widget set) and
     the installer's "save current state" path wrote the mock-objects'
     `__repr__` strings into the cfg file. This commit reverts the cfg
     to its pre-Junie state. **Followup: harden the cfg save path
     against non-string widget values** — track separately.

  4. The corrupted cfg caused the installer to call `os.makedirs()` on
     the mock-string values, producing 10 directories on disk literally
     named `<MagicMock name='Canvas().tk.call().strip()' id='4733210304'>/`
     etc., with 5–86 files of install artifacts inside each. Removed.

The "final step is timing out" the user reported was almost certainly
issue #2 above: install.py walked the milestone pipeline, hit one of
the unbounded subprocess.run calls, and the wrapped command (probably
supabase/deploy.sh, which Junie was reading for context when her
session timed out) hung. With the timeouts in place that path now
exits cleanly with rc=124 instead of locking up.

Verification:
  - pytest tests/installer/ -q                                   750 passed in ~25s
  - python3 -c "import knoe.deployment"                          imports clean
  - ./install.py --help                                          prints argparse help
  - find . -maxdepth 1 -type d -name '<MagicMock*' | wc -l       0
  - head -7 conf/k3d.cfg                                          clean (no MagicMock)

Out of scope for this commit (followups):
  - The cfg save-path that wrote mock-objects-as-strings (issue #3 root cause).
    Reproducer: launch the installer in an env where Tk widget vars are
    `unittest.mock.MagicMock` instances. The cfg save code should refuse to
    serialize non-str values rather than calling `str()` on a MagicMock.
  - The k3d-mirror Phase 3 brief (`docs/plans/junie/k3d-knoe-auth-pod-deploy.md`)
    is still open — Junie picked a different prompt this round.

Co-authored-by: Junie <junie@jetbrains.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 23:51:14 -07:00

133 lines
5.0 KiB
Python

"""
Unit tests for installer/deploy.py helpers.
Covers check_xcode_tools and build_knoe_app_core error paths without
requiring a real macOS Xcode build environment.
"""
from __future__ import annotations
import subprocess
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from knoe.deploy import check_xcode_tools, build_knoe_app_core
# ---------------------------------------------------------------------------
# check_xcode_tools
# ---------------------------------------------------------------------------
def test_check_xcode_tools_not_darwin():
with patch("knoe.deploy.platform.system", return_value="Linux"):
assert check_xcode_tools() is False
def test_check_xcode_tools_not_darwin_windows():
with patch("knoe.deploy.platform.system", return_value="Windows"):
assert check_xcode_tools() is False
def test_check_xcode_tools_darwin_success():
mock_result = MagicMock()
mock_result.returncode = 0
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.subprocess.run", return_value=mock_result):
assert check_xcode_tools() is True
def test_check_xcode_tools_darwin_failure():
mock_result = MagicMock()
mock_result.returncode = 1
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.subprocess.run", return_value=mock_result):
assert check_xcode_tools() is False
def test_check_xcode_tools_darwin_exception():
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.subprocess.run", side_effect=FileNotFoundError("xcrun not found")):
assert check_xcode_tools() is False
def test_check_xcode_tools_darwin_timeout():
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.subprocess.run", side_effect=subprocess.TimeoutExpired("xcrun", 10)):
assert check_xcode_tools() is False
# ---------------------------------------------------------------------------
# build_knoe_app_core — error paths
# ---------------------------------------------------------------------------
def test_build_knoe_app_core_not_darwin(tmp_path):
with patch("knoe.deploy.platform.system", return_value="Linux"):
with pytest.raises(Exception, match="macOS"):
build_knoe_app_core(tmp_path)
def test_build_knoe_app_core_no_xcode(tmp_path):
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.check_xcode_tools", return_value=False):
with pytest.raises(Exception, match="[Xx]code"):
build_knoe_app_core(tmp_path)
def test_build_knoe_app_core_no_build_script(tmp_path):
# xcode ok but knoe-app/build.sh missing
knoe_app = tmp_path / "knoe-app"
knoe_app.mkdir()
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.check_xcode_tools", return_value=True):
with pytest.raises(Exception, match="[Bb]uild script"):
build_knoe_app_core(tmp_path)
def test_build_knoe_app_core_build_fails(tmp_path):
knoe_app = tmp_path / "knoe-app"
knoe_app.mkdir()
build_sh = knoe_app / "build.sh"
build_sh.write_text("#!/bin/bash\nexit 1\n")
mock_result = MagicMock()
mock_result.returncode = 1
mock_result.stderr = "build error"
mock_result.stdout = ""
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.check_xcode_tools", return_value=True), \
patch("knoe.deploy.subprocess.run", return_value=mock_result):
with pytest.raises(Exception, match="[Bb]uild failed"):
build_knoe_app_core(tmp_path)
def test_build_knoe_app_core_app_missing_after_build(tmp_path):
knoe_app = tmp_path / "knoe-app"
knoe_app.mkdir()
build_sh = knoe_app / "build.sh"
build_sh.write_text("#!/bin/bash\nexit 0\n")
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stderr = ""
mock_result.stdout = "Build OK"
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.check_xcode_tools", return_value=True), \
patch("knoe.deploy.subprocess.run", return_value=mock_result):
# dist/Knoe.app is not created → should raise
with pytest.raises(Exception, match="[Kk]noe.app"):
build_knoe_app_core(tmp_path)
def test_build_knoe_app_core_success(tmp_path):
knoe_app = tmp_path / "knoe-app"
(knoe_app / "dist").mkdir(parents=True)
app_path = knoe_app / "dist" / "Knoe.app"
app_path.mkdir()
build_sh = knoe_app / "build.sh"
build_sh.write_text("#!/bin/bash\nexit 0\n")
mock_result = MagicMock()
mock_result.returncode = 0
with patch("knoe.deploy.platform.system", return_value="Darwin"), \
patch("knoe.deploy.check_xcode_tools", return_value=True), \
patch("knoe.deploy.subprocess.run", return_value=mock_result):
result = build_knoe_app_core(tmp_path)
assert result == app_path