test: replace false-green checks with behavioral coverage (#6282)

* test: replace false-green checks with behavioral coverage

* test: complete behavior-focused audit coverage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-18 03:16:25 +08:00
1 parent c7ab7aa6da
commit 74942bd190
91 files changed
+1891 -1391

No files matched your search

+50 -1
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
@@ -415,7 +416,7 @@ def test_apply_patch_edits_reports_invalid_edit_shapes(tmp_path):
assert "each edit must be an object" in non_object
def test_apply_patch_edits_rolls_back_when_late_operation_fails(tmp_path):
def test_apply_patch_preflight_rejects_missing_later_file_without_partial_write(tmp_path):
first = tmp_path / "first.txt"
first.write_text("before\n")
tool = ApplyPatchTool(workspace=tmp_path)
@@ -441,3 +442,51 @@ def test_apply_patch_edits_rolls_back_when_late_operation_fails(tmp_path):
assert "file to update does not exist: missing.txt" in result
assert first.read_text() == "before\n"
@pytest.mark.parametrize("first_exists", [True, False], ids=["existing-file", "added-file"])
def test_apply_patch_edits_rolls_back_when_later_write_fails(tmp_path, monkeypatch, first_exists):
first = tmp_path / "first.txt"
first_original = b"before\r\nfirst tail"
if first_exists:
first.write_bytes(first_original)
second = tmp_path / "second.txt"
second_original = b"before\r\nsecond tail"
second.write_bytes(second_original)
tool = ApplyPatchTool(workspace=tmp_path)
write_text = Path.write_text
failed = False
def _fail_second_write(path, *args, **kwargs):
nonlocal failed
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
monkeypatch.setattr(Path, "write_text", _fail_second_write)
result = asyncio.run(
tool.execute(
edits=[
{"path": "first.txt", "action": "add", "new_text": "after"},
{
"path": "second.txt",
"action": "replace",
"old_text": "before",
"new_text": "after",
},
]
)
)
assert failed
assert getattr(result, "is_error", False)
assert "Error applying patch: injected second write failure" in result
if first_exists:
assert first.read_bytes() == first_original
else:
assert not first.exists()
assert second.read_bytes() == second_original
+1 -1
View File
@@ -136,7 +136,7 @@ class TestEditIpynbFiles:
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
)
assert "Patch applied:" in result
assert '"source": "hi"' in f.read_text(encoding="utf-8")
assert f.read_text(encoding="utf-8") == '{"cells": [{"cell_type": "markdown", "source": "hi"}]}'
# ---------------------------------------------------------------------------
+45 -37
View File
@@ -1,22 +1,61 @@
"""Tests for exec tool environment isolation."""
import json
import shlex
import sys
import pytest
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.agent.tools.shell import ExecTool
_UNIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="Unix shell commands")
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_does_not_leak_parent_env(monkeypatch):
"""Env vars from the parent process must not be visible to commands."""
@pytest.mark.parametrize(
"allowed_env_keys, expected_allowed",
[
pytest.param(None, None, id="default-filtering"),
pytest.param(
["MY_CUSTOM_VAR", "NONEXISTENT_VAR_12345"],
"hello-from-config",
id="configured-passthrough",
),
],
)
@pytest.mark.parametrize(
"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")
tool = ExecTool()
result = await tool.execute(command="printenv NANOBOT_SECRET_TOKEN")
assert "super-secret-value" not in result
monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)
marker = "ENV_PROBE_COMPLETE "
script = (
"import json, os; "
"keys = ['MY_CUSTOM_VAR', 'NANOBOT_SECRET_TOKEN', 'NONEXISTENT_VAR_12345']; "
f"print({marker!r} + json.dumps({{key: os.environ.get(key) for key in keys}}))"
)
argv = [sys.executable, "-c", script]
command = shlex.join(argv) if command_mode == "shell" else argv
manager = ExecSessionManager()
tool = ExecTool(allowed_env_keys=allowed_env_keys, session_manager=manager)
try:
result = await tool.execute(command=command)
finally:
await manager.close_all()
assert not getattr(result, "is_error", False), result
assert "Exit code: 0" in result
completed = [line.removeprefix(marker) for line in result.splitlines() if line.startswith(marker)]
assert len(completed) == 1, result
assert json.loads(completed[0]) == {
"MY_CUSTOM_VAR": expected_allowed,
"NANOBOT_SECRET_TOKEN": None,
"NONEXISTENT_VAR_12345": None,
}
@pytest.mark.asyncio
@@ -67,37 +106,6 @@ async def test_exec_path_prepend_takes_lookup_precedence(tmp_path):
assert "fallback" not in result
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_allowed_env_keys_passthrough(monkeypatch):
"""Env vars listed in allowed_env_keys should be visible to commands."""
monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")
tool = ExecTool(allowed_env_keys=["MY_CUSTOM_VAR"])
result = await tool.execute(command="printenv MY_CUSTOM_VAR")
assert "hello-from-config" in result
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_allowed_env_keys_does_not_leak_others(monkeypatch):
"""Env vars NOT in allowed_env_keys should still be blocked."""
monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")
monkeypatch.setenv("MY_SECRET_VAR", "secret-value")
tool = ExecTool(allowed_env_keys=["MY_CUSTOM_VAR"])
result = await tool.execute(command="printenv MY_SECRET_VAR")
assert "secret-value" not in result
@_UNIX_ONLY
@pytest.mark.asyncio
async def test_exec_allowed_env_keys_missing_var_ignored(monkeypatch):
"""If an allowed key is not set in the parent process, it should be silently skipped."""
monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)
tool = ExecTool(allowed_env_keys=["NONEXISTENT_VAR_12345"])
result = await tool.execute(command="printenv NONEXISTENT_VAR_12345")
assert "Exit code: 1" in result
# --- path_append injection prevention ------------------------------------
+27 -12
View File
@@ -149,22 +149,37 @@ def test_exec_returns_completed_session_output_when_yield_time_ms_is_used(tmp_pa
def test_exec_session_yield_returns_when_process_finishes_early(tmp_path):
async def run() -> tuple[str, str, float]:
async def run() -> str:
manager = ExecSessionManager()
tool = ExecTool(working_dir=str(tmp_path), timeout=5, session_manager=manager)
stdin_tool = ExecSessionTool(manager=manager)
command = _python_command("import time; time.sleep(0.1); print('done')")
started = time.monotonic()
initial = await tool.execute(command=command, yield_time_ms=1200)
result, final = await _poll_if_running(initial, stdin_tool)
return result, final, time.monotonic() - started
tool = ExecTool(working_dir=str(tmp_path), timeout=20, session_manager=manager)
ready, release = tmp_path / "ready", tmp_path / "release"
command = _python_command(
"from pathlib import Path\nimport time\n"
"Path('ready').write_text('ready')\n"
"while not Path('release').exists(): time.sleep(0.01)\n"
"print('done')"
)
pending = asyncio.create_task(tool.execute(command=command, yield_time_ms=15000))
try:
async with asyncio.timeout(10):
while not ready.exists():
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:
release.touch()
pending.cancel()
await asyncio.gather(pending, return_exceptions=True)
await manager.close_all()
result, final, elapsed = asyncio.run(run())
result = asyncio.run(run())
assert "done" in result
assert "Exit code: 0" in final
assert "session_id:" not in final
assert elapsed < 4.0
assert "Exit code: 0" in result
assert "session_id:" not in result
def test_bounded_output_buffer_keeps_head_tail_and_exact_drop_count():
@@ -122,21 +122,6 @@ def test_edit_file_line_hint_can_cover_multiline_match(tmp_path):
assert target.read_text() == "before\nstart\nchanged\nend\nafter\n"
def test_edit_file_can_edit_ipynb_as_json(tmp_path):
target = tmp_path / "analysis.ipynb"
target.write_text('{"cells": []}')
tool = EditFileTool(workspace=tmp_path)
result = asyncio.run(tool.execute(
path=str(target),
old_text='"cells": []',
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
))
assert "Patch applied:" in result
assert '"source": "hi"' in target.read_text()
def test_edit_file_multiple_match_hint_mentions_occurrence(tmp_path):
target = tmp_path / "duplicate.txt"
target.write_text("same\nsame\n")
+18 -11
View File
@@ -50,14 +50,17 @@ async def test_probe_returns_true_for_open_port(tmp_path):
@pytest.mark.asyncio
async def test_probe_returns_false_for_closed_port():
"""Port 19999 is almost certainly not listening."""
assert await _probe_http_url("http://127.0.0.1:19999/mcp") is False
@pytest.mark.asyncio
async def test_probe_uses_default_port_for_http(monkeypatch: pytest.MonkeyPatch):
"""When no port is present, probe the validated address on port 80."""
@pytest.mark.parametrize(
"url, expected_port",
[
("http://unreachable-host.test/mcp", 80),
("http://unreachable-host.test:19999/mcp", 19999),
],
)
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(
@@ -71,8 +74,8 @@ async def test_probe_uses_default_port_for_http(monkeypatch: pytest.MonkeyPatch)
monkeypatch.setattr("nanobot.agent.tools.mcp.asyncio.open_connection", _open_connection)
assert await _probe_http_url("http://unreachable-host.test/mcp") is False
assert attempts == [("93.184.216.34", 80)]
assert await _probe_http_url(url) is False
assert attempts == [("93.184.216.34", expected_port)]
@pytest.mark.asyncio
@@ -80,8 +83,12 @@ async def test_probe_rejects_public_name_resolving_to_loopback():
def _resolver(hostname, port, family=0, type_=0):
return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 0))]
with patch("nanobot.security.network.socket.getaddrinfo", _resolver):
with (
patch("nanobot.security.network.socket.getaddrinfo", _resolver),
patch("nanobot.agent.tools.mcp.asyncio.open_connection") as open_connection,
):
assert await _probe_http_url("http://example.com:8765/mcp") is False
open_connection.assert_not_called()
@pytest.mark.asyncio