prole/tests/installer/test_cluster_save_triggers_status_check.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

139 lines
5.2 KiB
Python

import sys
import tkinter as tk
from pathlib import Path
from unittest.mock import MagicMock
import pytest
# Ensure `installer` is importable when tests are invoked directly via `pytest`
PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
import knoe.ui.screens.cluster as cluster_mod
from knoe.ui.screens.base import ScreenBaseMixin
from knoe.ui.screens.cluster import ClusterScreenMixin
class _DummyClusterSaveApp(ScreenBaseMixin, ClusterScreenMixin):
"""Minimal surface to exercise the Cluster Environment screen Save behavior."""
def __init__(self, root: tk.Tk):
self.root = root
# Canvas is not required by `_validate_and_save_cluster_config`, but other mixins
# assume it exists.
self.bg_canvas = tk.Canvas(root, width=1, height=1)
self._canvas_items = []
self._overlay_widgets = []
self.cluster_env = tk.StringVar(master=root, value="service")
self.selected_k3d_cluster = tk.StringVar(master=root, value="")
self.selected_kubectx = tk.StringVar(master=root, value="")
self.service_namespace = tk.StringVar(master=root, value="knoe-system")
self.prod_artifacts_path = tk.StringVar(master=root, value=str(Path.home()))
self.k3s_server_url = tk.StringVar(master=root, value="")
self.k3s_token = tk.StringVar(master=root, value="")
self.supabase_enabled = tk.BooleanVar(master=root, value=False)
self.gitops_enabled = tk.BooleanVar(master=root, value=False)
self.kerberos_enabled = tk.BooleanVar(master=root, value=False)
self.at_rest_encryption_enabled = tk.BooleanVar(master=root, value=False)
# Minimal config structure required by `_validate_and_save_cluster_config`.
self.knoe_cfg_data = {
"Initialize Cluster": {
"ENVIRONMENT": "service",
"K3S_SERVER_URL": "",
"K3S_TOKEN": "",
},
"Global": {
# Keep old/new equal so we don't trigger the namespace cleanup prompt.
"SERVICE_NAMESPACE": "knoe-system",
},
"Optional Features": {},
"Prod Cluster (k8s)": {},
}
self.saved_calls = 0
self.status_check_calls = 0
def _save_knoe_cfg(self):
self.saved_calls += 1
def _verify_k3s_services(self):
self.status_check_calls += 1
def test_cluster_env_save_triggers_status_check(monkeypatch):
# Some test modules replace tkinter with MagicMocks at import-time.
if isinstance(sys.modules.get("tkinter"), MagicMock):
pytest.skip("tkinter is mocked in this test run")
# Avoid depending on a real kubeconfig file.
monkeypatch.setattr(cluster_mod, "_find_kubeconfig_file", lambda: "/tmp/kubeconfig")
# Avoid any real secret handling.
monkeypatch.setattr(cluster_mod, "_encrypt_cfg_secret", lambda s: s)
root = tk.Tk()
root.withdraw()
try:
app = _DummyClusterSaveApp(root)
assert app._validate_and_save_cluster_config() is True
assert app.saved_calls == 1
# Requirement: clicking Save should immediately run a status check.
assert app.status_check_calls == 1
finally:
try:
root.destroy()
except Exception:
pass
def test_cluster_env_prod_artifacts_dir_expands_knoe_home_from_cfg(monkeypatch, tmp_path):
# Some test modules replace tkinter with MagicMocks at import-time.
if isinstance(sys.modules.get("tkinter"), MagicMock):
pytest.skip("tkinter is mocked in this test run")
# Ensure `$KNOE_HOME` is NOT available as an OS env var; it must come from config.
monkeypatch.delenv("KNOE_HOME", raising=False)
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(cluster_mod, "_encrypt_cfg_secret", lambda s: s)
monkeypatch.setattr(cluster_mod, "_find_kubeconfig_file", lambda: "/tmp/kubeconfig")
root = tk.Tk()
root.withdraw()
try:
app = _DummyClusterSaveApp(root)
# Stub out prod-specific helpers not present on the dummy.
app._ensure_prod_config_state = lambda: None
app._prod_put_config = lambda show_dialog=True: {"errors": []}
app._prod_payload_from_vars = lambda: {}
app.prod_config_api = MagicMock()
app.prod_config_api.post_plan.return_value = {"yaml": "", "opentofuVars": {}, "installPlan": [], "messages": []}
app.prod_tab_messages = tk.StringVar(master=root, value="")
# Switch to prod so the artifacts directory is validated/created.
app.cluster_env.set("prod")
# Provide KNOE_HOME via config data only.
knoe_home = tmp_path / "knoe-home"
knoe_home.mkdir(parents=True, exist_ok=True)
app.knoe_cfg_data.setdefault("System Environment", {})["KNOE_HOME"] = str(
knoe_home
)
# Use a path expression that previously would create a literal `$KNOE_HOME` dir.
app.prod_artifacts_path.set("$KNOE_HOME/staging")
assert app._validate_and_save_cluster_config() is True
assert (knoe_home / "staging").is_dir()
assert not (tmp_path / "$KNOE_HOME" / "staging").exists()
finally:
try:
root.destroy()
except Exception:
pass