test: consolidate repetitive cases across the suite

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-25 14:28:21 +08:00
1 parent c406024b59
commit 6eccc2859a
31 files changed
+745 -1315

No files matched your search

+11 -23
View File
@@ -2,6 +2,8 @@ from __future__ import annotations
import asyncio
import pytest
from nanobot.agent.tools.apply_patch import ApplyPatchTool
@@ -89,7 +91,14 @@ def test_apply_patch_edits_add_to_existing_file(tmp_path):
)
def test_apply_patch_edits_add_to_existing_file_without_final_newline(tmp_path):
@pytest.mark.parametrize(
"new_text",
[
pytest.param("beta", id="without_final_newline"),
pytest.param("\nbeta", id="respects_leading_newline"),
],
)
def test_apply_patch_add_separates_existing_file_without_final_newline(tmp_path, new_text):
target = tmp_path / "notes.txt"
target.write_text("alpha", encoding="utf-8")
tool = ApplyPatchTool(workspace=tmp_path)
@@ -100,7 +109,7 @@ def test_apply_patch_edits_add_to_existing_file_without_final_newline(tmp_path):
{
"path": "notes.txt",
"action": "add",
"new_text": "beta",
"new_text": new_text,
}
]
)
@@ -131,27 +140,6 @@ def test_apply_patch_edits_add_to_existing_crlf_file_without_final_newline(tmp_p
assert target.read_bytes() == b"alpha\r\nbravo\r\ncharlie\r\n"
def test_apply_patch_edits_add_to_existing_file_respects_leading_newline(tmp_path):
target = tmp_path / "notes.txt"
target.write_text("alpha", encoding="utf-8")
tool = ApplyPatchTool(workspace=tmp_path)
result = asyncio.run(
tool.execute(
edits=[
{
"path": "notes.txt",
"action": "add",
"new_text": "\nbeta",
}
]
)
)
assert "update notes.txt" in result
assert target.read_text(encoding="utf-8") == "alpha\nbeta\n"
def test_apply_patch_rejects_delete_action(tmp_path):
target = tmp_path / "utils.py"
target.write_text("def unused():\n pass\ndef used():\n return 1\n")
+76 -85
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
import pytest
from nanobot.agent.tools.shell import ExecTool
@@ -13,19 +15,84 @@ def test_deny_patterns_block_rm_rf():
assert "deny pattern filter" in result.lower()
def test_allow_patterns_bypass_deny():
"""allow_patterns take priority: matching command skips deny check."""
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/tmp/.*"])
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
@pytest.mark.parametrize(
"command, allow_pattern",
[
pytest.param("rm -rf /tmp/build", "rm\\s+-rf\\s+/tmp/.*", id="allow_patterns_bypass_deny"),
pytest.param(
"echo allowlisted 2>&1",
"echo\\s+allowlisted\\s+2>&1",
id="guard_allow_patterns_keep_fd_redirection_ampersand",
),
pytest.param(
"rm -rf /tmp/build",
"rm\\s+-rf\\s+/tmp/build",
id="allow_patterns_fullmatch_allows_exact_command",
),
pytest.param(
"echo allowlisted",
"\\becho\\s+allowlisted\\b",
id="guard_allow_patterns_allow_single_matching_segment",
),
pytest.param(
"echo allowlisted",
"^echo\\s+allowlisted$",
id="guard_allow_patterns_keep_fullmatch_style_compatibility",
),
],
)
def test_allow_patterns_accept_matching_commands(command, allow_pattern):
tool = ExecTool(allow_patterns=[allow_pattern])
result = tool._guard_command(command, "/tmp")
assert result is None
def test_allow_patterns_must_match_to_bypass():
"""Non-matching allow_patterns do NOT bypass deny."""
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/opt/"])
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
@pytest.mark.parametrize(
"command, reason, allow_pattern",
[
pytest.param(
"rm -rf /tmp/build",
"deny pattern filter",
"rm\\s+-rf\\s+/opt/",
id="allow_patterns_must_match_to_bypass",
),
pytest.param(
"echo allowlisted && touch /tmp/evil",
"allowlist",
"\\becho\\s+allowlisted\\b",
id="guard_allow_patterns_block_non_matching_chained_segment",
),
pytest.param(
"echo allowlisted & touch /tmp/evil",
"allowlist",
"echo\\s+allowlisted.*",
id="guard_allow_patterns_block_single_ampersand_chained_segment",
),
pytest.param(
"echo allowlisted\ntouch /tmp/evil",
"allowlist",
"echo\\s+allowlisted\\s*.*",
id="guard_allow_patterns_block_newline_chained_segment",
),
pytest.param(
"echo allowlisted\nrm -rf /",
"deny pattern filter",
"echo\\s+allowlisted\\s*.*",
id="guard_newline_chained_segment_still_hits_deny_patterns",
),
pytest.param(
"echo allowlisted &",
"allowlist",
"echo\\s+allowlisted",
id="guard_allow_patterns_preserve_trailing_background_operator",
),
],
)
def test_allow_patterns_do_not_bypass_rejected_commands(command, reason, allow_pattern):
tool = ExecTool(allow_patterns=[allow_pattern])
result = tool._guard_command(command, "/tmp")
assert result is not None
assert "deny pattern filter" in result.lower()
assert reason in result.lower()
def test_extra_deny_patterns_from_config():
@@ -58,42 +125,6 @@ def test_allow_patterns_is_whitelist_only():
assert "allowlist" in result.lower()
def test_guard_allow_patterns_block_non_matching_chained_segment():
"""Every top-level shell segment must match an allow pattern."""
tool = ExecTool(allow_patterns=[r"\becho\s+allowlisted\b"])
result = tool._guard_command("echo allowlisted && touch /tmp/evil", "/tmp")
assert result is not None
assert "allowlist" in result.lower()
def test_guard_allow_patterns_block_single_ampersand_chained_segment():
"""A backgrounded command is also a top-level shell segment."""
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted.*"])
result = tool._guard_command("echo allowlisted & touch /tmp/evil", "/tmp")
assert result is not None
assert "allowlist" in result.lower()
def test_guard_allow_patterns_block_newline_chained_segment():
"""A newline separates commands, so each line must match on its own."""
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted\s*.*"])
result = tool._guard_command("echo allowlisted\ntouch /tmp/evil", "/tmp")
assert result is not None
assert "allowlist" in result.lower()
def test_guard_newline_chained_segment_still_hits_deny_patterns():
"""An allowlisted first line does not exempt a denied later line."""
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted\s*.*"])
result = tool._guard_command("echo allowlisted\nrm -rf /", "/tmp")
assert result is not None
assert "deny pattern filter" 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") == [
@@ -101,23 +132,6 @@ def test_split_shell_segments_keep_line_continuation_intact():
]
def test_guard_allow_patterns_preserve_trailing_background_operator():
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted"])
result = tool._guard_command("echo allowlisted &", "/tmp")
assert result is not None
assert "allowlist" in result.lower()
def test_guard_allow_patterns_keep_fd_redirection_ampersand():
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted\s+2>&1"])
result = tool._guard_command("echo allowlisted 2>&1", "/tmp")
assert result is None
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+/"])
@@ -126,21 +140,6 @@ def test_deny_patterns_search_original_command_with_quoted_hash():
assert "deny pattern filter" in result.lower()
def test_allow_patterns_fullmatch_allows_exact_command():
"""A full-command allow pattern can still exempt an exact denied command."""
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/tmp/build"])
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
assert result is None
def test_guard_allow_patterns_allow_single_matching_segment():
tool = ExecTool(allow_patterns=[r"\becho\s+allowlisted\b"])
result = tool._guard_command("echo allowlisted", "/tmp")
assert result is None
def test_guard_allow_patterns_allow_multiple_matching_segments():
tool = ExecTool(
allow_patterns=[
@@ -152,11 +151,3 @@ def test_guard_allow_patterns_allow_multiple_matching_segments():
result = tool._guard_command("echo allowlisted && echo also_allowed", "/tmp")
assert result is None
def test_guard_allow_patterns_keep_fullmatch_style_compatibility():
tool = ExecTool(allow_patterns=[r"^echo\s+allowlisted$"])
result = tool._guard_command("echo allowlisted", "/tmp")
assert result is None
+12 -19
View File
@@ -762,13 +762,22 @@ def _make_fake_session(tool_names: list[str]) -> SimpleNamespace:
@pytest.mark.asyncio
async def test_connect_mcp_servers_enabled_tools_supports_raw_names(
fake_mcp_runtime: dict[str, object | None],
@pytest.mark.parametrize(
"enabled_tool",
[
pytest.param("demo", id="raw_names"),
pytest.param("mcp_test_demo", id="wrapped_names"),
],
)
async def test_connect_mcp_servers_enabled_tools_accepts_raw_and_wrapped_names(
fake_mcp_runtime: dict[str,
object | None],
enabled_tool,
) -> None:
fake_mcp_runtime["session"] = _make_fake_session(["demo", "other"])
registry = ToolRegistry()
stacks = await connect_mcp_servers(
{"test": MCPServerConfig(command="fake", enabled_tools=["demo"])},
{"test": MCPServerConfig(command="fake", enabled_tools=[enabled_tool])},
registry,
)
for stack in stacks.values():
@@ -793,22 +802,6 @@ async def test_connect_mcp_servers_enabled_tools_defaults_to_all(
assert registry.tool_names == ["mcp_test_demo", "mcp_test_other"]
@pytest.mark.asyncio
async def test_connect_mcp_servers_enabled_tools_supports_wrapped_names(
fake_mcp_runtime: dict[str, object | None],
) -> None:
fake_mcp_runtime["session"] = _make_fake_session(["demo", "other"])
registry = ToolRegistry()
stacks = await connect_mcp_servers(
{"test": MCPServerConfig(command="fake", enabled_tools=["mcp_test_demo"])},
registry,
)
for stack in stacks.values():
await stack.aclose()
assert registry.tool_names == ["mcp_test_demo"]
@pytest.mark.asyncio
async def test_connect_mcp_servers_enabled_tools_supports_limited_wrapped_names(
fake_mcp_runtime: dict[str, object | None],
+11 -29
View File
@@ -343,18 +343,18 @@ def test_exec_guard_blocks_home_path_outside_workspace(tmp_path) -> None:
assert "hard policy boundary" in error
def test_exec_guard_blocks_bare_tilde_cwd_escape(tmp_path) -> None:
@pytest.mark.parametrize(
"command",
[
pytest.param("cd ~ && cat secret.txt", id="bare_tilde_cwd_escape"),
pytest.param("cat ~root/.bashrc", id="named_user_home_path"),
pytest.param("cat --config=~/.nanobot/config.json", id="equals_home_path_outside_workspace"),
pytest.param("cat --config=~root/.bashrc", id="equals_named_user_home_path"),
],
)
def test_exec_guard_blocks_home_paths_outside_workspace(tmp_path, command) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("cd ~ && cat secret.txt", str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
def test_exec_guard_blocks_named_user_home_path(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("cat ~root/.bashrc", str(tmp_path))
error = tool._guard_command(command, str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
@@ -385,24 +385,6 @@ def test_exec_guard_allows_current_directory_tilde(tmp_path) -> None:
assert tool._guard_command("cat ~+/file.txt", str(tmp_path)) is None
def test_exec_guard_blocks_equals_home_path_outside_workspace(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("cat --config=~/.nanobot/config.json", str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
def test_exec_guard_blocks_equals_named_user_home_path(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("cat --config=~root/.bashrc", str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
def test_exec_guard_blocks_quoted_home_path_outside_workspace(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command('cat "~/.nanobot/config.json"', str(tmp_path))
+10 -27
View File
@@ -71,13 +71,6 @@ def test_clean_url_passes_validation():
assert is_valid
def test_backtick_url_produces_empty_scheme_in_urlparse():
from urllib.parse import urlparse
p = urlparse("`https://example.com/page`")
assert p.scheme == ""
assert p.netloc == ""
# --- WebFetchTool.execute integration tests ---
@pytest.mark.asyncio
@@ -103,27 +96,17 @@ async def test_execute_accepts_cleanable_http_urls(url):
# --- startswith guard tests ---
@pytest.mark.asyncio
async def test_execute_rejects_non_http_url_after_cleaning():
@pytest.mark.parametrize(
"url",
[
pytest.param("ftp://example.com/file", id="non_http_url_after_cleaning"),
pytest.param("`not a url at all`", id="garbage_after_cleaning"),
pytest.param("`example.com/page`", id="bare_domain_after_cleaning"),
],
)
async def test_execute_rejects_invalid_url_after_cleaning(url):
tool = WebFetchTool()
result = await tool.execute(url="ftp://example.com/file")
data = json.loads(result)
assert "error" in data
assert "URL validation failed" in data["error"]
@pytest.mark.asyncio
async def test_execute_rejects_garbage_after_cleaning():
tool = WebFetchTool()
result = await tool.execute(url="`not a url at all`")
data = json.loads(result)
assert "error" in data
assert "URL validation failed" in data["error"]
@pytest.mark.asyncio
async def test_execute_rejects_bare_domain_after_cleaning():
tool = WebFetchTool()
result = await tool.execute(url="`example.com/page`")
result = await tool.execute(url=url)
data = json.loads(result)
assert "error" in data
assert "URL validation failed" in data["error"]
+31 -66
View File
@@ -42,11 +42,26 @@ def test_brave_with_api_key_remains_concurrency_safe():
assert tool.concurrency_safe is True
def test_brave_without_api_key_is_treated_as_duckduckgo_for_concurrency(monkeypatch):
monkeypatch.delenv("BRAVE_API_KEY", raising=False)
tool = _tool(provider="brave", api_key="")
assert tool.exclusive is True
assert tool.concurrency_safe is False
@pytest.mark.parametrize(
"env_key, expected_exclusive, expected_safe, provider",
[
pytest.param("BRAVE_API_KEY", True, False, "brave", id="brave-fallback"),
pytest.param("KEENABLE_API_KEY", False, True, "keenable", id="keenable"),
pytest.param("SERPER_API_KEY", True, False, "serper", id="serper-fallback"),
pytest.param("ANYSEARCH_API_KEY", False, True, "anysearch", id="anysearch"),
],
)
def test_search_concurrency_without_api_key(
monkeypatch,
env_key,
expected_exclusive,
expected_safe,
provider,
):
monkeypatch.delenv(env_key, raising=False)
tool = _tool(provider=provider, api_key="")
assert tool.exclusive is expected_exclusive
assert tool.concurrency_safe is expected_safe
@pytest.mark.asyncio
@@ -132,13 +147,6 @@ async def test_tavily_search(monkeypatch):
assert "https://openclaw.io" in result
def test_keenable_without_api_key_is_concurrency_safe(monkeypatch):
monkeypatch.delenv("KEENABLE_API_KEY", raising=False)
tool = _tool(provider="keenable", api_key="")
assert tool.exclusive is False
assert tool.concurrency_safe is True
@pytest.mark.asyncio
async def test_keenable_search(monkeypatch):
async def mock_post(self, url, **kw):
@@ -202,14 +210,6 @@ async def test_keenable_search_http_error(monkeypatch):
assert "Error: Keenable search failed (401)" in result
def test_serper_without_api_key_is_treated_as_duckduckgo(monkeypatch):
# Serper requires a key; without one we fall back to DuckDuckGo for concurrency.
monkeypatch.delenv("SERPER_API_KEY", raising=False)
tool = _tool(provider="serper", api_key="")
assert tool.exclusive is True
assert tool.concurrency_safe is False
@pytest.mark.asyncio
async def test_serper_search(monkeypatch):
async def mock_post(self, url, **kw):
@@ -287,15 +287,6 @@ async def test_serper_search_rate_limited(monkeypatch):
assert is_tool_error_result(result)
def test_anysearch_remains_concurrency_safe_without_api_key(monkeypatch):
# Unlike keyed providers, AnySearch works without a key (anonymous quota),
# so it must never be treated as exclusive/serialized.
monkeypatch.delenv("ANYSEARCH_API_KEY", raising=False)
tool = _tool(provider="anysearch", api_key="")
assert tool.exclusive is False
assert tool.concurrency_safe is True
@pytest.mark.asyncio
async def test_anysearch_search(monkeypatch):
async def mock_post(self, url, **kw):
@@ -575,7 +566,15 @@ async def test_duckduckgo_search_passes_proxy(monkeypatch):
@pytest.mark.asyncio
async def test_brave_fallback_to_duckduckgo_when_no_key(monkeypatch):
@pytest.mark.parametrize(
"env_key, provider",
[
pytest.param("BRAVE_API_KEY", "brave", id="brave_fallback_to_duckduckgo_when_no_key"),
pytest.param("KAGI_API_KEY", "kagi", id="kagi_fallback_to_duckduckgo_when_no_key"),
pytest.param("EXA_API_KEY", "exa", id="exa_fallback_to_duckduckgo_when_no_key"),
],
)
async def test_provider_falls_back_to_duckduckgo_without_key(monkeypatch, env_key, provider):
class MockDDGS:
def __init__(self, **kw):
pass
@@ -584,9 +583,9 @@ async def test_brave_fallback_to_duckduckgo_when_no_key(monkeypatch):
return [{"title": "Fallback", "href": "https://ddg.example", "body": "DuckDuckGo fallback"}]
monkeypatch.setattr("ddgs.DDGS", MockDDGS)
monkeypatch.delenv("BRAVE_API_KEY", raising=False)
monkeypatch.delenv(env_key, raising=False)
tool = _tool(provider="brave", api_key="")
tool = _tool(provider=provider, api_key="")
result = await tool.execute(query="test")
assert "Fallback" in result
@@ -768,40 +767,6 @@ async def test_jina_422_falls_back_to_duckduckgo(monkeypatch):
assert "DuckDuckGo fallback" in result
@pytest.mark.asyncio
async def test_kagi_fallback_to_duckduckgo_when_no_key(monkeypatch):
class MockDDGS:
def __init__(self, **kw):
pass
def text(self, query, max_results=5):
return [{"title": "Fallback", "href": "https://ddg.example", "body": "DuckDuckGo fallback"}]
monkeypatch.setattr("ddgs.DDGS", MockDDGS)
monkeypatch.delenv("KAGI_API_KEY", raising=False)
tool = _tool(provider="kagi", api_key="")
result = await tool.execute(query="test")
assert "Fallback" in result
@pytest.mark.asyncio
async def test_exa_fallback_to_duckduckgo_when_no_key(monkeypatch):
class MockDDGS:
def __init__(self, **kw):
pass
def text(self, query, max_results=5):
return [{"title": "Fallback", "href": "https://ddg.example", "body": "DuckDuckGo fallback"}]
monkeypatch.setattr("ddgs.DDGS", MockDDGS)
monkeypatch.delenv("EXA_API_KEY", raising=False)
tool = _tool(provider="exa", api_key="")
result = await tool.execute(query="test")
assert "Fallback" in result
@pytest.mark.asyncio
async def test_jina_search_uses_path_encoded_query(monkeypatch):
calls = {}