diff --git a/swarm_pipeline.py b/swarm_pipeline.py index 9b565b8..04216b6 100644 --- a/swarm_pipeline.py +++ b/swarm_pipeline.py @@ -9,6 +9,8 @@ import os import sys import json +import re +import subprocess import time import datetime import threading @@ -22,6 +24,19 @@ LOG_FILE = os.path.join(SPECS_DIR, "terminal.log") STATUS_FILE = os.path.join(SPECS_DIR, "swarm-status.json") +_RAN_LINE = re.compile(r"^Ran (\d+) tests? in ", re.M) + + +def count_tests_run(output: str): + """Number of tests unittest says it ran, or None if there is no summary line. + + A runner that exits 0 without running anything must not count as a pass: unittest + exits 0 for an empty discovery up to Python 3.11 and 5 ("NO TESTS RAN") from 3.12 on. + """ + found = _RAN_LINE.findall(output or "") + return int(found[-1]) if found else None + + def get_timestamp() -> str: return datetime.datetime.now().strftime("%H:%M:%S") @@ -452,10 +467,12 @@ def compute_progress(step_num): f.write(test_clean.strip() + "\n") # Execute test suite to verify tests pass - log_swarm_message("07_qa", "Executing automated test suite: python -m unittest discover tests ...", base_dir) + log_swarm_message("07_qa", "Executing the generated tests: python -m unittest discover -s tests -p test_api.py ...", base_dir) try: + # Only the generated file: any other test in tests/ (the framework ships its own) must + # neither decide whether the generated tests pass nor eat into the timeout. test_proc = subprocess.run( - [sys.executable, "-m", "unittest", "discover", "-s", "tests"], + [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-p", "test_api.py"], cwd=base_dir, capture_output=True, text=True, @@ -466,7 +483,13 @@ def compute_progress(step_num): log_swarm_message("07_qa", f"[TEST FAILURE] Unit test runner reported failures:\n{err_output[:300]}", base_dir) update_swarm_status("07_qa", "WAITING", "Test execution failed. Unit tests reported failures or syntax errors.", 50, base_dir, phase="FAILED: QA Unit Tests Failed") return False - log_swarm_message("07_qa", "Automated test suite passed with zero regressions.", base_dir) + ran = count_tests_run((test_proc.stderr or "") + "\n" + (test_proc.stdout or "")) + if not ran: # 0 tests, or no unittest summary at all (for example pytest-style functions) + why = "ran no tests" if ran == 0 else "printed no unittest summary" + log_swarm_message("07_qa", f"[TEST FAILURE] The generated tests {why}; nothing was verified.", base_dir) + update_swarm_status("07_qa", "WAITING", f"Generated tests {why}.", 50, base_dir, phase="FAILED: QA No Tests Ran") + return False + log_swarm_message("07_qa", f"Automated test suite passed ({ran} test{'s' if ran != 1 else ''} ran).", base_dir) except Exception as e: log_swarm_message("07_qa", f"[TEST RUNNER ERROR] Could not execute tests: {str(e)}", base_dir) update_swarm_status("07_qa", "WAITING", f"Test runner error: {str(e)}", 0, base_dir, phase="FAILED: QA Test Runner Error") diff --git a/tests/support.py b/tests/support.py new file mode 100644 index 0000000..7371da5 --- /dev/null +++ b/tests/support.py @@ -0,0 +1,183 @@ +"""Shared fixtures for the swarm pipeline tests. + +Everything here is a fake: providers are plain dicts with a fake key, the +model call (`council.call_llm`) is replaced, and `subprocess.run` is replaced, +so no network is touched and no model-generated code is ever executed. + +Importing this module also puts the repository root on ``sys.path`` so the +tests work under ``python -I`` (isolated mode drops the working directory +from the import path). +""" + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +REPO_ROOT = str(Path(os.environ.get("TENAGENT_TEST_ROOT") or Path(__file__).resolve().parent.parent)) +if REPO_ROOT not in sys.path: + sys.path.insert(0, REPO_ROOT) + +import council # noqa: E402 +import swarm_pipeline # noqa: E402 + +FAKE_KEY = "sk-FAKE-do-not-use-0123456789" +PROVIDER = {"id": "groq", "name": "Mock provider", "key": FAKE_KEY} +AGENT_IDS = [ + "01_pm", "02_arch", "03_designer", "04_dba", "05_backend", + "06_client", "07_qa", "08_security", "09_devops", "10_tech_lead", +] + +# (substring of the system prompt, output key) +STAGE_MARKERS = [ + ("Product Manager", "prd"), + ("System Architect", "adr"), + ("design tokens containing", "tokens"), + ("Screen Flow Document", "flows"), + ("Database Engineer", "sql"), + ("API Architect", "openapi"), + ("You are the Backend Engineer", "backend"), + ("Client Engineer", "client"), + ("Formulate a QA Test Matrix", "qa_matrix"), + ("executable Python unittest suite", "tests"), + ("OWASP Application Security Auditor", "security"), + ("DevOps Engineer", "docker"), + ("Technical Lead", "lead"), +] + +PROSE = " Users can create, list and remove items, and every list view shows the newest entry first." + +GOOD_OUTPUTS = { + "prd": "# Product requirements\n\nUsers can list things." + PROSE, + "adr": "# Architecture ADR\n\nClean architecture with domain, use case and repository layers." + PROSE, + "tokens": '{"colors": {"primary": "#fff"}, "typography": {}, "spacing": {}}', + "flows": "# Screen flows\n\nHome -> list -> detail." + PROSE, + "sql": "CREATE TABLE thing (id INTEGER PRIMARY KEY);", + "openapi": ( + "openapi: 3.0.0\ninfo:\n title: Mock\n version: 1.0.0\n" + "paths:\n /health:\n get:\n responses:\n '200':\n description: ok\n" + ), + "backend": "def example():\n return 1\n", + "client": "App", + "qa_matrix": "# QA test matrix\n\nHappy path, empty list, boundary sizes." + PROSE, + "tests": ( + "import unittest\n\n" + "class TestExample(unittest.TestCase):\n" + " def test_example(self):\n" + " self.assertEqual(1 + 1, 2)\n" + ), + "security": "# Advisory security review\n\nNo findings are claimed here; a scanner must confirm." + PROSE, + "docker": "FROM python:3.11-slim\n", + "lead": "[APPROVED FOR PRODUCTION]", +} + + +def stage_key(system_prompt): + for marker, key in STAGE_MARKERS: + if marker in system_prompt: + return key + raise AssertionError("unrecognised stage prompt: " + system_prompt[:60]) + + +def make_status_file(root, overall=0, phase="Phase 1", agent_overrides=None): + specs = Path(root) / "specs" + specs.mkdir(parents=True, exist_ok=True) + agents = [] + for aid in AGENT_IDS: + agent = { + "id": aid, "role": aid, "status": "IDLE", "currentTask": "", + "processDetail": "", "progress": 0, "deliverable": "", + } + agent.update((agent_overrides or {}).get(aid, {})) + agents.append(agent) + data = { + "project": {"name": "t", "phase": phase, "overallProgress": overall}, + "agents": agents, + "logs": [], + } + path = specs / "swarm-status.json" + path.write_text(json.dumps(data, indent=2), encoding="utf-8") + return path + + +def read_status(root): + return json.loads((Path(root) / "specs" / "swarm-status.json").read_text(encoding="utf-8-sig")) + + +def list_files(root): + return sorted(p.relative_to(root).as_posix() for p in Path(root).rglob("*") if p.is_file()) + + +class PipelineCase(unittest.TestCase): + """Runs the real pipeline entry point with a faked model call and a faked test runner.""" + + def setUp(self): + quiet = patch.object(swarm_pipeline, "print", create=True) # the pipeline echoes its log to stdout + quiet.start() + self.addCleanup(quiet.stop) + self.new_root() + + def new_root(self): + """Fresh project directory (also used between subTests so they cannot leak state).""" + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + (self.root / "Dockerfile").write_text("FROM original-image\n", encoding="utf-8") + (self.root / ".github" / "workflows").mkdir(parents=True) + (self.root / ".github" / "workflows" / "ci.yml").write_text("name: Original CI\n", encoding="utf-8") + self.calls = [] + self.test_runs = [] + + def run_swarm(self, outputs=None, providers=None, status=True, goal="Mock task", + call_hook=None, run_fn=None, debate=None, test_returncode=0, + test_output="Ran 1 test in 0.001s\n\nOK\n"): + merged = dict(GOOD_OUTPUTS) + merged.update(outputs or {}) + if status and not (self.root / "specs" / "swarm-status.json").exists(): + make_status_file(self.root) + providers = [PROVIDER] if providers is None else providers + + def fake_call_llm(provider, system_prompt, user_prompt, timeout=75): + key = stage_key(system_prompt) + self.calls.append(key) + if call_hook: + call_hook(key) + value = merged[key] + if isinstance(value, BaseException): + raise value + return value() if callable(value) else value + + def fake_run(args, **kwargs): + # The QA stage would run the generated tests; here nothing is ever executed. + self.test_runs.append({"args": list(args), **kwargs}) + if isinstance(test_returncode, BaseException): + raise test_returncode + return subprocess.CompletedProcess(args, test_returncode, "", test_output) + + with ExitStack() as stack: + stack.enter_context(patch.object(council, "get_active_providers", return_value=providers)) + stack.enter_context(patch.object(council, "call_llm", side_effect=fake_call_llm)) + stack.enter_context(patch("subprocess.run", side_effect=fake_run)) + if debate is None: + debate_patch = patch.object( + council, "run_council_debate", return_value={"status": "native_only", "consensus": None}) + else: + debate_patch = patch.object(council, "run_council_debate", side_effect=debate) + stack.enter_context(debate_patch) + stack.enter_context(patch.object(swarm_pipeline.time, "sleep")) + runner = run_fn or swarm_pipeline.execute_multi_brain_swarm + return runner(goal, str(self.root)) + + def read(self, rel): + return (self.root / rel).read_text(encoding="utf-8") + + def exists(self, rel): + return (self.root / rel).exists() + + def files(self): + return list_files(self.root) diff --git a/tests/test_swarm_qa_stage.py b/tests/test_swarm_qa_stage.py new file mode 100644 index 0000000..6600191 --- /dev/null +++ b/tests/test_swarm_qa_stage.py @@ -0,0 +1,72 @@ +"""The QA stage runs the generated tests; the run must reach (and honestly report) that step. + +`subprocess.run` is faked in every test (see support.PipelineCase), so no generated +code is executed. +""" + +import sys +import unittest + +import support # noqa: F401 (puts the repo root on sys.path for python -I) +from support import PipelineCase, read_status + + +class QaStageRunsTheGeneratedTests(PipelineCase): + def test_a_complete_run_gets_past_the_test_runner(self): + self.assertTrue(self.run_swarm()) + self.assertNotIn("FAILED", read_status(self.root)["project"]["phase"]) + self.assertEqual(self.calls[-1], "lead", "the stages after QA never ran") + + def test_the_runner_is_invoked_on_the_projects_tests_directory(self): + self.run_swarm() + self.assertEqual(len(self.test_runs), 1) + run = self.test_runs[0] + self.assertEqual(run["args"], [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-p", "test_api.py"]) + self.assertEqual(run["cwd"], str(self.root)) + self.assertGreater(run["timeout"], 0) + + def test_failing_generated_tests_stop_the_run_with_the_unit_test_phase(self): + self.assertFalse(self.run_swarm(test_returncode=1)) + data = read_status(self.root) + self.assertEqual(data["project"]["phase"], "FAILED: QA Unit Tests Failed") + self.assertNotIn("security", self.calls, "stages after a failed QA run must not start") + self.assertFalse(self.exists("specs/signoff.md")) + + def test_a_runner_that_exits_zero_after_running_no_tests_is_not_a_pass(self): + # unittest exits 0 for an empty discovery on Python <= 3.11 and 5 on 3.12+ + self.assertFalse(self.run_swarm(test_returncode=0, test_output="Ran 0 tests in 0.000s\n\nNO TESTS RAN\n")) + self.assertEqual(read_status(self.root)["project"]["phase"], "FAILED: QA No Tests Ran") + self.assertNotIn("security", self.calls) + + def test_a_runner_with_no_summary_line_is_not_a_pass(self): + for output in ("", "something unrelated\n", "Ran many tests\n"): + with self.subTest(output=output): + self.new_root() + self.assertFalse(self.run_swarm(test_returncode=0, test_output=output)) + self.assertEqual(read_status(self.root)["project"]["phase"], "FAILED: QA No Tests Ran") + + def test_the_number_of_tests_that_ran_is_logged(self): + self.assertTrue(self.run_swarm(test_output="Ran 3 tests in 0.002s\n\nOK\n")) + self.assertIn("3 tests ran", self.read("specs/terminal.log")) + + def test_the_log_line_names_the_command_that_is_run(self): + self.run_swarm() + self.assertIn("unittest discover -s tests -p test_api.py", self.read("specs/terminal.log")) + + def test_count_tests_run_parses_the_last_summary(self): + import swarm_pipeline + + self.assertEqual(swarm_pipeline.count_tests_run("Ran 1 test in 0.1s\nOK"), 1) + self.assertEqual(swarm_pipeline.count_tests_run("Ran 12 tests in 1s\n\nOK"), 12) + self.assertEqual(swarm_pipeline.count_tests_run("Ran 0 tests in 0s"), 0) + self.assertEqual(swarm_pipeline.count_tests_run("Ran 2 tests in 1s\nRan 5 tests in 1s"), 5) + self.assertIsNone(swarm_pipeline.count_tests_run("")) + self.assertIsNone(swarm_pipeline.count_tests_run(None)) + + def test_runner_that_cannot_start_is_reported_as_a_runner_error(self): + self.assertFalse(self.run_swarm(test_returncode=OSError("no interpreter"))) + self.assertEqual(read_status(self.root)["project"]["phase"], "FAILED: QA Test Runner Error") + + +if __name__ == "__main__": + unittest.main()