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

+4 -13
View File
@@ -507,26 +507,17 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_no_summary_when_compact_returns_empty(self):
ac = _make_autocompact()
mock_sm = _mock_sessions()
ac.sessions = mock_sm
mock_sm.get_or_create.return_value = _make_session(metadata={
"_last_summary": {"text": "Previous checkpoint.", "last_active": "2026-05-13T10:00:00"},
})
ac = _make_autocompact(sessions=mock_sm)
ac.consolidator.compact_idle_session = AsyncMock(return_value="")
await ac._archive("cli:test", runtime=_runtime())
assert "cli:test" not in ac._summaries
@pytest.mark.asyncio
async def test_no_summary_when_compact_returns_nothing(self):
ac = _make_autocompact()
mock_sm = _mock_sessions()
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="(nothing)")
await ac._archive("cli:test", runtime=_runtime())
assert "cli:test" not in ac._summaries
@pytest.mark.asyncio
async def test_exception_still_removes_from_archiving(self):
ac = _make_autocompact()
+20 -5
View File
@@ -1,21 +1,36 @@
from __future__ import annotations
from nanobot.agent.tools.context import ContextAware, RequestContext
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.context import ContextAware, RequestContext, request_context
from nanobot.agent.tools.registry import ToolRegistry
class _ContextTool:
class _ContextTool(Tool):
name = "legacy_context"
description = "External-style tool using the legacy context setter."
parameters = {"type": "object", "properties": {}}
def __init__(self):
self.last_ctx = None
def set_context(self, ctx: RequestContext) -> None:
self.last_ctx = ctx
async def execute(self, **kwargs):
return self.last_ctx
def test_context_aware_sets_request_context():
async def test_registry_injects_request_context_into_legacy_tool():
tool = _ContextTool()
registry = ToolRegistry()
registry.register(tool)
ctx = RequestContext(channel="test", chat_id="123", session_key="test:123")
tool.set_context(ctx)
assert tool.last_ctx.channel == "test"
with request_context(ctx):
result = await registry.execute(tool.name, {})
assert result is ctx
assert tool.last_ctx is ctx
def test_context_tool_is_instance_of_context_aware():
+4 -7
View File
@@ -281,16 +281,13 @@ class TestBuildUserContent:
class TestBuildSystemPrompt:
def test_returns_nonempty_string(self, tmp_path):
builder = _builder(tmp_path)
result = builder.build_system_prompt()
assert isinstance(result, str)
assert len(result) > 0
def test_includes_identity_section(self, tmp_path):
builder = _builder(tmp_path)
result = builder.build_system_prompt()
assert "workspace" in result.lower() or "python" in result.lower()
assert "## Runtime\n" in result
assert "Agent profile: SOUL.md and USER.md" in result
assert "History log: memory/history.jsonl" in result
def test_default_identity_uses_relative_agent_paths(self, tmp_path):
result = ContextBuilder(tmp_path)._get_identity()
-14
View File
@@ -289,20 +289,6 @@ async def test_composite_error_isolation_all_async():
# ---------------------------------------------------------------------------
def test_composite_finalize_content_pipeline():
class Upper(AgentHook):
def finalize_content(self, context, content):
return content.upper() if content else content
class Suffix(AgentHook):
def finalize_content(self, context, content):
return (content + "!") if content else content
hook = CompositeHook([Upper(), Suffix()])
result = hook.finalize_content(_ctx(), "hello")
assert result == "HELLO!"
def test_composite_finalize_content_none_passthrough():
hook = CompositeHook([AgentHook()])
assert hook.finalize_content(_ctx(), None) is None
+32 -15
View File
@@ -64,8 +64,8 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
release = threading.Event()
captured = []
finalized = []
ticks = []
ticking = True
heartbeat_requested = asyncio.Event()
heartbeat_progress = asyncio.Event()
class Lifecycle(AgentHook):
async def on_finally(self, context):
@@ -77,15 +77,16 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
context.messages[0]["content"] = "hook-only"
async def heartbeat():
while ticking:
ticks.append(runtime_loop.time())
await asyncio.sleep(0.01)
while True:
await heartbeat_requested.wait()
heartbeat_requested.clear()
heartbeat_progress.set()
def blocked(operation, *args, **kwargs):
captured.append((current_request_context(), current_workspace_scope(), threading.get_ident()))
runtime_loop.call_soon_threadsafe(entered.set)
try:
assert release.wait(5), "test did not release prompt preparation"
assert release.wait(10), "test did not release prompt preparation"
return operation(*args, **kwargs)
finally:
runtime_loop.call_soon_threadsafe(finished.set)
@@ -127,11 +128,11 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
tasks = [task, pulse]
try:
await asyncio.wait_for(entered.wait(), timeout=5)
before = len(ticks)
status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 0.5)
status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 5)
assert status is not None and "test-model" in status.content
await asyncio.sleep(0.04)
assert len(ticks) >= before + 2
heartbeat_requested.set()
await asyncio.wait_for(heartbeat_progress.wait(), 5)
assert not release.is_set()
assert not finished.is_set()
assert captured[0][2] != threading.get_ident()
if phase != "history":
@@ -145,7 +146,7 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
if cancel:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(task, 0.5)
await asyncio.wait_for(task, 5)
assert not finished.is_set()
if phase != "history":
assert len(finalized) == 1
@@ -155,15 +156,32 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
assert final_loop is runtime_loop
if phase != "prompt":
assert snapshot
# A new session queues behind the physical worker, even after its caller exits.
# Observe the new session entering the real semaphore, not a settling delay.
slots = loop.runner.context_governor._preparation_slots
acquire_slot = slots.acquire
queued = asyncio.Event()
acquired = asyncio.Event()
async def acquire():
# History preparation queues before RequestContext is bound.
is_waiting = asyncio.current_task() is waiting
if is_waiting:
queued.set()
result = await acquire_slot()
if is_waiting:
acquired.set()
return result
monkeypatch.setattr(slots, "acquire", acquire)
waiting = asyncio.create_task(loop.process_direct("Queued", session_key="cli:waiting"))
tasks.append(waiting)
await asyncio.sleep(0.04)
await asyncio.wait_for(queued.wait(), 5)
assert not acquired.is_set()
assert len(provider.requests) == expected_requests
assert not waiting.done()
waiting.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(waiting, 0.5)
await asyncio.wait_for(waiting, 5)
elif phase == "history":
# The live nested payload may change after capture; the worker owns its copy.
live.messages[0]["content"][0]["text"] = "Changed after capture"
@@ -184,7 +202,6 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
assert current_request_context() is None
assert current_workspace_scope() is None
finally:
ticking = False
release.set()
for pending in tasks:
if not pending.done():
-34
View File
@@ -1487,40 +1487,6 @@ async def test_runner_backfill_only_mutates_model_context_not_returned_messages(
]
def test_governance_repairs_orphans_after_history_rewrite():
"""A rewritten history drops tool results whose calls are no longer present."""
rewritten = [
{"role": "system", "content": "system"},
{"role": "tool", "tool_call_id": "tc_old", "name": "search",
"content": "old result"},
{"role": "assistant", "content": "old answer"},
{"role": "user", "content": "new msg"},
]
cleaned = ContextGovernor.drop_orphan_tool_results(rewritten)
# The orphan tool result should be removed.
assert not any(
m.get("role") == "tool" and m.get("tool_call_id") == "tc_old"
for m in cleaned
)
def test_governance_fallback_still_repairs_orphans():
"""When full governance fails, the fallback must still repair orphans."""
# Messages with an orphan tool result (no matching assistant tool_call).
messages = [
{"role": "user", "content": "hello"},
{"role": "tool", "tool_call_id": "orphan_tc", "name": "read",
"content": "stale"},
{"role": "assistant", "content": "hi"},
]
repaired = ContextGovernor.drop_orphan_tool_results(messages)
repaired = ContextGovernor.backfill_missing_tool_results(repaired)
# Orphan tool result should be gone.
assert not any(m.get("tool_call_id") == "orphan_tc" for m in repaired)
# ---------------------------------------------------------------------------
# Malformed tool_call name guard (missing/non-string name wedges the session
# upstream: messages.content.N.tool_use.name: Input should be a valid string)
+15
View File
@@ -182,6 +182,21 @@ async def test_runner_lets_llm_recover_from_shell_guard_path_outside():
assert result.tool_events and result.tool_events[0]["status"] == "error"
# v2: detail keeps the breadcrumb but the runner did not raise.
assert "workspace_violation" in result.tool_events[0]["detail"]
calls = [
call
for message in captured_second_call if message.get("role") == "assistant"
for call in message.get("tool_calls", []) if call["id"] == "call_blocked"
]
assert len(calls) == 1
assert calls[0]["function"]["name"] == "exec"
rejections = [
message for message in captured_second_call
if message.get("role") == "tool" and message.get("tool_call_id") == "call_blocked"
]
assert len(rejections) == 1
assert rejections[0]["name"] == "exec"
assert "Command blocked by safety guard (path outside working dir)" in rejections[0]["content"]
assert "Consider this result in the context of the user's goal" in rejections[0]["content"]
@pytest.mark.asyncio
+1 -61
View File
@@ -147,6 +147,7 @@ class TestInspectPathNavigation:
@pytest.mark.asyncio
async def test_inspect_config_subfield(self):
"""Positive control for sensitive-field blocking: ordinary config stays inspectable."""
loop = _make_mock_loop()
tool = _make_tool(loop=loop)
result = await tool.execute(action="check", key="web_config.enable")
@@ -649,60 +650,6 @@ class TestSubagentHookStatus:
assert context.iteration == 1
# ---------------------------------------------------------------------------
# Checkpoint callback updates status
# ---------------------------------------------------------------------------
class TestCheckpointCallback:
@pytest.mark.asyncio
async def test_checkpoint_updates_phase_and_iteration(self):
"""The _on_checkpoint callback should update status.phase and iteration."""
from nanobot.agent.subagent import SubagentStatus
status = SubagentStatus(
task_id="cp",
label="test",
task_description="test",
started_at=time.monotonic(),
)
# Simulate the checkpoint callback as defined in _run_subagent
async def _on_checkpoint(payload: dict) -> None:
status.phase = payload.get("phase", status.phase)
status.iteration = payload.get("iteration", status.iteration)
await _on_checkpoint({"phase": "awaiting_tools", "iteration": 2})
assert status.phase == "awaiting_tools"
assert status.iteration == 2
await _on_checkpoint({"phase": "tools_completed", "iteration": 3})
assert status.phase == "tools_completed"
assert status.iteration == 3
@pytest.mark.asyncio
async def test_checkpoint_preserves_phase_on_missing_key(self):
"""If payload doesn't have 'phase', status.phase should stay unchanged."""
from nanobot.agent.subagent import SubagentStatus
status = SubagentStatus(
task_id="cp",
label="test",
task_description="test",
started_at=time.monotonic(),
phase="initializing",
)
async def _on_checkpoint(payload: dict) -> None:
status.phase = payload.get("phase", status.phase)
status.iteration = payload.get("iteration", status.iteration)
await _on_checkpoint({"iteration": 1})
assert status.phase == "initializing"
assert status.iteration == 1
# ---------------------------------------------------------------------------
# read-only mode (tools.my.allow_set=False)
# ---------------------------------------------------------------------------
@@ -819,13 +766,6 @@ class TestSensitiveSubFieldBlocking:
result = await tool.execute(action="set", key="some_config.password", value="evil")
assert "not accessible" in result
@pytest.mark.asyncio
async def test_inspect_non_sensitive_subfield_allowed(self):
"""web_config.enable should still be inspectable."""
tool = _make_tool()
result = await tool.execute(action="check", key="web_config.enable")
assert "True" in result
@pytest.mark.asyncio
async def test_modify_sensitive_top_level_blocked(self):
"""Top-level key matching sensitive name must be blocked for set."""
+68 -24
View File
@@ -110,19 +110,13 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
)
mgr._announce_result = AsyncMock()
async def fake_run(spec):
exec_tool = spec.tools.get("exec")
assert exec_tool is not None
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
return AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
)
mgr.runner.run = AsyncMock(side_effect=fake_run)
mgr.runner.run = AsyncMock(return_value=AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
))
await mgr.spawn(
task="do task",
@@ -134,6 +128,11 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr.runner.run.assert_awaited_once()
spec = mgr.runner.run.await_args.args[0]
exec_tool = spec.tools.get("exec")
assert exec_tool is not None
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]
@pytest.mark.asyncio
@@ -154,17 +153,13 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
)
mgr._announce_result = AsyncMock()
async def fake_run(spec):
assert spec.max_iterations == 37
return AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
)
mgr.runner.run = AsyncMock(side_effect=fake_run)
mgr.runner.run = AsyncMock(return_value=AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
))
await mgr.spawn(
task="do task",
@@ -176,6 +171,55 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr.runner.run.assert_awaited_once()
spec = mgr.runner.run.await_args.args[0]
assert spec.max_iterations == 37
assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]
@pytest.mark.asyncio
async def test_subagent_checkpoint_updates_status_and_preserves_omitted_fields(tmp_path):
"""Runner checkpoints update detached task snapshots without resetting omitted fields."""
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
mgr = SubagentManager(
consolidator=MagicMock(spec=Consolidator),
workspace=tmp_path,
bus=MessageBus(),
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
)
mgr._announce_result = AsyncMock()
snapshots = []
async def fake_run(spec):
for payload in [
{"phase": "awaiting_tools", "iteration": 2},
{"phase": "tools_completed", "iteration": 3},
{"iteration": 4},
{"phase": "final_response"},
]:
await spec.checkpoint_callback(payload)
snapshots.extend(mgr.statuses_for_session("test:c1").values())
return AgentRunResult(
messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
)
mgr.runner.run = AsyncMock(side_effect=fake_run)
await mgr.spawn(task="do task", session_key="test:c1", runtime=_runtime(MagicMock()))
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
assert [(s.state, s.phase, s.iteration) for s in snapshots] == [
("running", "awaiting_tools", 2),
("running", "tools_completed", 3),
("running", "tools_completed", 4),
("running", "final_response", 4),
]
assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]
@pytest.mark.asyncio