"""Offline tests for v40.2 AI delegation; no real provider calls are made.""" from __future__ import annotations import json import os import tempfile from pathlib import Path from unittest.mock import patch from ai_delegation import AIDelegationManager class FakeResponse: def __init__(self, status=200, body=None, text=""): self.status_code = status self.ok = 200 <= status < 300 self._body = body or {} self.text = text or json.dumps(self._body) def json(self): return self._body def make_config(root: Path, workers): path = root / "ai_workers.json" path.write_text(json.dumps({"version": 1, "save_reports": True, "max_parallel": 3, "workers": workers}, indent=2), encoding="utf-8") return AIDelegationManager(path, root / "logs") def worker(wid, role, api_style="openai_compatible"): return { "id": wid, "name": wid.title(), "provider": "Mock API", "api_style": api_style, "base_url": "https://api.example.test/v1", "model": "mock-model", "api_key_env": "TEST_DELEGATION_KEY", "role": role, "enabled": True, "max_tokens": 100, "timeout_sec": 5 } def test_default_registry_is_disabled_and_contains_no_keys(): with tempfile.TemporaryDirectory() as td: manager = AIDelegationManager(Path(td) / "ai_workers.json", Path(td) / "logs") status = manager.status() assert status["enabled_workers"] == 0 text = manager.config_path.read_text(encoding="utf-8") assert "api_key" not in text.lower() or "api_key_env" in text.lower() assert "sk-" not in text assert all(not row["enabled"] for row in status["workers"]) print("PASS test_default_registry_is_disabled_and_contains_no_keys") def test_single_worker_delegate_and_audit_report(): with tempfile.TemporaryDirectory() as td: manager = make_config(Path(td), [worker("researcher", "researcher")]) fake = FakeResponse(body={"choices": [{"message": {"content": "Evidence summary and assumptions."}}]}) with patch.dict(os.environ, {"TEST_DELEGATION_KEY": "test-key-not-real"}), patch("ai_delegation.requests.post", return_value=fake) as post: report = manager.delegate("researcher", "Research project cost options.") assert report["status"] == "completed", report assert report["workers"][0]["output"] == "Evidence summary and assumptions." sent = post.call_args.kwargs assert sent["headers"]["Authorization"] == "Bearer test-key-not-real" saved = Path(td) / "logs" / (report["run_id"] + ".json") assert saved.exists() assert "test-key-not-real" not in saved.read_text(encoding="utf-8") print("PASS test_single_worker_delegate_and_audit_report") def test_team_parallel_workers_and_manager_summary(): with tempfile.TemporaryDirectory() as td: manager = make_config(Path(td), [worker("researcher", "researcher"), worker("reviewer", "reviewer")]) def response_for(*args, **kwargs): payload = kwargs.get("json", {}) role = "review" if "reviewer" in json.dumps(payload).lower() or "Independently review" in json.dumps(payload) else "research" return FakeResponse(body={"choices": [{"message": {"content": f"{role} findings."}}]}) with patch.dict(os.environ, {"TEST_DELEGATION_KEY": "mock-secret"}), patch("ai_delegation.requests.post", side_effect=response_for) as post: report = manager.run_team("Prepare a website launch plan.", manager_synthesizer=lambda goal, rows: f"Manager consolidated {len(rows)} specialist reports.") assert report["status"] == "completed", report assert len(report["workers"]) == 2, report assert all(row["status"] == "completed" for row in report["workers"]), report assert report["manager_summary"] == "Manager consolidated 2 specialist reports." assert post.call_count == 2, post.call_count print("PASS test_team_parallel_workers_and_manager_summary") def test_anthropic_and_gemini_response_parsing(): with tempfile.TemporaryDirectory() as td: anth = worker("claude", "reviewer", "anthropic") anth["base_url"] = "https://api.anthropic.com" gem = worker("gemini", "analyst", "gemini") gem["base_url"] = "https://generativelanguage.googleapis.com/v1beta" manager = make_config(Path(td), [anth, gem]) anth_response = FakeResponse(body={"content": [{"type": "text", "text": "Claude says review."}]}) gem_response = FakeResponse(body={"candidates": [{"content": {"parts": [{"text": "Gemini says analysis."}]}}]}) with patch.dict(os.environ, {"TEST_DELEGATION_KEY": "mock-secret"}), patch("ai_delegation.requests.post", side_effect=[anth_response, gem_response]) as post: a = manager.delegate("claude", "Review this plan.") b = manager.delegate("gemini", "Analyze this plan.") assert a["workers"][0]["output"] == "Claude says review." assert b["workers"][0]["output"] == "Gemini says analysis." assert "x-api-key" in post.call_args_list[0].kwargs["headers"] assert "x-goog-api-key" in post.call_args_list[1].kwargs["headers"] print("PASS test_anthropic_and_gemini_response_parsing") def test_worker_missing_key_is_reported_as_failure_without_network(): with tempfile.TemporaryDirectory() as td: manager = make_config(Path(td), [worker("researcher", "researcher")]) with patch.dict(os.environ, {}, clear=True), patch("ai_delegation.requests.post") as post: report = manager.delegate("researcher", "Do a small task.") assert report["status"] == "failed" assert "TEST_DELEGATION_KEY" in report["workers"][0]["error"] post.assert_not_called() print("PASS test_worker_missing_key_is_reported_as_failure_without_network") def test_nonlocal_http_endpoint_rejected(): with tempfile.TemporaryDirectory() as td: w = worker("unsafe", "analyst") w["base_url"] = "http://api.example.test/v1" config = Path(td) / "ai_workers.json" config.write_text(json.dumps({"workers": [w]}), encoding="utf-8") try: AIDelegationManager(config, Path(td) / "logs") except ValueError as exc: assert "HTTPS" in str(exc) else: raise AssertionError("Non-local HTTP endpoint should be refused.") print("PASS test_nonlocal_http_endpoint_rejected") def main(): tests = [test_default_registry_is_disabled_and_contains_no_keys, test_single_worker_delegate_and_audit_report, test_team_parallel_workers_and_manager_summary, test_anthropic_and_gemini_response_parsing, test_worker_missing_key_is_reported_as_failure_without_network, test_nonlocal_http_endpoint_rejected] for test in tests: test() print(f"PASS all {len(tests)} AI delegation tests (offline mocks; no real API calls)") if __name__ == "__main__": main()