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

-6
View File
@@ -1,5 +1,3 @@
"""Tests for abbreviate_path utility."""
import os
from nanobot.utils.path import abbreviate_path
@@ -79,26 +77,22 @@ class TestAbbreviatePathURLs:
assert abbreviate_path(url) == url
def test_url_no_path_just_domain(self):
"""G3: URL with no path should return as-is if short enough."""
url = "https://example.com"
assert abbreviate_path(url) == url
def test_url_with_query_string(self):
"""G3: URL with query params should abbreviate path part."""
url = "https://example.com/api/v2/endpoint?key=value&other=123"
result = abbreviate_path(url, max_len=40)
assert "example.com" in result
assert "\u2026" in result
def test_url_very_long_basename(self):
"""G3: URL with very long basename should truncate basename."""
url = "https://example.com/path/very_long_resource_name_file.json"
result = abbreviate_path(url, max_len=35)
assert "example.com" in result
assert "\u2026" in result
def test_url_negative_budget_consistent_format(self):
"""I3: Negative budget should still produce domain/…/basename format."""
url = "https://a.co/very/deep/path/with/lots/of/segments/and/a/long/basename.txt"
result = abbreviate_path(url, max_len=20)
assert "a.co" in result
+2 -21
View File
@@ -1,5 +1,3 @@
"""Tests for GitStore core operations."""
import subprocess
from pathlib import Path
from unittest.mock import patch
@@ -18,7 +16,6 @@ def git(tmp_path):
class TestSummarizeWorkingTree:
"""Ground-truth diff summary used to keep Dream audit records honest."""
def test_empty_when_not_initialized(self, tmp_path):
git = GitStore(tmp_path, tracked_files=["MEMORY.md"])
@@ -35,7 +32,6 @@ class TestSummarizeWorkingTree:
assert "1 file changed, 2 insertions(+), 0 deletions(-)" in summary
def test_only_reports_requested_paths(self, git, tmp_path):
# MEMORY.md changes, but we only ask about the unchanged SOUL.md.
(tmp_path / "MEMORY.md").write_text("changed\n", encoding="utf-8")
assert git.summarize_working_tree(["SOUL.md"]) == ""
@@ -45,28 +41,24 @@ class TestSummarizeWorkingTree:
assert "MEMORY.md: +3 -0" in summary
def test_detects_deletion(self, git, tmp_path):
# File removed from the working tree (must have content first; the
# fixture's tracked files start empty, so an empty-file delete is a no-op).
(tmp_path / "MEMORY.md").write_text("has content\n", encoding="utf-8")
git.auto_commit("add content")
(tmp_path / "MEMORY.md").unlink()
summary = git.summarize_working_tree(["MEMORY.md"])
assert summary # a removal is still a change
assert summary
assert "deletion" in summary
def test_non_utf8_file_marked_binary_without_replacement_chars(self, git, tmp_path):
# Invalid UTF-8 must not leak replacement chars into the audit record.
(tmp_path / "MEMORY.md").write_bytes(b"\x89PNG\r\n\x1a\n\xff\xfe\x00\x01")
summary = git.summarize_working_tree(["MEMORY.md"])
assert "MEMORY.md: binary or non-UTF-8 file changed" in summary
assert "\ufffd" not in summary # no U+FFFD replacement chars leaked
assert "\ufffd" not in summary
class TestNestedRepoProtection:
"""Regression tests for GitHub issue #2980: nested repo protection."""
def test_init_refuses_inside_git_repo(self, tmp_path):
"""init() should detect it's inside an existing git repo and refuse."""
project = tmp_path / "project"
project.mkdir()
(project / ".git").mkdir()
@@ -81,7 +73,6 @@ class TestNestedRepoProtection:
assert not (workspace / ".git").is_dir()
def test_init_preserves_existing_gitignore(self, tmp_path):
"""init() should preserve existing .gitignore entries and append new ones."""
workspace = tmp_path / "workspace"
workspace.mkdir()
@@ -99,7 +90,6 @@ class TestNestedRepoProtection:
assert "!.gitignore" in gitignore
def test_init_no_gitignore_creates_new(self, tmp_path):
"""init() should create .gitignore with Dream content when none exists."""
workspace = tmp_path / "workspace"
workspace.mkdir()
@@ -112,11 +102,9 @@ class TestNestedRepoProtection:
assert gitignore == expected
def test_init_gitignore_merge_idempotent(self, tmp_path):
"""init() should not duplicate Dream entries already in .gitignore."""
workspace = tmp_path / "workspace"
workspace.mkdir()
# Pre-existing .gitignore that already has some Dream entries
existing = "*.pyc\n/*\n!MEMORY.md\n"
(workspace / ".gitignore").write_text(existing, encoding="utf-8")
@@ -125,16 +113,13 @@ class TestNestedRepoProtection:
assert result is True
gitignore = (workspace / ".gitignore").read_text(encoding="utf-8")
# No duplicate lines
lines = gitignore.splitlines()
assert lines.count("/*") == 1
assert lines.count("!MEMORY.md") == 1
# Existing entry preserved, new Dream entries appended
assert "*.pyc" in gitignore
assert "!.gitignore" in gitignore
def test_init_outside_git_repo_works_normally(self, tmp_path):
"""init() should succeed and create .git when not inside a git repo."""
workspace = tmp_path / "workspace"
workspace.mkdir()
@@ -145,7 +130,6 @@ class TestNestedRepoProtection:
assert (workspace / ".git").is_dir()
def test_staging_paths_are_absolute_from_workspace(self, tmp_path, monkeypatch):
"""Git operations should not depend on the process working directory."""
from dulwich import porcelain
workspace = tmp_path / "workspace"
@@ -169,7 +153,6 @@ class TestNestedRepoProtection:
assert all(path.is_relative_to(workspace) for path in staging_paths)
def test_staging_paths_preserve_symlinks(self, tmp_path):
"""Absolute staging paths should still identify the tracked symlink itself."""
workspace = tmp_path / "workspace"
workspace.mkdir()
target = tmp_path / "shared-memory.md"
@@ -187,7 +170,6 @@ class TestNestedRepoProtection:
assert staging_path.is_symlink()
def test_init_refuses_inside_git_worktree(self, tmp_path):
"""init() should refuse when the parent checkout is a git worktree."""
repo = tmp_path / "repo"
repo.mkdir()
subprocess.run(["git", "init", "-q", str(repo)], check=True)
@@ -229,7 +211,6 @@ class TestNestedRepoProtection:
class TestCommitIdEncoding:
"""Commit ids must be usable with git, not hex-of-hex."""
def test_auto_commit_returns_the_real_short_sha(self, git, tmp_path):
(tmp_path / "MEMORY.md").write_text("- a fact\n", encoding="utf-8")
-5
View File
@@ -211,7 +211,6 @@ def test_atomic_write_text_creates_parent_and_replaces_exact_content(
def test_atomic_write_lines_round_trip_replaces_target(tmp_path: Path) -> None:
"""Missing newline insertion or a non-atomic partial write drops records."""
target = tmp_path / "history.jsonl"
target.write_text("old\n", encoding="utf-8")
@@ -224,7 +223,6 @@ def test_atomic_write_lines_round_trip_replaces_target(tmp_path: Path) -> None:
@pytest.mark.parametrize("name", ["status.json", "更新状态-🐈.json"])
def test_atomic_record_reader_does_not_block_concurrent_replacement(tmp_path: Path, name: str) -> None:
"""The update UI can poll while a detached worker commits its next phase."""
from nanobot.utils.atomic_file import _open_snapshot, read_atomic_bytes
target = tmp_path / name
@@ -256,7 +254,6 @@ def test_atomic_writes_clean_temp_when_replace_fails(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error_type: type[BaseException],
write: Callable[[Path, str], None],
) -> None:
"""A failed replace must not leave a temp file or change the target."""
target = tmp_path / "history.jsonl"
target.write_text("kept\n", encoding="utf-8")
@@ -273,7 +270,6 @@ def test_atomic_writes_clean_temp_when_replace_fails(
def test_atomic_write_lines_leaves_unrelated_tmp_sibling(tmp_path: Path) -> None:
"""A unique temp name must not clobber a sibling ``*.tmp`` file."""
target = tmp_path / "history.jsonl"
stale = target.with_name(target.name + ".tmp")
stale.write_text("stale", encoding="utf-8")
@@ -300,7 +296,6 @@ def test_atomic_write_lines_skips_fsync_when_disabled(
def test_atomic_write_lines_suppresses_directory_permission_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Windows directory open raises PermissionError; the replace must still stick."""
target = tmp_path / "history.jsonl"
opened: list[tuple[object, int]] = []
real_open = atomic_file.os.open
@@ -1,5 +1,3 @@
"""Tests for length-recovery prompt construction."""
from nanobot.utils.runtime import build_length_recovery_message
-3
View File
@@ -1,5 +1,3 @@
"""Tests for ``nanobot.utils.media_decode``."""
from __future__ import annotations
import base64
@@ -136,7 +134,6 @@ def test_unknown_mime_falls_back_to_bin(tmp_path) -> None:
def test_default_limit_is_10mb(tmp_path) -> None:
"""Backwards-compatible default — the API path depends on this."""
assert DEFAULT_MAX_BYTES == 10 * 1024 * 1024
assert MAX_FILE_SIZE == 10 * 1024 * 1024
-3
View File
@@ -1,5 +1,3 @@
"""Tests for restart notice helpers."""
from __future__ import annotations
import os
@@ -28,7 +26,6 @@ def test_set_and_consume_restart_notice_env_roundtrip(monkeypatch):
assert notice.started_at_raw
assert notice.metadata == {}
# Consumed values should be cleared from env.
assert consume_restart_notice_from_env() is None
assert "NANOBOT_RESTART_NOTIFY_CHANNEL" not in os.environ
assert "NANOBOT_RESTART_NOTIFY_CHAT_ID" not in os.environ
-21
View File
@@ -1,5 +1,3 @@
"""Tests for web search provider usage fetching and /status integration."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
@@ -14,9 +12,6 @@ from nanobot.utils.searchusage import (
fetch_search_usage,
)
# ---------------------------------------------------------------------------
# SearchUsageInfo.format() tests
# ---------------------------------------------------------------------------
class TestSearchUsageInfoFormat:
def test_unsupported_provider_shows_no_tracking(self):
@@ -73,10 +68,6 @@ class TestSearchUsageInfoFormat:
assert "not available" in text
# ---------------------------------------------------------------------------
# _parse_tavily_usage tests
# ---------------------------------------------------------------------------
class TestParseTavilyUsage:
def test_full_response(self):
data = {
@@ -146,10 +137,6 @@ class TestParseTavilyUsage:
assert info.crawl_used == 1
# ---------------------------------------------------------------------------
# fetch_search_usage routing tests
# ---------------------------------------------------------------------------
class TestFetchSearchUsageRouting:
@pytest.mark.asyncio
async def test_duckduckgo_returns_unsupported(self):
@@ -181,7 +168,6 @@ class TestFetchSearchUsageRouting:
@pytest.mark.asyncio
async def test_tavily_no_api_key_returns_error(self):
with patch.dict("os.environ", {}, clear=True):
# Ensure TAVILY_API_KEY is not set
import os
os.environ.pop("TAVILY_API_KEY", None)
info = await fetch_search_usage("tavily", api_key=None)
@@ -265,10 +251,6 @@ class TestFetchSearchUsageRouting:
assert info.supported is True
# ---------------------------------------------------------------------------
# build_status_content integration tests
# ---------------------------------------------------------------------------
class TestBuildStatusContentWithSearchUsage:
_BASE_KWARGS = dict(
version="0.1.0",
@@ -281,7 +263,6 @@ class TestBuildStatusContentWithSearchUsage:
)
def test_no_search_usage_unchanged(self):
"""Omitting search_usage_text keeps existing behaviour."""
content = build_status_content(**self._BASE_KWARGS)
assert "🔍" not in content
assert "Web Search" not in content
@@ -299,11 +280,9 @@ class TestBuildStatusContentWithSearchUsage:
def test_existing_fields_still_present(self):
usage_text = "🔍 Web Search: duckduckgo\n Usage tracking: not available"
content = build_status_content(**self._BASE_KWARGS, search_usage_text=usage_text)
# Original fields must still be present
assert "nanobot v0.1.0" in content
assert "claude-opus-4-5" in content
assert "1000 in / 200 out" in content
# New field appended
assert "duckduckgo" in content
def test_full_tavily_in_status(self):
-12
View File
@@ -7,7 +7,6 @@ from nanobot.utils.helpers import (
class TestStripThinkTag:
"""Test <thought>...</thought> block stripping (Gemma 4 and similar models)."""
def test_closed_tag(self):
assert strip_think("Hello <thought>reasoning</thought> World") == "Hello World"
@@ -89,14 +88,12 @@ class TestStripThinkMalformedLeaks:
)
def test_malformed_think_no_gt_english_with_space(self):
# English leak with a space after the tag name (common streaming form).
assert strip_think("<think The fountain opens at 09:00") == ("The fountain opens at 09:00")
def test_malformed_thought_no_gt(self):
assert strip_think("<thought广场照明灯") == "广场照明灯"
def test_thinker_word_preserved(self):
# `<thinker>` is a valid tag name variant; must not match.
assert strip_think("<thinker>content</thinker>") == "<thinker>content</thinker>"
def test_self_closing_preserved(self):
@@ -104,15 +101,12 @@ class TestStripThinkMalformedLeaks:
assert strip_think("<thought/>ok") == "<thought/>ok"
def test_orphan_closing_think_at_end_stripped(self):
# Typical leak: model opens `<think>` without closing; we strip the
# opener from the start, leaving an orphan `</think>` at the end.
assert strip_think("answer</think>") == "answer"
def test_orphan_closing_think_at_start_stripped(self):
assert strip_think("</think>answer") == "answer"
def test_channel_marker_at_start_stripped(self):
# Harmony / Gemma 4 channel markers leak at the start of a response.
assert strip_think("<channel|>喷泉策略:09:00 开启") == ("喷泉策略:09:00 开启")
assert strip_think("<|channel|>answer") == "answer"
@@ -146,8 +140,6 @@ class TestStripThinkConservativePreserve:
assert strip_think("<think:foo>bar</think:foo>") == "<think:foo>bar</think:foo>"
def test_literal_close_think_in_prose_preserved(self):
# Mid-prose references to `</think>` in backticks or plain text must
# not be stripped; edge-only regex protects this.
text = "Use `</think>` to close a thinking block."
assert strip_think(text) == text
@@ -198,7 +190,6 @@ class TestExtractThink:
assert clean == ""
def test_unclosed_think_not_extracted(self):
# Unclosed blocks at start are stripped but NOT extracted
text = "<think>unclosed thinking..."
thinking, clean = extract_think(text)
assert thinking is None
@@ -207,7 +198,6 @@ class TestExtractThink:
def test_empty_think_block(self):
text = "Hello <think></think> World"
thinking, clean = extract_think(text)
# Empty blocks result in empty string after strip
assert thinking == ""
assert clean == "Hello World"
@@ -248,7 +238,6 @@ squares = [x**2 for x in range(10)]
class TestExtractReasoning:
"""Single source of truth for reasoning extraction across all providers."""
def test_strips_tags_from_dedicated_reasoning_content(self):
reasoning, content = extract_reasoning(
@@ -269,7 +258,6 @@ class TestExtractReasoning:
assert content == "visible answer"
def test_prefers_reasoning_content_and_strips_inline_think(self):
# Dedicated field wins; inline tags are still scrubbed from content.
reasoning, content = extract_reasoning(
"dedicated",
None,
@@ -1,5 +1,3 @@
"""Tests for subagent announce text shaping on external channel surfaces."""
from nanobot.utils.subagent_channel_display import scrub_subagent_announce_body
-3
View File
@@ -1,5 +1,3 @@
"""Tests for append-only WebUI transcript replay."""
from __future__ import annotations
import json
@@ -456,7 +454,6 @@ def test_many_short_trace_rows_are_bounded_and_resolved(history, tmp_path, monke
{"event": "message", "chat_id": "deferred-many-traces", "text": "done"},
{"event": "turn_end", "chat_id": "deferred-many-traces"},
]
# Replay needs the full stored input, not one durable append per trace row.
history.sessions.append_history(
key,
[fact_from_record({**row, "created_at_ms": 1_700_000_000_000}) for row in rows],
-3
View File
@@ -1,5 +1,3 @@
"""Tests for WebSocket turn timing strip bookkeeping."""
import sqlite3
from unittest.mock import AsyncMock, MagicMock
@@ -375,7 +373,6 @@ async def test_turn_end_reads_goal_without_loading_conversation_history(
})
await sessions.state.aclose()
# A new owner has no cached history to hide an accidental full draft read.
sessions = SessionManager(tmp_path)
def deny_history(action, table, *_args):
@@ -1,5 +1,3 @@
"""Tests for WebUI websocket logging helpers."""
from __future__ import annotations
import logging
@@ -37,7 +35,6 @@ def test_websocket_handshake_noise_filter_suppresses_disconnects() -> None:
def test_websocket_handshake_noise_filter_suppresses_non_get_probes() -> None:
"""HEAD probes reach the WS port as InvalidMessage wrapping a ValueError."""
filter_ = WebSocketHandshakeNoiseFilter()
head_probe = InvalidMessage("did not receive a valid HTTP request")
head_probe.__cause__ = ValueError("unsupported HTTP method; expected GET; got HEAD")
@@ -46,7 +43,6 @@ def test_websocket_handshake_noise_filter_suppresses_non_get_probes() -> None:
def test_websocket_handshake_noise_filter_suppresses_malformed_requests() -> None:
"""Port scanners / TLS-to-plain-port probes raise a bare InvalidMessage."""
filter_ = WebSocketHandshakeNoiseFilter()
malformed = InvalidMessage("did not receive a valid HTTP request")
-2
View File
@@ -1,5 +1,3 @@
"""Project selection directory metadata contracts."""
import os
import stat
import sys
@@ -1,5 +1,3 @@
"""Tests for repeated_workspace_violation throttle and signature."""
from __future__ import annotations
from nanobot.utils.runtime import (
@@ -85,7 +83,6 @@ def test_repeated_workspace_violation_escalates_after_third_attempt():
def test_repeated_workspace_violation_independent_per_target():
"""Different outside paths must each get their own retry budget."""
counts: dict[str, int] = {}
repeated_workspace_violation_error(
@@ -94,7 +91,6 @@ def test_repeated_workspace_violation_independent_per_target():
repeated_workspace_violation_error(
"read_file", {"path": "/Users/x/Downloads/01.md"}, counts,
)
# Different target, fresh budget.
assert repeated_workspace_violation_error(
"read_file", {"path": "/Users/x/Documents/notes.md"}, counts,
) is None