Files
hermes-agent/tests/gateway/test_yuanbao_reconnect_set_active.py
teknium1 d10bb2ab6f test: make tests/ mirror the source tree; drop issue numbers from filenames
`scripts/run_tests.sh tests/<dir>/` is how a change gets its regression
coverage run, so a test filed under the wrong directory is a test nobody
runs when that code changes. Two kinds of drift had accumulated.

Parallel directories for one source package, folded into the mirror:
  tests/acp        -> tests/acp_adapter   (its __init__/conftest move with it)
  tests/cli        -> tests/hermes_cli    (prompt_toolkit fixture merged into
                                           hermes_cli/conftest.py)
  tests/run_agent  -> tests/agent         (backoff fixture becomes
                                           agent/conftest.py)
  tests/relay      -> tests/gateway/relay
  tests/state      -> tests/hermes_state

246 loose files at tests/ root, routed by the package they import/patch:
hermes_cli, hermes_state, agent, gateway, tools, plugins, tui_gateway, cron.
Installer and desktop-update script tests go to tests/scripts/{install,
desktop_update}/. 43 tests of root-level modules (batch_runner, utils,
hermes_constants, packaging) stay at the root.

Filenames drop their issue numbers (95 files: test_89315_x.py -> test_x.py);
the number stays in the module docstring where it has context.

Collisions: test_cli_skin_integration.py existed in both tests/ and tests/cli
with different subsets — merged into one (10 tests, all kept);
run_agent/test_pre_compress_memory_context.py -> agent/..._handoff.py;
tests/test_account_usage.py -> agent/test_account_usage_fetch.py;
tests/test_web_server.py -> hermes_cli/test_web_server_ws_ping.py.
Deleted: test_minisweagent_path.py (empty since PR #2804),
test_model_picker_scroll.py (tested a private copy of the logic, imported
nothing), test_process_loop_event_loop_warning.py (asserted asyncio behaviour,
imported nothing from Hermes).

Repo-root path arithmetic (Path(__file__).parents[N], dirname chains) is
bumped for the 202 files that changed depth and verified by evaluating every
such expression against the new location. classify_changes' desktop-updater
lane prefix, tests-os.yml's ignore glob and every in-tree path comment follow
the moves. tests/test_tests_tree_layout.py keeps the tree from drifting back.
2026-09-13 09:18:02 -07:00

106 lines
3.6 KiB
Python

"""test_yuanbao_reconnect_set_active.py - Verify _do_reconnect restores the active singleton.
Regression test for #58363: after a WS disconnect/reconnect cycle,
``YuanbaoAdapter.get_active()`` must return the live adapter (not ``None``).
The original ``_do_reconnect()`` succeeded but never called
``YuanbaoAdapter.set_active()``, leaving the singleton permanently
``None`` until a full gateway restart.
"""
import sys
import os
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if _REPO_ROOT not in sys.path:
sys.path.insert(0, _REPO_ROOT)
import pytest
from gateway.platforms.yuanbao import (
YuanbaoAdapter,
ConnectionManager,
)
def _make_adapter(**kwargs):
"""Create a minimal YuanbaoAdapter mock."""
adapter = MagicMock(spec=YuanbaoAdapter)
adapter.name = "yuanbao"
adapter._app_key = "test_key"
adapter._app_secret = "test_secret"
adapter._api_domain = "https://test.example.com"
adapter._route_env = None
adapter._bot_id = "test_bot"
adapter._ws_url = "wss://test.example.com/ws"
adapter._mark_connected = MagicMock()
adapter._mark_disconnected = MagicMock()
adapter._release_platform_lock = MagicMock()
return adapter
@pytest.mark.asyncio
async def test_do_reconnect_calls_set_active_on_success():
"""After a successful reconnect, set_active(adapter) must be called."""
adapter = _make_adapter()
cm = ConnectionManager(adapter)
# Mock the reconnect internals to succeed on first attempt
mock_ws = AsyncMock()
mock_ws.close = AsyncMock()
with (
patch.object(cm, "_cleanup_ws", new_callable=AsyncMock) as mock_cleanup,
patch(
"gateway.platforms.yuanbao.SignManager.force_refresh",
new_callable=AsyncMock,
return_value={"bot_id": "test_bot", "token": "test_token"},
),
patch("gateway.platforms.yuanbao.websockets.connect", new_callable=AsyncMock, return_value=mock_ws),
patch.object(cm, "_authenticate", new_callable=AsyncMock, return_value=True),
patch.object(cm, "_heartbeat_loop", new_callable=AsyncMock),
patch.object(cm, "_receive_loop", new_callable=AsyncMock),
patch("gateway.platforms.yuanbao.MAX_RECONNECT_ATTEMPTS", 1),
):
# Clear any existing active instance
YuanbaoAdapter.set_active(None)
assert YuanbaoAdapter.get_active() is None
# Run reconnect
result = await cm._do_reconnect()
# Reconnect should succeed
assert result is True
# After successful reconnect, get_active() must return the adapter
assert YuanbaoAdapter.get_active() is adapter
@pytest.mark.asyncio
async def test_do_reconnect_does_not_set_active_on_failure():
"""When all reconnect attempts fail, set_active should NOT be called."""
adapter = _make_adapter()
cm = ConnectionManager(adapter)
with (
patch.object(cm, "_cleanup_ws", new_callable=AsyncMock),
patch(
"gateway.platforms.yuanbao.SignManager.force_refresh",
new_callable=AsyncMock,
side_effect=Exception("auth failed"),
),
patch("gateway.platforms.yuanbao.MAX_RECONNECT_ATTEMPTS", 1),
):
# Clear any existing active instance
YuanbaoAdapter.set_active(None)
assert YuanbaoAdapter.get_active() is None
# Run reconnect - should fail
result = await cm._do_reconnect()
# Reconnect should fail
assert result is False
# get_active() should still be None
assert YuanbaoAdapter.get_active() is None