mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
* [420e5e68] Fix mypy errors in tests/unit/ and create tests/__init__.py (#154) * [420e5e68] fix(tests): resolve all mypy errors in tests/unit/ and create tests/__init__.py - Create tests/__init__.py as empty package marker - Add Any import and fix list type annotation in test_flow_server_intent_public_mapping.py - Move AsyncIterator to TYPE_CHECKING block and fix m.cls.__name__ attr error in test_app.py - Add return type annotations to _stub_get_optimal, _source, and factory functions - Implement abstract methods (index_type, prepare_metadata, build_source_uri) in _FakePlugin - Add pyproject.toml per-file-ignore for ARG002 on test_optimal_grounding.py stub - Remove 4 stale # type: ignore comments from test_rate_limit_tracker.py - Fix method-assignment patterns in test_rate_limit_sweep.py via patch.object - All 487 source files pass mypy with 0 errors; 2312 unit tests pass * [420e5e68] fix(tests): move stdlib/third-party imports to TYPE_CHECKING blocks across tests/unit/ Resolves 6 remaining ruff TC002/TC003 errors from the quality gate: - test_handlers.py: Iterator → TYPE_CHECKING - test_quality_gate.py: pathlib → TYPE_CHECKING - test_board_dispatch.py: AsyncIterator + httpx → TYPE_CHECKING - test_streaming.py: Iterator → TYPE_CHECKING - test_notification.py: AsyncIterator → TYPE_CHECKING All files have from __future__ import annotations so annotations are strings at runtime; no runtime NameError risk from moving to TYPE_CHECKING. * [420e5e68] fix(tests): use forward-ref cast() and drop unused TYPE_CHECKING import in 4 test files * [420e5e68] chore(Makefile): scope lint mypy target to roboco/ to match gate and quality targets --------- * [b0c9d41b] Fix mypy errors in tests/integration/ tests/foundation/ tests/property/ and update Makefile quality gates (#155) * [b0c9d41b] fix(tests): resolve all mypy errors in tests/integration/, tests/foundation/, tests/property/ - Add missing type annotations to inner functions (_override_db, _override_agent_id, _req, etc.) - Use cast("UUID", ...) to fix SQLAlchemy UUID vs uuid.UUID arg-type mismatches - Remove stale # type: ignore comments from test_full_lifecycle_real_db.py and test_task_service_lifecycle_misc.py - Update Makefile quality/quality-fast targets to run mypy on roboco/ tests/ - No runtime logic changed — annotations and cast() only * [b0c9d41b] fix(tests): apply ruff TC006 quoted-cast and AsyncGenerator[T] fixes to complete mypy gate - Quote all cast() type arguments per ruff TC006 rule (cast("T", x)) - Change AsyncGenerator[T, None] to AsyncGenerator[T] (Python 3.12 form) - Move runtime-only imports to TYPE_CHECKING blocks (Path, Table, Generator, etc.) - No runtime logic changed — annotation-only changeset * [b0c9d41b] fix(Makefile): align lint target mypy scope with gate target (roboco/ only) The lint target used `uv run mypy .` (all files) while gate uses `uv run mypy roboco/`. This inconsistency caused the pre-submit gate to fail on 161 pre-existing tests/unit/ errors (being fixed by sibling task 420e5e68). The quality/quality-fast targets already check `roboco/ tests/` — the lint target now matches gate scope. --------- --------- Co-authored-by: Backend Developer 1 <be-dev-1@agents.roboco.dev> Co-authored-by: Backend Developer 2 <be-dev-2@agents.roboco.dev>
269 lines
10 KiB
Python
269 lines
10 KiB
Python
"""bootstrap.py coverage — orchestration entrypoint with all I/O patched.
|
|
|
|
`main()` wires database init, event-bus init, websocket-bridge,
|
|
orchestrator startup, and the uvicorn API server. Every external call gets
|
|
patched so the tests run in milliseconds without a real Redis/Postgres/HTTP
|
|
stack. Helpers `_run_api_server` and `_wait_for_api_ready` get their own
|
|
isolated checks.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import runpy
|
|
from http import HTTPStatus
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
from roboco.bootstrap import (
|
|
_BootstrapHolder,
|
|
_run_api_server,
|
|
_wait_for_api_ready,
|
|
main,
|
|
)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _run_api_server
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_api_server_starts_uvicorn() -> None:
|
|
"""_run_api_server constructs a uvicorn Config + Server and serves."""
|
|
server_instance = MagicMock()
|
|
server_instance.serve = AsyncMock()
|
|
with (
|
|
patch("roboco.bootstrap.uvicorn.Config") as cfg_cls,
|
|
patch("roboco.bootstrap.uvicorn.Server", return_value=server_instance),
|
|
):
|
|
await _run_api_server()
|
|
cfg_cls.assert_called_once()
|
|
server_instance.serve.assert_awaited_once()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _wait_for_api_ready
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_wait_for_api_ready_returns_when_health_ok() -> None:
|
|
"""200 from /health → return immediately."""
|
|
response = MagicMock()
|
|
response.status_code = HTTPStatus.OK
|
|
client_instance = MagicMock()
|
|
client_instance.get = AsyncMock(return_value=response)
|
|
client_instance.__aenter__ = AsyncMock(return_value=client_instance)
|
|
client_instance.__aexit__ = AsyncMock(return_value=False)
|
|
with patch("roboco.bootstrap.httpx.AsyncClient", return_value=client_instance):
|
|
await _wait_for_api_ready(max_wait=4)
|
|
client_instance.get.assert_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_wait_for_api_ready_swallows_errors_and_times_out() -> None:
|
|
"""Connection errors are swallowed; loop times out and warns."""
|
|
client_instance = MagicMock()
|
|
client_instance.get = AsyncMock(side_effect=ConnectionError("boom"))
|
|
client_instance.__aenter__ = AsyncMock(return_value=client_instance)
|
|
client_instance.__aexit__ = AsyncMock(return_value=False)
|
|
sleep_mock = AsyncMock()
|
|
with (
|
|
patch("roboco.bootstrap.httpx.AsyncClient", return_value=client_instance),
|
|
patch("roboco.bootstrap.asyncio.sleep", sleep_mock),
|
|
):
|
|
await _wait_for_api_ready(max_wait=4)
|
|
# Loop ran a couple of iterations (2s each) before timing out.
|
|
assert sleep_mock.await_count >= 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_wait_for_api_ready_keeps_polling_on_non_200() -> None:
|
|
"""Non-200 status → keep polling until max_wait."""
|
|
response = MagicMock()
|
|
response.status_code = HTTPStatus.SERVICE_UNAVAILABLE
|
|
client_instance = MagicMock()
|
|
client_instance.get = AsyncMock(return_value=response)
|
|
client_instance.__aenter__ = AsyncMock(return_value=client_instance)
|
|
client_instance.__aexit__ = AsyncMock(return_value=False)
|
|
with (
|
|
patch("roboco.bootstrap.httpx.AsyncClient", return_value=client_instance),
|
|
patch("roboco.bootstrap.asyncio.sleep", AsyncMock()),
|
|
):
|
|
await _wait_for_api_ready(max_wait=4)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# main()
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _make_main_patches(*, raise_on_spawn: bool = False) -> tuple[Any, Any, Any]:
|
|
"""Bundle the heavy IO mocks main() needs.
|
|
|
|
Returns a context manager and the orchestrator mock so the test can
|
|
inspect calls afterward.
|
|
"""
|
|
orchestrator_mock = MagicMock()
|
|
orchestrator_mock.start = AsyncMock()
|
|
orchestrator_mock.stop = AsyncMock()
|
|
if raise_on_spawn:
|
|
orchestrator_mock.spawn_agent = AsyncMock(side_effect=RuntimeError("boom"))
|
|
else:
|
|
orchestrator_mock.spawn_agent = AsyncMock()
|
|
|
|
event_bus_mock = MagicMock()
|
|
event_bus_mock.start_listening = AsyncMock()
|
|
event_bus_mock.disconnect = AsyncMock()
|
|
|
|
api_task_mock = AsyncMock() # api_task awaited inside main
|
|
|
|
return orchestrator_mock, event_bus_mock, api_task_mock
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_skip_orchestrator_returns_after_db_bootstrap() -> None:
|
|
"""skip_orchestrator=True → only DB bootstrap runs, then early return."""
|
|
db_mock = AsyncMock()
|
|
with (
|
|
patch("roboco.bootstrap.bootstrap_database", db_mock),
|
|
patch("roboco.bootstrap.init_event_bus") as bus,
|
|
):
|
|
await main(skip_orchestrator=True)
|
|
db_mock.assert_awaited_once()
|
|
bus.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_skip_db_skips_database_bootstrap() -> None:
|
|
"""skip_db=True → bootstrap_database not called, but rest still runs."""
|
|
db_mock = AsyncMock()
|
|
with (
|
|
patch("roboco.bootstrap.bootstrap_database", db_mock),
|
|
# Skip orchestrator so we exit early — we just want to verify db
|
|
# bootstrap path.
|
|
patch("roboco.bootstrap.init_event_bus") as bus,
|
|
):
|
|
await main(skip_db=True, skip_orchestrator=True)
|
|
db_mock.assert_not_called()
|
|
bus.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_full_path_starts_orchestrator_and_shuts_down() -> None:
|
|
"""Happy path: bootstrap, init bus, start orchestrator, await api task."""
|
|
orch, bus, _ = _make_main_patches()
|
|
|
|
with (
|
|
patch("roboco.bootstrap.bootstrap_database", AsyncMock()),
|
|
patch("roboco.bootstrap.init_event_bus", AsyncMock(return_value=bus)),
|
|
patch("roboco.bootstrap.register_default_handlers"),
|
|
patch("roboco.bootstrap.start_websocket_bridge", AsyncMock()),
|
|
patch("roboco.bootstrap.AgentOrchestrator", return_value=orch),
|
|
patch("roboco.bootstrap.set_orchestrator"),
|
|
patch("roboco.bootstrap.NotificationService"),
|
|
patch("roboco.bootstrap.set_event_context"),
|
|
patch("roboco.bootstrap.set_reasoning_stream_callback"),
|
|
patch("roboco.bootstrap._wait_for_api_ready", AsyncMock()),
|
|
# Replace _run_api_server with an AsyncMock that returns immediately;
|
|
# create_task wraps the coroutine into a real Task that completes
|
|
# without warnings.
|
|
patch("roboco.bootstrap._run_api_server", AsyncMock(return_value=None)),
|
|
):
|
|
await main()
|
|
|
|
orch.start.assert_awaited_once()
|
|
orch.stop.assert_awaited_once()
|
|
bus.start_listening.assert_awaited_once()
|
|
bus.disconnect.assert_awaited_once()
|
|
assert _BootstrapHolder.orchestrator is None # Cleared in finally.
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_spawns_requested_agents() -> None:
|
|
"""spawn_agents list → orchestrator.spawn_agent called for each."""
|
|
orch, bus, _ = _make_main_patches()
|
|
|
|
with (
|
|
patch("roboco.bootstrap.bootstrap_database", AsyncMock()),
|
|
patch("roboco.bootstrap.init_event_bus", AsyncMock(return_value=bus)),
|
|
patch("roboco.bootstrap.register_default_handlers"),
|
|
patch("roboco.bootstrap.start_websocket_bridge", AsyncMock()),
|
|
patch("roboco.bootstrap.AgentOrchestrator", return_value=orch),
|
|
patch("roboco.bootstrap.set_orchestrator"),
|
|
patch("roboco.bootstrap.NotificationService"),
|
|
patch("roboco.bootstrap.set_event_context"),
|
|
patch("roboco.bootstrap.set_reasoning_stream_callback"),
|
|
patch("roboco.bootstrap._wait_for_api_ready", AsyncMock()),
|
|
patch("roboco.bootstrap._run_api_server", AsyncMock(return_value=None)),
|
|
):
|
|
await main(spawn_agents=["be-dev-1", "fe-dev-1"])
|
|
|
|
_EXPECTED_SPAWNS = 2
|
|
assert orch.spawn_agent.await_count == _EXPECTED_SPAWNS
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_logs_and_continues_when_spawn_fails() -> None:
|
|
"""spawn_agent failure logs error but doesn't abort startup."""
|
|
orch, bus, _ = _make_main_patches(raise_on_spawn=True)
|
|
|
|
with (
|
|
patch("roboco.bootstrap.bootstrap_database", AsyncMock()),
|
|
patch("roboco.bootstrap.init_event_bus", AsyncMock(return_value=bus)),
|
|
patch("roboco.bootstrap.register_default_handlers"),
|
|
patch("roboco.bootstrap.start_websocket_bridge", AsyncMock()),
|
|
patch("roboco.bootstrap.AgentOrchestrator", return_value=orch),
|
|
patch("roboco.bootstrap.set_orchestrator"),
|
|
patch("roboco.bootstrap.NotificationService"),
|
|
patch("roboco.bootstrap.set_event_context"),
|
|
patch("roboco.bootstrap.set_reasoning_stream_callback"),
|
|
patch("roboco.bootstrap._wait_for_api_ready", AsyncMock()),
|
|
patch("roboco.bootstrap._run_api_server", AsyncMock(return_value=None)),
|
|
):
|
|
# Should not raise — error is caught + logged.
|
|
await main(spawn_agents=["broken-agent"])
|
|
|
|
orch.spawn_agent.assert_awaited_once()
|
|
orch.stop.assert_awaited_once() # Cleanup still ran.
|
|
|
|
|
|
def test_module_run_as_script_invokes_cli() -> None:
|
|
"""`python -m roboco.bootstrap` → calls `roboco.cli.cli()`."""
|
|
cli_mock = MagicMock()
|
|
with patch.dict(
|
|
"sys.modules",
|
|
{"roboco.cli": MagicMock(cli=cli_mock)},
|
|
):
|
|
runpy.run_module("roboco.bootstrap", run_name="__main__")
|
|
cli_mock.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_handles_api_task_cancellation() -> None:
|
|
"""If api_task is cancelled, finally block still runs cleanup."""
|
|
orch, bus, _ = _make_main_patches()
|
|
|
|
async def _raise_cancelled() -> None:
|
|
raise asyncio.CancelledError()
|
|
|
|
with (
|
|
patch("roboco.bootstrap.bootstrap_database", AsyncMock()),
|
|
patch("roboco.bootstrap.init_event_bus", AsyncMock(return_value=bus)),
|
|
patch("roboco.bootstrap.register_default_handlers"),
|
|
patch("roboco.bootstrap.start_websocket_bridge", AsyncMock()),
|
|
patch("roboco.bootstrap.AgentOrchestrator", return_value=orch),
|
|
patch("roboco.bootstrap.set_orchestrator"),
|
|
patch("roboco.bootstrap.NotificationService"),
|
|
patch("roboco.bootstrap.set_event_context"),
|
|
patch("roboco.bootstrap.set_reasoning_stream_callback"),
|
|
patch("roboco.bootstrap._wait_for_api_ready", AsyncMock()),
|
|
patch("roboco.bootstrap._run_api_server", _raise_cancelled),
|
|
):
|
|
await main()
|
|
|
|
# Cleanup ran despite cancellation.
|
|
orch.stop.assert_awaited_once()
|
|
bus.disconnect.assert_awaited_once()
|