""" F98: compute_cascade() Decision-Matrix Tests (TDD). Testet die zentrale Cascade-Funktion (Provider × Multiroom → Folgeaktionen) aus Rainers Architektur-Konzept §3.3. Die Matrix ist die Single Source of Truth für Ollama-Install, Modell-Pull und faiss/numpy-Install. Matrix (verbindlich): ollama + multiroom → Ollama JA, qwen2.5:7b + nomic-embed-text, faiss JA ollama + single → Ollama JA, nomic-embed-text only, faiss NEIN custom (DGX) + multiroom → Ollama NEIN, keine Modelle, faiss JA custom (DGX) + single → Ollama NEIN, keine Modelle, faiss NEIN openrouter + * → Ollama NEIN, keine Modelle, faiss nur multiroom ollama-cloud + * → Ollama NEIN, keine Modelle, faiss nur multiroom none + * → Ollama NEIN, keine Modelle, faiss nur multiroom """ from __future__ import annotations import subprocess from pathlib import Path import pytest INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh" def _read_install_sh() -> str: return INSTALL_SH.read_text() def _extract_functions(*names: str) -> str: """Extrahiert Funktions-Definitionen (plus log-Helfer) aus install.sh, OHNE den Hauptfluss auszuführen. Gibt ein bash-Snippet zurück.""" content = INSTALL_SH.read_text() lines = content.splitlines() def _find_func(name: str) -> tuple[int, int] | None: start = None for i, line in enumerate(lines): if line.startswith(f"{name}()"): start = i break if start is None: return None end = start for j in range(start + 1, len(lines)): if lines[j].strip() == "}": end = j break return start, end header_parts = [] for helper in ("mask_secrets", "log", "warn", "err", "ok", "banner", "die"): r = _find_func(helper) if r: header_parts.append("\n".join(lines[r[0]:r[1] + 1])) header = "C_RESET=''; C_BLUE=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_BOLD=''\n\n" + "\n\n".join(header_parts) funcs = [] for name in names: r = _find_func(name) if r: funcs.append("\n".join(lines[r[0]:r[1] + 1])) return header + "\n\n" + "\n\n".join(funcs) + "\n" def _run_cascade(provider: str, multiroom: str) -> tuple[str, str, int]: """Führt compute_cascade() mit gegebenem Provider/Multiroom aus und gibt (stdout, stderr, rc) zurück.""" snippet = ( _extract_functions("compute_cascade") + f"PROVIDER='{provider}'\n" + f"RC_MULTIROOM='{multiroom}'\n" + "compute_cascade\n" + "echo \"OLLAMA_INSTALL_REQUIRED=$OLLAMA_INSTALL_REQUIRED\"\n" + "echo \"FAISS_REQUIRED=$FAISS_REQUIRED\"\n" + "echo \"MODEL_PULL_REQUIRED=${MODEL_PULL_REQUIRED[*]}\"\n" ) env = {"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": "/tmp/f98-cascade-home"} result = subprocess.run( ["bash", "-c", snippet], capture_output=True, text=True, env=env, timeout=30, ) return result.stdout, result.stderr, result.returncode def _parse(out: str) -> dict: d = {} for line in out.splitlines(): if "=" in line and not line.startswith("Cascade:"): k, v = line.split("=", 1) d[k] = v return d class TestComputeCascadeMatrix: """Jede Zelle der Cascade-Matrix §3.3 wird explizit abgeklopft.""" def test_ollama_multiroom(self): out, err, rc = _run_cascade("ollama", "true") d = _parse(out) assert rc == 0, f"compute_cascade crashte:\n{out}\n{err}" assert d["OLLAMA_INSTALL_REQUIRED"] == "true" assert d["FAISS_REQUIRED"] == "true" assert "qwen2.5:7b" in d["MODEL_PULL_REQUIRED"] assert "nomic-embed-text" in d["MODEL_PULL_REQUIRED"] def test_ollama_single(self): out, err, rc = _run_cascade("ollama", "false") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "true" assert d["FAISS_REQUIRED"] == "false" assert "nomic-embed-text" in d["MODEL_PULL_REQUIRED"] assert "qwen2.5:7b" not in d["MODEL_PULL_REQUIRED"] def test_custom_dgx_multiroom(self): out, err, rc = _run_cascade("custom", "true") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "true" assert d["MODEL_PULL_REQUIRED"] == "" def test_custom_dgx_single(self): out, err, rc = _run_cascade("custom", "false") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "false" assert d["MODEL_PULL_REQUIRED"] == "" def test_openrouter_multiroom(self): out, err, rc = _run_cascade("openrouter", "true") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "true" assert d["MODEL_PULL_REQUIRED"] == "" def test_openrouter_single(self): out, err, rc = _run_cascade("openrouter", "false") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "false" assert d["MODEL_PULL_REQUIRED"] == "" def test_ollama_cloud_multiroom(self): out, err, rc = _run_cascade("ollama-cloud", "true") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "true" assert d["MODEL_PULL_REQUIRED"] == "" def test_ollama_cloud_single(self): out, err, rc = _run_cascade("ollama-cloud", "false") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "false" assert d["MODEL_PULL_REQUIRED"] == "" def test_none_multiroom(self): out, err, rc = _run_cascade("none", "true") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "true" assert d["MODEL_PULL_REQUIRED"] == "" def test_none_single(self): out, err, rc = _run_cascade("none", "false") d = _parse(out) assert rc == 0 assert d["OLLAMA_INSTALL_REQUIRED"] == "false" assert d["FAISS_REQUIRED"] == "false" assert d["MODEL_PULL_REQUIRED"] == "" class TestCascadeIntegration: """Strukturelle Invarianten: die drei unkonditionalen Stellen sind jetzt conditional auf die Cascade-Flags.""" def test_compute_cascade_function_exists(self): content = _read_install_sh() assert "compute_cascade()" in content def test_ollama_install_conditional(self): """install_system_deps: Ollama-Block in `if $OLLAMA_INSTALL_REQUIRED`.""" content = _read_install_sh() assert "OLLAMA_INSTALL_REQUIRED" in content # Der Ollama-Install-Block muss conditional sein. assert "if $OLLAMA_INSTALL_REQUIRED; then" in content def test_model_pull_uses_array(self): """Hauptfluss iteriert über MODEL_PULL_REQUIRED, nicht hardcoded Liste.""" content = _read_install_sh() assert 'for m in "${MODEL_PULL_REQUIRED[@]}"' in content # Die alte hardcoded Schleife darf nicht mehr im Hauptfluss stehen. assert 'for m in qwen2.5:7b nomic-embed-text; do' not in content def test_install_python_deps_function_exists(self): content = _read_install_sh() assert "install_python_deps()" in content def test_no_python3_pip_in_wizard_phase7(self): """P-179: Phase 7 nutzt kein `python3 -m pip install` mehr.""" content = _read_install_sh() # Nur noch der pipx-Fallback in install_system_deps darf python3 -m pip nutzen. # Der Wizard-Phase-7-Block darf es nicht mehr. assert "python3 -m pip install --quiet" not in content def test_loginctl_timeout(self): """P-182: loginctl enable-linger mit timeout 10.""" content = _read_install_sh() assert "timeout 10 sudo loginctl enable-linger" in content def test_no_naked_secret_refs(self): """P-177 A2: keine nackten `[ -z "$VAR" ]` Secret-Refs mehr.""" import re content = _read_install_sh() # Nackte Secret-Refs (ohne ${VAR:-}) dürfen nicht mehr existieren. assert not re.search(r'\[ -z "\$[A-Z_]+(_KEY|_PASSWORD|_USER_ID)"', content) def test_setup_requirements_has_required_if(self): """P-178: setup_requirements.txt hat required_if-Spalte.""" req = Path(__file__).resolve().parents[1] / "setup_requirements.txt" content = req.read_text() assert "required_if" in content assert "faiss-cpu|faiss-cpu|1.7.4|SOFT|multiroom" in content assert "numpy|numpy|1.24.0|SOFT|multiroom" in content assert "snowballstemmer|snowballstemmer|2.2.0|SOFT|always" in content