Commit 2e28580c by sunqi02 Committed by 胡悦

test: add self-call guard, sub-agent persistence, and shielding tests

1 parent f92e1eed
......@@ -1101,3 +1101,85 @@ class TestSubAgentPostReply:
assert call_count == 2
should_send = call_count != 1
assert should_send is True
import asyncio
# ── 自调用防护 & 子Agent 消息持久化测试 ──────────────────────────
class TestSelfCallGuard:
"""验证 _call_sub_agent 的自调用防护和子Agent消息落地。"""
def test_rejects_steward_self_call(self):
"""主Agent 不允许调用自己的 code → 返回错误提示。"""
hub = _make_test_hub()
steward_key = hub._find_steward_key()
result = asyncio.run(hub._call_sub_agent(steward_key, "测试指令"))
assert "不允许主Agent自调用" in result
assert "发言人Agent" in result
def test_rejects_unknown_agent(self):
"""调用不存在的 agent code → 返回错误提示。"""
hub = _make_test_hub()
result = asyncio.run(hub._call_sub_agent("nonexistent_999", "测试指令"))
assert "不存在" in result
def test_save_tool_interactions_with_default_agent_code(self):
"""传入 default_agent_code 时,tool_use/tool_result 使用该 code。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-default-agent-code"
# SessionMemory.add() 要求 session 已存在,否则静默跳过
store.set(sid, {"conversation_history": []})
mem = SessionMemory(sid, store)
# 模拟一个 Msg 对象(使用 MagicMock)
fake_msg = MagicMock()
fake_msg.content = [
{"type": "tool_use", "name": "read_file", "input": {"file_path": "test.txt"}},
]
AgentHub._save_tool_interactions(mem, [fake_msg], default_agent_code="17")
history = store.get(sid).get("conversation_history", [])
assert len(history) == 1
assert history[0]["agent_code"] == "17"
def test_save_tool_interactions_without_default_agent_code(self):
"""不传 default_agent_code 时,使用 block 的 name 作为 agent_code。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-no-default-code"
# SessionMemory.add() 要求 session 已存在,否则静默跳过
store.set(sid, {"conversation_history": []})
mem = SessionMemory(sid, store)
fake_msg = MagicMock()
fake_msg.content = [
{"type": "tool_use", "name": "read_file", "input": {"file_path": "test.txt"}},
]
AgentHub._save_tool_interactions(mem, [fake_msg])
history = store.get(sid).get("conversation_history", [])
assert len(history) == 1
assert history[0]["agent_code"] == "read_file"
class TestMessageShielding:
"""验证主Agent 消息屏蔽逻辑。"""
def test_call_count_zero_sends_reply(self):
"""call_count == 0 → 需正常发送和存 DB。"""
ctx = {"call_count": 0}
assert ctx["call_count"] == 0
def test_call_count_one_shields_reply(self):
"""call_count >= 1 → 不发送、不存 DB。"""
ctx = {"call_count": 1}
assert ctx["call_count"] >= 1
def test_call_count_multi_shields_reply(self):
"""call_count >= 2 → 同样不发送、不存 DB。"""
ctx = {"call_count": 3}
assert ctx["call_count"] >= 1
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!