test: remove unreachable cases and strengthen weak assertions

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-22 17:19:20 +08:00
1 parent 169062be11
commit abfe510ce1
25 files changed
+64 -302

No files matched your search

-20
View File
@@ -340,26 +340,6 @@ class TestCheckExpired:
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
async def test_session_with_no_key_skips(self):
"""Session info with empty/missing key should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = [{"key": "", "updated_at": "old"}]
ac.sessions = mock_sm
scheduler = MagicMock()
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
async def test_session_with_missing_key_field_skips(self):
"""Session info dict without 'key' field should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = [{"updated_at": "old"}]
ac.sessions = mock_sm
scheduler = MagicMock()
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
async def test_dream_session_skips(self):
"""Internal Dream sessions should not be scheduled for idle compact."""
ac = _make_autocompact(ttl=15)
+9 -42
View File
@@ -313,16 +313,6 @@ class TestFormatValue:
class TestSyncWorkspaceTemplates:
"""Tests for sync_workspace_templates file synchronization."""
def test_creates_missing_files(self, tmp_path):
"""Should create template files that don't exist."""
workspace = tmp_path / "workspace"
added = sync_workspace_templates(workspace, silent=True)
# Check that some files were created
assert isinstance(added, list)
# The actual files depend on the templates directory
def test_does_not_overwrite_existing_files(self, tmp_path):
"""Should not overwrite files that already exist."""
workspace = tmp_path / "workspace"
@@ -398,13 +388,16 @@ class TestProviderChannelInfo:
assert "openai_codex" not in names
assert "github_copilot" not in names
def test_get_channel_names_returns_dict(self):
from nanobot.cli.onboard import _get_channel_names
def test_get_channel_names_maps_display_names(self, monkeypatch):
monkeypatch.setattr(onboard_wizard, "_get_channel_info", lambda: {
"first": ("First channel", Config),
"second": ("Second channel", Config),
})
names = _get_channel_names()
assert isinstance(names, dict)
# Should include at least some channels
assert len(names) >= 0
assert onboard_wizard._get_channel_names() == {
"first": "First channel",
"second": "Second channel",
}
def test_get_provider_info_returns_valid_structure(self):
from nanobot.cli.onboard import _get_provider_info
@@ -1780,26 +1773,6 @@ class TestMainMenuInteraction:
assert loginchat["enabled"] is True
assert calls == {"force": False}
def test_main_menu_dispatch_includes_channel_common(self):
"""Advanced menu dispatch should route [H] to Channel Common."""
# We verify by checking the dispatch table is set up correctly
# The menu items are defined inline in run_onboard, so we test
# that _configure_general_settings handles the new sections.
from nanobot.cli.onboard import _SETTINGS_GETTER, _SETTINGS_SECTIONS, _SETTINGS_SETTER
assert "Channel Common" in _SETTINGS_SECTIONS
assert "Channel Common" in _SETTINGS_GETTER
assert "Channel Common" in _SETTINGS_SETTER
def test_main_menu_dispatch_includes_api_server(self):
"""Advanced menu dispatch should route [I] to API Server."""
from nanobot.cli.onboard import _SETTINGS_GETTER, _SETTINGS_SECTIONS, _SETTINGS_SETTER
assert "API Server" in _SETTINGS_SECTIONS
assert "API Server" in _SETTINGS_GETTER
assert "API Server" in _SETTINGS_SETTER
def test_run_onboard_channel_common_edit(self, monkeypatch):
"""run_onboard should handle [H] Channel Common through Advanced Settings."""
initial_config = Config()
@@ -2168,12 +2141,6 @@ class TestModelPresetWizard:
assert defaults.model_preset is None
_MODEL_PRESET_CACHE.clear()
def test_main_menu_dispatch_includes_model_presets(self):
"""_configure_model_presets should be importable and callable."""
from nanobot.cli.onboard import _configure_model_presets
assert callable(_configure_model_presets)
def test_run_onboard_model_presets_edit(self, monkeypatch):
"""run_onboard should handle [M] Model Presets through Advanced Settings."""
from nanobot.config.schema import ModelPresetConfig
-19
View File
@@ -612,17 +612,6 @@ class TestRunningCounts:
class TestSubagentHook:
@pytest.mark.asyncio
async def test_before_execute_tools_without_status_preserves_calls(self):
hook = _SubagentHook()
tool_call = MagicMock()
tool_call.name = "read_file"
tool_call.arguments = {"path": "/tmp/test"}
ctx = _make_hook_context(tool_calls=[tool_call])
result = await hook.before_execute_tools(ctx)
assert result is None
assert ctx.tool_calls == [tool_call]
@pytest.mark.asyncio
async def test_after_iteration_updates_status(self):
status = SubagentStatus(
@@ -639,14 +628,6 @@ class TestSubagentHook:
assert len(status.tool_events) == 1
assert status.usage == LLMUsage.reported(input_tokens=100, output_tokens=0)
@pytest.mark.asyncio
async def test_after_iteration_no_status_noop(self):
hook = _SubagentHook()
ctx = _make_hook_context(iteration=5)
result = await hook.after_iteration(ctx)
assert result is None
assert ctx.iteration == 5
@pytest.mark.asyncio
async def test_after_iteration_sets_error(self):
status = SubagentStatus(
-13
View File
@@ -628,19 +628,6 @@ class TestSubagentHookStatus:
assert status.error == "something went wrong"
@pytest.mark.asyncio
async def test_after_iteration_no_status_is_noop(self):
"""after_iteration with no status should be a no-op."""
from nanobot.agent.hook import AgentHookContext
from nanobot.agent.subagent import _SubagentHook
hook = _SubagentHook()
context = AgentHookContext(iteration=1, messages=[])
result = await hook.after_iteration(context)
assert result is None
assert context.iteration == 1
# ---------------------------------------------------------------------------
# read-only mode (tools.my.allow_set=False)
-8
View File
@@ -126,14 +126,6 @@ async def test_skill_command_no_render_as_text(tmp_path: Path) -> None:
assert out.metadata.get("render_as") != "text"
@pytest.mark.asyncio
async def test_skill_command_does_not_list_goal_runtime_protocol(tmp_path: Path) -> None:
loop = _make_loop(tmp_path)
out = await cmd_skill(_ctx(loop))
assert "long-goal" not in out.content
@pytest.mark.asyncio
async def test_skill_command_registered_on_router(tmp_path: Path) -> None:
router = CommandRouter()
+4 -2
View File
@@ -15,9 +15,11 @@ from nanobot.config.schema import Config
def test_save_config_round_trips(tmp_path: Path) -> None:
path = tmp_path / "config.json"
save_config(Config(), path)
config = Config()
config.agents.defaults.model = "saved-model"
save_config(config, path)
loaded = load_config(path)
assert loaded.agents.defaults.model
assert loaded.agents.defaults.model == "saved-model"
@pytest.mark.skipif(os.name == "nt", reason="Windows does not expose POSIX file modes")
+16 -21
View File
@@ -3,6 +3,7 @@
from unittest.mock import MagicMock
import httpx
import pytest
import nanobot.providers.openai_compat_provider as openai_compat_provider
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
@@ -17,28 +18,22 @@ def _make_spec(is_local: bool = False) -> MagicMock:
class TestLocalEndpointProxyDisabled:
"""Local endpoints must bypass proxy to avoid routing LAN traffic through it."""
async def test_local_disables_proxy(self):
spec = _make_spec(is_local=True)
@pytest.mark.parametrize("api_base,is_local", [
("http://localhost:11434/v1", True),
("http://192.168.8.188:1234/v1", False),
])
async def test_local_endpoint_bypasses_environment_proxy(self, monkeypatch, api_base, is_local):
for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"):
monkeypatch.delenv(name, raising=False)
monkeypatch.delenv(name.lower(), raising=False)
monkeypatch.setenv("ALL_PROXY", "http://proxy.example:8123")
spec = _make_spec(is_local=is_local)
spec.env_key = ""
spec.default_api_base = "http://localhost:11434/v1"
provider = OpenAICompatProvider(
api_key="test", api_base="http://localhost:11434/v1", spec=spec,
)
await provider._ensure_client()
transport = provider._client._client._transport
# The transport should be an AsyncHTTPTransport with proxy=None
assert isinstance(transport, httpx.AsyncHTTPTransport)
async def test_lan_ip_disables_proxy(self):
spec = _make_spec(is_local=False)
spec.env_key = ""
spec.default_api_base = None
provider = OpenAICompatProvider(
api_key="test", api_base="http://192.168.8.188:1234/v1", spec=spec,
)
await provider._ensure_client()
transport = provider._client._client._transport
assert isinstance(transport, httpx.AsyncHTTPTransport)
spec.default_api_base = api_base
provider = OpenAICompatProvider(api_key="test", api_base=api_base, spec=spec)
async with await provider._ensure_client() as sdk:
client = sdk._client
assert client._transport_for_url(httpx.URL(api_base)) is client._transport
class TestCloudEndpointProxyEnabled:
@@ -131,15 +131,6 @@ def test_responses_declaration_routes_other_models(provider):
assert provider._should_use_responses_api("gpt-4o", None) is True
def test_responses_only_declaration_ignores_circuit_breaker(provider):
provider.default_model = "gpt-4o"
provider._preset_model_api = ModelAPICapabilities(("responses",), "responses")
provider._responses_failures = {"gpt-4o|gpt-4o|": _RESPONSES_FAILURE_THRESHOLD}
provider._responses_tripped_at = {"gpt-4o|gpt-4o|": 0.0}
assert provider._should_use_responses_api("gpt-4o", None) is True
def test_circuit_opens_after_threshold(provider):
for _ in range(_RESPONSES_FAILURE_THRESHOLD):
provider._record_responses_failure("gpt-5", None)
+9 -4
View File
@@ -1,5 +1,6 @@
"""Tests for ReadFileTool enhancements: description fix, read dedup, PDF support, device blacklist, office docs."""
import base64
import os
import sys
from unittest.mock import patch
@@ -95,14 +96,18 @@ class TestReadDedup:
assert "unchanged" not in read_result.lower()
@pytest.mark.asyncio
async def test_dedup_does_not_apply_to_images(self, tool, tmp_path):
async def test_repeated_image_reads_return_full_content(self, tool, tmp_path):
f = tmp_path / "img.png"
f.write_bytes(b"\x89PNG\r\n\x1a\nfake-png-data")
first = await tool.execute(path=str(f))
assert isinstance(first, list)
second = await tool.execute(path=str(f))
# Images should always return full content blocks, not a stub
assert isinstance(second, list)
assert second == first
assert second[0]["type"] == "image_url"
encoded = base64.b64encode(f.read_bytes()).decode("ascii")
assert second[0]["image_url"]["url"] == f"data:image/png;base64,{encoded}"
assert second[0]["_meta"]["path"] == str(f)
assert second[1] == {"type": "text", "text": f"(Image file: {f})"}
@pytest.mark.asyncio
async def test_known_text_extension_falls_back_to_latin1(self, tool, tmp_path):