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:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

+10 -106
View File
@@ -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):