refactor: remove redundant comments and docstrings (#6527)
* refactor: remove redundant comments and docstrings * fix(signal): annotate async context manager as a generator
This commit is contained in:
1 parent
cb3ba45317
commit
a4d2430140
922 files changed
+406
-7738
No files matched your search
@@ -1,5 +1,3 @@
|
||||
"""Shared contract tests for self-contained channel packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Channel transports decide whether to render compaction lifecycle events."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -87,7 +85,6 @@ async def test_dispatch_forwards_all_compaction_phases_before_adapter_filtering(
|
||||
with suppress(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, timeout=2)
|
||||
|
||||
# The recorder sees the manager -> adapter boundary, not a fake presentation rule.
|
||||
received = [call.args[0] for call in channel._send_mock.await_args_list]
|
||||
assert received == [*messages, final]
|
||||
assert [msg.event for msg in received] == [*events, None]
|
||||
@@ -113,7 +110,6 @@ def test_global_notice_config_round_trip_and_rebuild(manager):
|
||||
manager.config = Config.model_validate({"channels": {"showCompactionNotices": True}})
|
||||
manager.config = Config.model_validate_json(manager.config.model_dump_json(by_alias=True))
|
||||
assert manager._build_channel(_MockChannel, {}).show_compaction_notices is True
|
||||
# Rebuilding an adapter after a config change must resolve the new default.
|
||||
manager.config.channels.show_compaction_notices = False
|
||||
assert manager._build_channel(_MockChannel, {}).show_compaction_notices is False
|
||||
assert manager._build_channel(
|
||||
|
||||
@@ -179,7 +179,6 @@ async def test_pending_and_concurrent_sends_are_bounded_and_cancellable(monkeypa
|
||||
assert active == 0
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
# Cancellation returns admission permits, including tasks not yet sending.
|
||||
for i in range(4):
|
||||
await asyncio.wait_for(manager._queue_outbound(
|
||||
channel, OutboundMessage("websocket", str(i), "b"),
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for ChannelManager delta coalescing to reduce streaming latency."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from copy import deepcopy
|
||||
@@ -111,7 +109,6 @@ def _end(
|
||||
|
||||
|
||||
class TestDeltaCoalescing:
|
||||
"""Tests for stream delta message coalescing."""
|
||||
|
||||
async def test_response_source_change_is_a_coalescing_boundary(self, manager, bus):
|
||||
first, second = _delta("primary"), _delta("backup")
|
||||
@@ -232,7 +229,6 @@ class TestDeltaCoalescing:
|
||||
|
||||
|
||||
class TestDispatchOutboundWithCoalescing:
|
||||
"""Tests for the full _dispatch_outbound flow with coalescing."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("end_stream", [False, True])
|
||||
@@ -281,7 +277,6 @@ class TestDispatchOutboundWithCoalescing:
|
||||
|
||||
|
||||
class TestProgressFiltering:
|
||||
"""Progress filtering should honor per-channel settings."""
|
||||
|
||||
def test_progress_visibility_uses_global_defaults(self, manager):
|
||||
assert manager._should_send_progress("mock", tool_hint=False) is True
|
||||
@@ -475,7 +470,6 @@ class TestToolEventDelivery:
|
||||
|
||||
|
||||
class TestRetryWaitFiltering:
|
||||
"""Internal provider retry heartbeats must never reach channels."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_retry_wait_message_dropped(self, manager, bus):
|
||||
|
||||
@@ -137,7 +137,6 @@ async def test_reasoning_end_routes_to_send_reasoning_end(manager):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_shot_reasoning_expands_to_delta_plus_end(manager):
|
||||
"""One-shot reasoning expands to a single delta + end."""
|
||||
channel = manager.channels["mock"]
|
||||
msg = outbound_message_for_event(
|
||||
channel="mock",
|
||||
@@ -206,7 +205,6 @@ async def test_dispatch_silently_drops_reasoning_for_unknown_channel(manager):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_base_channel_reasoning_primitives_are_noop_safe():
|
||||
"""Plugins that don't override the streaming primitives must not blow up."""
|
||||
|
||||
class _Plain(BaseChannel):
|
||||
name = "plain"
|
||||
@@ -224,7 +222,6 @@ async def test_base_channel_reasoning_primitives_are_noop_safe():
|
||||
channel = _Plain({}, MessageBus())
|
||||
assert await channel.send_reasoning_delta("c", "x") is None
|
||||
assert await channel.send_reasoning_end("c") is None
|
||||
# And the one-shot wrapper translates without raising.
|
||||
assert await channel.send_reasoning(
|
||||
OutboundMessage(channel="plain", chat_id="c", content="x", metadata={})
|
||||
) is None
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for channel package discovery, management, and config behavior."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -41,9 +39,6 @@ from nanobot.providers.transcription import GroqTranscriptionProvider as _GroqPr
|
||||
from nanobot.providers.transcription import OpenAITranscriptionProvider as _OpenAIProvider
|
||||
from nanobot.utils.restart import RestartNotice
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _FakePlugin(BaseChannel):
|
||||
name = "fakeplugin"
|
||||
@@ -244,10 +239,6 @@ def _stub_optional_feature_cli(
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ChannelsConfig extra="allow"
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_channels_config_accepts_unknown_keys():
|
||||
cfg = ChannelsConfig.model_validate({
|
||||
"myplugin": {"enabled": True, "token": "abc"},
|
||||
@@ -542,10 +533,6 @@ def test_channel_manager_preserves_single_instance_plugin_owned_instances(monkey
|
||||
assert manager.channels["fakeplugin"].config["instances"] == ["plugin-owned-value"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Channel package discovery
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_discover_plugins_loads_package_descriptors():
|
||||
from nanobot.channels.registry import discover_plugins
|
||||
|
||||
@@ -842,18 +829,11 @@ def test_discover_plugins_handles_load_error():
|
||||
assert "broken" not in result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Runtime discovery
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_discover_all_includes_available_channel_packages():
|
||||
from nanobot.channels.registry import discover_all, discover_plugins
|
||||
|
||||
result = discover_all()
|
||||
|
||||
# discover_all() only returns channels that are actually available (dependencies installed)
|
||||
# discover_plugins() returns all channel package descriptors
|
||||
# So we check that all actually loaded channels are in the result
|
||||
for name in result:
|
||||
assert name in discover_plugins()
|
||||
|
||||
@@ -908,13 +888,8 @@ def test_discover_enabled_warns_for_enabled_package_import_errors():
|
||||
assert "missing" in str(warning.call_args.args[2])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Manager _init_channels with dict config
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("proxy", ["", "http://127.0.0.1:7890"])
|
||||
def test_manager_loads_plugin_from_dict_config(monkeypatch, proxy):
|
||||
"""Existing two-argument plugins work with or without a shared proxy configured."""
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
|
||||
fake_config = Config.model_validate({
|
||||
@@ -1047,7 +1022,6 @@ async def test_base_channel_reads_current_transcription_config_each_call(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""BaseChannel.transcribe_audio resolves config at call time, not manager init time."""
|
||||
from nanobot.providers import transcription as transcription_mod
|
||||
|
||||
config_path = tmp_path / "config.json"
|
||||
@@ -1154,11 +1128,6 @@ def test_openai_transcription_provider_honors_api_base_argument():
|
||||
assert custom.api_url == "http://override/v1/audio/transcriptions"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Transcription provider HTTP tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _StubResponse:
|
||||
status_code = 200
|
||||
|
||||
@@ -1192,7 +1161,6 @@ def _stub_async_client(captured: dict[str, object]):
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_transcription_provider_includes_language(tmp_path, provider_cls, language):
|
||||
"""Provider must include the 'language' field in multipart body when set."""
|
||||
audio = tmp_path / "sample.wav"
|
||||
audio.write_bytes(b"audio")
|
||||
captured: dict[str, object] = {}
|
||||
@@ -1212,7 +1180,6 @@ async def test_transcription_provider_includes_language(tmp_path, provider_cls,
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_transcription_provider_omits_language_when_none(tmp_path, provider_cls):
|
||||
"""When language is not set, the 'language' key must be absent from the multipart body."""
|
||||
audio = tmp_path / "sample.wav"
|
||||
audio.write_bytes(b"audio")
|
||||
captured: dict[str, object] = {}
|
||||
@@ -2119,7 +2086,7 @@ def test_live_runtime_status_overrides_enabled_configuration_for_webui():
|
||||
decorated = with_channel_runtime_status(payload, runtime_status)
|
||||
|
||||
feature = decorated["features"][0]
|
||||
assert feature["enabled"] is True # desired config remains visible to actions
|
||||
assert feature["enabled"] is True
|
||||
assert feature["running"] is False
|
||||
assert feature["ready"] is False
|
||||
assert feature["runtime_status"] == "failed"
|
||||
@@ -2646,8 +2613,6 @@ def test_optional_dependency_metadata_for_enable():
|
||||
|
||||
assert "boto3>=1.43.0" not in data["project"]["dependencies"]
|
||||
assert deps["bedrock"] == ["boto3>=1.43.0", "botocore>=1.43.0,<2.0.0"]
|
||||
# The built-in remote WebUI proxy now needs aiohttp even without channels.
|
||||
# Keep the historical API extra installable for existing deployment commands.
|
||||
assert "aiohttp>=3.14.3,<4.0.0" in required
|
||||
assert deps["api"] == ["aiohttp>=3.9.0,<4.0.0"]
|
||||
for dep_name in (
|
||||
@@ -2892,12 +2857,7 @@ async def test_manager_skips_disabled_channel_package(monkeypatch):
|
||||
assert "fakeplugin" not in mgr.channels
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Channel default_config() and dict-to-Pydantic conversion
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_channel_default_config():
|
||||
"""Channels expose default_config() returning a dict with 'enabled': False."""
|
||||
from nanobot.channels.dingtalk.runtime import DingTalkChannel
|
||||
cfg = DingTalkChannel.default_config()
|
||||
assert isinstance(cfg, dict)
|
||||
@@ -2906,7 +2866,6 @@ def test_channel_default_config():
|
||||
|
||||
|
||||
def test_channel_init_from_dict():
|
||||
"""Channels accept a raw dict and convert to Pydantic internally."""
|
||||
from nanobot.channels.dingtalk.runtime import DingTalkChannel
|
||||
bus = MessageBus()
|
||||
ch = DingTalkChannel({"enabled": False, "clientId": "test-id", "allowFrom": ["*"]}, bus)
|
||||
@@ -2915,61 +2874,47 @@ def test_channel_init_from_dict():
|
||||
|
||||
|
||||
def test_channels_config_send_max_retries_default():
|
||||
"""ChannelsConfig should have send_max_retries with default value of 3."""
|
||||
cfg = ChannelsConfig()
|
||||
assert hasattr(cfg, 'send_max_retries')
|
||||
assert cfg.send_max_retries == 3
|
||||
|
||||
|
||||
def test_channels_config_send_max_retries_upper_bound():
|
||||
"""send_max_retries should be bounded to prevent resource exhaustion."""
|
||||
from pydantic import ValidationError
|
||||
|
||||
# Value too high should be rejected
|
||||
with pytest.raises(ValidationError):
|
||||
ChannelsConfig(send_max_retries=100)
|
||||
|
||||
# Negative should be rejected
|
||||
with pytest.raises(ValidationError):
|
||||
ChannelsConfig(send_max_retries=-1)
|
||||
|
||||
# Boundary values should be allowed
|
||||
cfg_min = ChannelsConfig(send_max_retries=0)
|
||||
assert cfg_min.send_max_retries == 0
|
||||
|
||||
cfg_max = ChannelsConfig(send_max_retries=10)
|
||||
assert cfg_max.send_max_retries == 10
|
||||
|
||||
# Value above upper bound should be rejected
|
||||
with pytest.raises(ValidationError):
|
||||
ChannelsConfig(send_max_retries=11)
|
||||
|
||||
|
||||
def test_channels_config_transcription_language_pattern():
|
||||
"""transcription_language must match ISO-639 format (2-3 lowercase letters) or be None."""
|
||||
from pydantic import ValidationError
|
||||
|
||||
# Valid values
|
||||
assert ChannelsConfig(transcription_language="en").transcription_language == "en"
|
||||
assert ChannelsConfig(transcription_language="kor").transcription_language == "kor"
|
||||
assert ChannelsConfig(transcription_language=None).transcription_language is None
|
||||
|
||||
# Invalid values
|
||||
with pytest.raises(ValidationError):
|
||||
ChannelsConfig(transcription_language="EN") # uppercase
|
||||
ChannelsConfig(transcription_language="EN")
|
||||
with pytest.raises(ValidationError):
|
||||
ChannelsConfig(transcription_language="english") # full word
|
||||
ChannelsConfig(transcription_language="english")
|
||||
with pytest.raises(ValidationError):
|
||||
ChannelsConfig(transcription_language="en-US") # BCP 47 tag
|
||||
ChannelsConfig(transcription_language="en-US")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _send_with_retry
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_retry_succeeds_first_try():
|
||||
"""_send_with_retry should succeed on first try and not retry."""
|
||||
call_count = 0
|
||||
|
||||
class _FailingChannel(BaseChannel):
|
||||
@@ -2985,7 +2930,6 @@ async def test_send_with_retry_succeeds_first_try():
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
# Succeeds on first try
|
||||
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(send_max_retries=3),
|
||||
@@ -3007,7 +2951,6 @@ async def test_send_with_retry_succeeds_first_try():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_retry_retries_on_failure():
|
||||
"""_send_with_retry should retry on failure up to max_retries times."""
|
||||
call_count = 0
|
||||
|
||||
class _FailingChannel(BaseChannel):
|
||||
@@ -3039,17 +2982,15 @@ async def test_send_with_retry_retries_on_failure():
|
||||
|
||||
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
|
||||
|
||||
# Patch asyncio.sleep to avoid actual delays
|
||||
with patch("nanobot.channels.manager.asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
|
||||
await mgr._send_with_retry(mgr.channels["failing"], msg)
|
||||
|
||||
assert call_count == 3 # 3 total attempts (initial + 2 retries)
|
||||
assert mock_sleep.call_count == 2 # 2 sleeps between retries
|
||||
assert call_count == 3
|
||||
assert mock_sleep.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_retry_no_retry_when_max_is_zero():
|
||||
"""_send_with_retry should not retry when send_max_retries is 0."""
|
||||
call_count = 0
|
||||
|
||||
class _FailingChannel(BaseChannel):
|
||||
@@ -3084,12 +3025,11 @@ async def test_send_with_retry_no_retry_when_max_is_zero():
|
||||
with patch("nanobot.channels.manager.asyncio.sleep", new_callable=AsyncMock):
|
||||
await mgr._send_with_retry(mgr.channels["failing"], msg)
|
||||
|
||||
assert call_count == 1 # Called once but no retry (max(0, 1) = 1)
|
||||
assert call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_retry_calls_send_delta():
|
||||
"""_send_with_retry should call send_delta for stream delta events."""
|
||||
calls: list[tuple[str, str, str | None, bool, bool, bool]] = []
|
||||
|
||||
class _StreamingChannel(BaseChannel):
|
||||
@@ -3103,7 +3043,7 @@ async def test_send_with_retry_calls_send_delta():
|
||||
pass
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
pass # Should not be called
|
||||
pass
|
||||
|
||||
async def send_delta(
|
||||
self,
|
||||
@@ -3156,7 +3096,6 @@ async def test_send_with_retry_calls_send_delta():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_retry_skips_send_when_streamed():
|
||||
"""_send_with_retry should not call send for streamed response events."""
|
||||
send_called = False
|
||||
send_delta_called = False
|
||||
|
||||
@@ -3290,7 +3229,6 @@ def test_outbound_duplicate_suppression_cache_is_bounded() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_retry_propagates_cancelled_error():
|
||||
"""_send_with_retry should re-raise CancelledError for graceful shutdown."""
|
||||
class _CancellingChannel(BaseChannel):
|
||||
name = "cancelling"
|
||||
display_name = "Cancelling"
|
||||
@@ -3324,7 +3262,6 @@ async def test_send_with_retry_propagates_cancelled_error():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_with_retry_propagates_cancelled_error_during_sleep():
|
||||
"""_send_with_retry should re-raise CancelledError during sleep."""
|
||||
call_count = 0
|
||||
|
||||
class _FailingChannel(BaseChannel):
|
||||
@@ -3356,7 +3293,6 @@ async def test_send_with_retry_propagates_cancelled_error_during_sleep():
|
||||
|
||||
msg = OutboundMessage(channel="failing", chat_id="123", content="test")
|
||||
|
||||
# Mock sleep to raise CancelledError
|
||||
async def cancel_during_sleep(_):
|
||||
raise asyncio.CancelledError("cancelled during sleep")
|
||||
|
||||
@@ -3364,14 +3300,9 @@ async def test_send_with_retry_propagates_cancelled_error_during_sleep():
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await mgr._send_with_retry(mgr.channels["failing"], msg)
|
||||
|
||||
# Should have attempted once before sleep was cancelled
|
||||
assert call_count == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ChannelManager - lifecycle and getters
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _ChannelWithAllowFrom(BaseChannel):
|
||||
"""Channel with configurable allow_from."""
|
||||
name = "withallow"
|
||||
@@ -3416,7 +3347,6 @@ class _StartableChannel(BaseChannel):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_validate_allow_from_allows_empty_list():
|
||||
"""Empty allow_from is valid now — pairing store handles unapproved senders."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3427,7 +3357,6 @@ async def test_validate_allow_from_allows_empty_list():
|
||||
mgr.channels = {"test": _ChannelWithAllowFrom(fake_config, None, [])}
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Should not raise — empty list defers to pairing store
|
||||
mgr._validate_allow_from()
|
||||
assert list(mgr.channels) == ["test"]
|
||||
assert mgr.channels["test"].config.allow_from == []
|
||||
@@ -3435,7 +3364,6 @@ async def test_validate_allow_from_allows_empty_list():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_validate_allow_from_passes_with_asterisk():
|
||||
"""_validate_allow_from should not raise when allow_from contains '*'."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3446,7 +3374,6 @@ async def test_validate_allow_from_passes_with_asterisk():
|
||||
mgr.channels = {"test": _ChannelWithAllowFrom(fake_config, None, ["*"])}
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Should not raise
|
||||
mgr._validate_allow_from()
|
||||
assert list(mgr.channels) == ["test"]
|
||||
assert mgr.channels["test"].config.allow_from == ["*"]
|
||||
@@ -3454,7 +3381,6 @@ async def test_validate_allow_from_passes_with_asterisk():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_validate_allow_from_allows_empty_dict_allow_from():
|
||||
"""Empty dict-backed allow_from is valid — pairing store handles approval."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3472,7 +3398,6 @@ async def test_validate_allow_from_allows_empty_dict_allow_from():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_validate_allow_from_allows_missing_allow_from():
|
||||
"""Omitted allowFrom is valid — channel operates in pairing-only mode."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3496,7 +3421,6 @@ async def test_validate_allow_from_allows_missing_allow_from():
|
||||
mgr.channels = {"test": _NoAllowFromChannel({"enabled": True}, None)}
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Should not raise — pairing-only mode
|
||||
mgr._validate_allow_from()
|
||||
assert list(mgr.channels) == ["test"]
|
||||
assert "allow_from" not in mgr.channels["test"].config
|
||||
@@ -3504,7 +3428,6 @@ async def test_validate_allow_from_allows_missing_allow_from():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_channel_returns_channel_if_exists():
|
||||
"""get_channel should return the channel if it exists."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3522,7 +3445,6 @@ async def test_get_channel_returns_channel_if_exists():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_status_returns_running_state():
|
||||
"""get_status should return enabled and running state for each channel."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3538,12 +3460,11 @@ async def test_get_status_returns_running_state():
|
||||
status = mgr.get_status()
|
||||
|
||||
assert status["startable"]["enabled"] is True
|
||||
assert status["startable"]["running"] is False # Not started yet
|
||||
assert status["startable"]["running"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enabled_channels_returns_channel_names():
|
||||
"""enabled_channels should return list of enabled channel names."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3567,7 +3488,6 @@ async def test_enabled_channels_returns_channel_names():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_all_cancels_dispatcher_and_stops_channels():
|
||||
"""stop_all should cancel the dispatch task and stop all channels."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3582,7 +3502,6 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
|
||||
mgr._outbound_tasks = {}
|
||||
mgr._stopping_channels = set()
|
||||
|
||||
# Create a real cancelled task
|
||||
async def dummy_task():
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
@@ -3592,15 +3511,12 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
|
||||
|
||||
await mgr.stop_all()
|
||||
|
||||
# Task should be cancelled
|
||||
assert dispatch_task.cancelled()
|
||||
# Channel should be stopped
|
||||
assert ch.stopped is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_channel_logs_error_on_failure():
|
||||
"""_start_channel should log error when channel start fails."""
|
||||
class _FailingChannel(BaseChannel):
|
||||
name = "failing"
|
||||
display_name = "Failing"
|
||||
@@ -3627,7 +3543,6 @@ async def test_start_channel_logs_error_on_failure():
|
||||
|
||||
ch = _FailingChannel(fake_config, mgr.bus)
|
||||
|
||||
# Should not raise, just log error
|
||||
await mgr._start_channel("failing", ch)
|
||||
assert mgr.channels == {}
|
||||
assert mgr._dispatch_task is None
|
||||
@@ -3635,7 +3550,6 @@ async def test_start_channel_logs_error_on_failure():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_all_handles_channel_exception():
|
||||
"""stop_all should handle exceptions when stopping channels gracefully."""
|
||||
class _StopFailingChannel(BaseChannel):
|
||||
name = "stopfailing"
|
||||
display_name = "Stop Failing"
|
||||
@@ -3662,7 +3576,6 @@ async def test_stop_all_handles_channel_exception():
|
||||
mgr._stopping_channels = set()
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Should not raise even if channel.stop() raises
|
||||
await mgr.stop_all()
|
||||
assert list(mgr.channels) == ["stopfailing"]
|
||||
assert mgr._dispatch_task is None
|
||||
@@ -3670,7 +3583,6 @@ async def test_stop_all_handles_channel_exception():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_all_handles_channel_stop_cancelled_task():
|
||||
"""stop_all should treat a channel's already-cancelled internals as stopped."""
|
||||
|
||||
class _StopCancelledChannel(BaseChannel):
|
||||
name = "stopcancelled"
|
||||
@@ -3709,7 +3621,6 @@ async def test_stop_all_handles_channel_stop_cancelled_task():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_all_no_channels_logs_warning():
|
||||
"""start_all should log warning when no channels are enabled."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3717,10 +3628,9 @@ async def test_start_all_no_channels_logs_warning():
|
||||
|
||||
mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
|
||||
mgr.config = fake_config
|
||||
mgr.channels = {} # No channels
|
||||
mgr.channels = {}
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Should return early without creating dispatch task
|
||||
await mgr.start_all()
|
||||
|
||||
assert mgr._dispatch_task is None
|
||||
@@ -3728,7 +3638,6 @@ async def test_start_all_no_channels_logs_warning():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_all_creates_dispatch_task():
|
||||
"""start_all should create the dispatch task when channels exist."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3742,7 +3651,6 @@ async def test_start_all_creates_dispatch_task():
|
||||
mgr._channel_tasks = {}
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Cancel immediately after start to avoid running forever
|
||||
async def cancel_after_start():
|
||||
await asyncio.sleep(0.01)
|
||||
if mgr._dispatch_task:
|
||||
@@ -3761,13 +3669,11 @@ async def test_start_all_creates_dispatch_task():
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
# Dispatch task should have been created
|
||||
assert mgr._dispatch_task is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_notify_restart_done_waits_until_channel_starts():
|
||||
"""Restart notice should not be sent before the target channel starts."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3802,7 +3708,6 @@ async def test_notify_restart_done_waits_until_channel_starts():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_websocket_restart_notice_does_not_overwrite_recovery_state():
|
||||
"""WebSocket attach/recovery events already own reconnect state."""
|
||||
fake_config = SimpleNamespace(
|
||||
channels=ChannelsConfig(),
|
||||
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
|
||||
@@ -3823,7 +3728,6 @@ async def test_websocket_restart_notice_does_not_overwrite_recovery_state():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restart_notice_retries_until_running_channel_accepts_delivery():
|
||||
"""A running flag must not make an early transport failure final."""
|
||||
|
||||
class _EventuallyDeliverableChannel(_StartableChannel):
|
||||
def __init__(self, config, bus):
|
||||
|
||||
@@ -40,7 +40,6 @@ INTERNAL_CHANNEL_FIELDS = {
|
||||
"signal": {"allowFrom"},
|
||||
"weixin": {"token"},
|
||||
"whatsapp": {"databasePath", "lidMappings"},
|
||||
# nanobot WebUI owns this transport and intentionally has no channel dialog.
|
||||
"websocket": {
|
||||
"allowFrom",
|
||||
"host",
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Feishu/Lark QR onboarding: verification URL handling."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -27,7 +27,7 @@ def _make_channel(tmp_path, **config_kwargs) -> QQChannel:
|
||||
app_id="test_app", secret="test_secret", media_dir=str(tmp_path), **config_kwargs,
|
||||
)
|
||||
channel = QQChannel(config, MessageBus())
|
||||
channel._client = object() # truthy: pass the initialized check
|
||||
channel._client = object()
|
||||
return channel
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Regression tests for QQ inbound attachment download SSRF protection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -94,7 +92,6 @@ async def test_inbound_download_blocks_ssrf_target(url: str) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inbound_validation_does_not_run_dns_on_the_event_loop(monkeypatch):
|
||||
"""The URL guard uses blocking getaddrinfo; keep it off the gateway loop."""
|
||||
loop_thread = threading.get_ident()
|
||||
validation_threads = []
|
||||
|
||||
@@ -118,7 +115,6 @@ async def test_inbound_download_does_not_follow_redirects(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
status: int,
|
||||
) -> None:
|
||||
"""A redirect on an inbound attachment download must be rejected, not followed."""
|
||||
monkeypatch.setattr("nanobot.channels.qq.runtime.validate_url_target", lambda _url: (True, ""))
|
||||
channel = _make_channel()
|
||||
fake_http = _FakeDownloadHttp(status=status)
|
||||
@@ -143,7 +139,6 @@ async def test_inbound_download_saves_successful_attachment(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
url: str,
|
||||
) -> None:
|
||||
"""A valid 200 response still follows the normal atomic media write path."""
|
||||
validated_urls: list[str] = []
|
||||
|
||||
def validate(target: str) -> tuple[bool, str]:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Regression tests for QQ WebSocket reconnect backoff."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Exercise scheduled delivery through the real gateway pipeline, without external sends."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
@@ -162,11 +160,8 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
|
||||
if origin == "websocket":
|
||||
manager.channels["websocket"] = MagicMock(spec=BaseChannel, send=AsyncMock(), stop=AsyncMock())
|
||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||
# Legacy channel/to fields still normalize through the existing binding migration.
|
||||
schedule = CronSchedule(kind="at", at_ms=4102444800000) if one_shot else CronSchedule(kind="every", every_ms=86400000)
|
||||
if origin == "websocket":
|
||||
# A WebUI-created task remains in its source chat even when its instructions
|
||||
# explicitly request a separate send. Recovery must keep that send's target.
|
||||
with request_context(RequestContext("websocket", "source", session_key="websocket:source",
|
||||
metadata={"webui": True, "_wants_stream": True})):
|
||||
await CronTool(cron).execute(action="add", name="Reminder", every_seconds=86400,
|
||||
@@ -202,7 +197,6 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
|
||||
assert DELIVERY_RUN_META not in json.dumps(calls[0]["messages"])
|
||||
assert "Diagnostic result" not in calls[0]["messages"][0]["content"]
|
||||
await manager.stop_all()
|
||||
# A second gateway uses the saved result; no timer, agent, or model is restarted.
|
||||
manager = make_manager(tmp_path, sessions)
|
||||
manager.channels["whatsapp"] = channel
|
||||
channel._connected = True
|
||||
@@ -216,7 +210,6 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
|
||||
await again._recover_scheduled()
|
||||
assert channel._client.send_message.await_count == 1
|
||||
assert len(calls) == count
|
||||
# Existing jobs still load after delivery state is added beside them.
|
||||
old_jobs = CronService(cron.store_path).list_jobs()
|
||||
assert old_jobs == [] if one_shot else old_jobs[0].payload.message == job.payload.message
|
||||
finally:
|
||||
@@ -335,7 +328,6 @@ async def test_recovery_keeps_destination_order_and_does_not_block_other_chats(t
|
||||
await manager._recover_scheduled()
|
||||
await drain(manager)
|
||||
assert [call.args[0].content for call in channel.send.await_args_list] == ["first", "other", "first", "second"]
|
||||
# A stale queued copy must not downgrade the durable successful result.
|
||||
manager._outbox.finish(first, "failed", "channel_disabled")
|
||||
assert all(row["status"] == "sent" for row in rows(manager._outbox))
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Reachable manager/adapter ownership contracts for outbound retries."""
|
||||
|
||||
import asyncio
|
||||
import random
|
||||
from types import SimpleNamespace
|
||||
@@ -7,7 +5,6 @@ from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
# Telegram is an optional channel dependency, as in its adapter-owned suite.
|
||||
pytest.importorskip("telegram")
|
||||
from telegram.error import NetworkError, RetryAfter, TimedOut
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Behavioral delegation and executable ownership boundaries for WebSocket."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
@@ -144,7 +142,6 @@ def _session_namespace_literal_lines(source: str) -> list[int]:
|
||||
if annotation is not None:
|
||||
ignored.update(ast.walk(annotation))
|
||||
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
|
||||
# A standalone string (including a docstring) does not define runtime policy.
|
||||
ignored.add(node.value)
|
||||
return [
|
||||
node.lineno
|
||||
@@ -157,8 +154,6 @@ def _session_namespace_literal_lines(source: str) -> list[int]:
|
||||
|
||||
|
||||
def test_persisted_webui_session_prefix_has_one_production_owner() -> None:
|
||||
# Consumers import session_identity; independent literal keys/prefixes fork its policy.
|
||||
# Exact persisted values and mapping round trips live in test_session_identity.py.
|
||||
owners = {}
|
||||
for path in (_REPOSITORY_ROOT / "nanobot").rglob("*.py"):
|
||||
if "tests" in path.parts:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Regression tests for WebSocket listener health probing portability."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
@@ -86,7 +84,6 @@ def test_unsupported_sockopt_falls_back_to_fd_liveness(unsupported_errno: int) -
|
||||
|
||||
|
||||
def test_listener_health_uses_unsupported_sockopt_fallback() -> None:
|
||||
"""The fallback must be wired into the health check that controls readiness."""
|
||||
sock = _StubSocket(fileno=3, error=OSError(errno.ENOPROTOOPT, "Protocol not available"))
|
||||
server: Any = _StubServer(sock)
|
||||
|
||||
@@ -103,7 +100,6 @@ def test_unexpected_oserror_propagates() -> None:
|
||||
|
||||
|
||||
def test_listener_health_rejects_invalid_socket_state() -> None:
|
||||
"""``EINVAL`` can mean that a live socket isn't actually listening."""
|
||||
sock = _StubSocket(fileno=3, error=OSError(errno.EINVAL, "Invalid argument"))
|
||||
server: Any = _StubServer(sock)
|
||||
|
||||
@@ -111,7 +107,6 @@ def test_listener_health_rejects_invalid_socket_state() -> None:
|
||||
|
||||
|
||||
def test_unsupported_sockopt_still_rejects_dead_fd() -> None:
|
||||
"""The portability fallback must not mask an already-closed listener."""
|
||||
sock = _StubSocket(fileno=-1, error=OSError(errno.ENOPROTOOPT, "Protocol not available"))
|
||||
|
||||
assert WebSocketChannel._socket_is_accepting(sock) is False
|
||||
Reference in new issue
Block a user