open-swe/tests/test_corridor_mcp.py

181 lines
5.6 KiB
Python
Raw Normal View History

from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent import server
from agent.integrations import corridor_mcp
class _FakeTool:
def __init__(self, name: str) -> None:
self.name = name
@pytest.fixture(autouse=True)
def clear_corridor_env(monkeypatch: pytest.MonkeyPatch) -> None:
for name in (
"CORRIDOR_API_TOKEN",
"CORRIDOR_MCP_TOKEN",
"CORRIDOR_TOKEN",
"CORRIDOR_MCP_URL",
"CORRIDOR_MCP_SERVER_URL",
):
monkeypatch.delenv(name, raising=False)
def test_load_corridor_mcp_config_empty_without_token() -> None:
assert corridor_mcp.load_corridor_mcp_config() is None
def test_load_corridor_mcp_config_uses_default_url(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("CORRIDOR_API_TOKEN", "tok")
config = corridor_mcp.load_corridor_mcp_config()
assert config == corridor_mcp.CorridorMCPConfig(
url=corridor_mcp.DEFAULT_CORRIDOR_MCP_URL,
token="tok",
)
def test_load_corridor_mcp_config_accepts_query_token(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("CORRIDOR_MCP_URL", "https://app.corridor.dev/api/mcp?token=tok")
config = corridor_mcp.load_corridor_mcp_config()
assert config == corridor_mcp.CorridorMCPConfig(
url=corridor_mcp.DEFAULT_CORRIDOR_MCP_URL,
token="tok",
)
def test_load_corridor_mcp_config_rejects_non_corridor_url(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("CORRIDOR_API_TOKEN", "tok")
monkeypatch.setenv("CORRIDOR_MCP_URL", "https://example.com/api/mcp")
assert corridor_mcp.load_corridor_mcp_config() is None
@pytest.mark.asyncio
async def test_load_corridor_tools_empty_when_not_configured() -> None:
assert await corridor_mcp.load_corridor_tools() == []
@pytest.mark.asyncio
async def test_load_corridor_tools_degrades_on_error(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("CORRIDOR_API_TOKEN", "tok")
with patch.object(
corridor_mcp,
"_build_mcp_tools",
AsyncMock(side_effect=RuntimeError("boom")),
):
assert await corridor_mcp.load_corridor_tools() == []
@pytest.mark.asyncio
async def test_load_corridor_tools_returns_tools(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("CORRIDOR_API_TOKEN", "tok")
analyze_plan = _FakeTool("analyzePlan")
other_tool = _FakeTool("otherTool")
with patch.object(
corridor_mcp,
"_build_mcp_tools",
AsyncMock(return_value=[other_tool, analyze_plan]),
):
assert await corridor_mcp.load_corridor_tools() == [analyze_plan]
@pytest.mark.asyncio
async def test_server_load_corridor_mcp_tools() -> None:
with patch.object(server, "load_corridor_tools", AsyncMock(return_value=["corridor"])):
assert await server._load_corridor_mcp_tools() == ["corridor"]
@pytest.mark.asyncio
async def test_server_load_corridor_mcp_tools_degrades_on_error() -> None:
with patch.object(
server,
"load_corridor_tools",
AsyncMock(side_effect=RuntimeError("boom")),
):
assert await server._load_corridor_mcp_tools() == []
@pytest.mark.asyncio
async def test_get_agent_passes_corridor_prompt_state() -> None:
config = {
"configurable": {
"__is_for_execution__": True,
"thread_id": "thread-123",
},
"metadata": {},
}
def fake_create_deep_agent(**_kwargs):
class _DummyAgent:
def with_config(self, _config):
return self
return _DummyAgent()
async def run_with_corridor_tools(corridor_tools: list[object]) -> bool:
with (
patch.object(
server,
"resolve_github_token",
new_callable=AsyncMock,
return_value=("ghp", None),
),
patch.object(server, "resolve_triggering_user_identity", return_value=None),
patch.object(
server,
"ensure_sandbox_for_thread",
new_callable=AsyncMock,
return_value=MagicMock(),
),
patch.object(
server,
"aresolve_sandbox_work_dir",
new_callable=AsyncMock,
return_value="/workspace",
),
patch.object(
server,
"get_team_default_model_pair",
new_callable=AsyncMock,
return_value=(("openai:gpt-5.5", "medium"), ("openai:gpt-5.5", "low")),
),
patch.object(server, "fallback_model_id_for", return_value=None),
feat: port durable dispatch hardening and startup latency improvements (#160) * feat: port plan-review & workflow-approval UX (#135) Port six upstream commits onto dev: - c03a6be7 (already ported): keep plan guidance high-level - 546042a4: add workflow approval UI with diff preview, approval URLs, web review links, and polling for approval status during active runs - 216cf181: remove workflow token elevation; approved pushes pass through directly without proxy token rewriting - 3dbc0282: preserve plan redirects after login by accepting relative same-origin redirect_to values and rejecting blocked paths - bb104d93: submit plan comments with cmd+enter - 90cb6caa: terse Slack replies, shared content via save_plan outside plan mode (PLAN_STATUS_SHARED), reject shared-content mutations Refs: #135 * feat: port durable dispatch hardening and startup latency improvements Port five upstream PRs onto dev: - #1621 / #1658: durable dispatch with loopback webhook defense, create_durable_run helper, _config_with_prepare_run_id, degradation to None for relative/loopback completion webhook URLs - #1696: run-level completion webhook deduplication (replace claim-then-post with post-then-flag per run_id), DeferredErrorModel for graph-factory resilience, ToolRetryMiddleware for task subagents, TimeoutWrapupMiddleware for all three graphs - #1697: lazy-load __init__.py for agent.middleware, agent.tools, agent.dashboard (PEP 562); defer heavy imports (exa_py in web_search, agent.webapp in request_pr_review, deepagents in sandbox.py); add ttl_cache.py with stale-while-revalidate for tool loaders Refs: #137 * fix: restore login page render and clear CI lint/format The plan-review port removed the authRedirectUrl import from login.tsx but left its call site, crashing the login page at runtime (blank page, no 'Sign in to open-swe'). Pass the relative path straight to loginUrl, matching the plan route and the backend relative-redirect handling. Also drop an unused os import in the guard test and reformat workflow_push_guard.py to satisfy ruff. * fix: restore RepairOrphaned middleware export and repoint model fake to deferred_model boundary * fix: restore RepairOrphanedToolCallsMiddleware, fix E2E model-fake patch, drop dead ttl_cache - Re-add RepairOrphanedToolCallsMiddleware to the lazy middleware __init__ (_MIDDLEWARE_MODULES, __all__, TYPE_CHECKING) so agent.reviewer can import it. - Reroute E2E model patching to deferred_model.make_model so make_model_or_defer (used by all three graph factories) returns the scripted fake instead of building a real model with fake credentials. - Drop unused agent/utils/ttl_cache.py — no agent module imports it. - Fix import ordering in agent/reviewer.py and agent/analyzer.py (ruff I001). - Format tests/test_dispatch.py. * fix: claim-then-post run-level failure dedup; stop permanent suppression --------- Co-authored-by: amoussa1229 <166072409+amoussa1229@users.noreply.github.com> Co-authored-by: Adam Moussa <adam@seahavenind.com>
2026-07-09 17:11:25 -04:00
patch("agent.utils.deferred_model.make_model", return_value=MagicMock()),
patch.object(
server, "_load_observability_tools", new_callable=AsyncMock, return_value=[]
),
patch.object(
server,
"_observability_authorized",
new_callable=AsyncMock,
return_value=False,
),
patch.object(
server,
"_load_corridor_mcp_tools",
new_callable=AsyncMock,
return_value=corridor_tools,
),
patch.object(server, "construct_system_prompt", return_value="prompt") as prompt,
patch.object(server, "create_deep_agent", side_effect=fake_create_deep_agent),
):
await server.get_agent(config)
return bool(prompt.call_args.kwargs["corridor_enabled"])
assert await run_with_corridor_tools([]) is False
assert await run_with_corridor_tools([_FakeTool("analyzePlan")]) is True