Files
xieyi-weixin-/test_assistant_handoff.py
T
2026-09-30 19:30:58 +08:00

156 lines
8.2 KiB
Python

# -*- coding: utf-8 -*-
"""转人工也提醒医疗助理:已有待审提醒改成转人工(发过的不重发),没有就新建;不再挡住会话。
提醒库、设置都放在临时目录;不连企业微信、不发送。
"""
import ast
import json
import sqlite3
import tempfile
import unittest
from contextlib import closing
from pathlib import Path
import review_assistant as ra
ROOT = Path(__file__).resolve().parent
ACCOUNT = "1688856770803435"
RECIPIENT = "S:1688856770803435_7881300000000001"
CUSTOMER = "S:1688856770803435_7881300000000002"
def settings(enabled=True):
return {ra.SETTINGS_KEY: {ACCOUNT: {"enabled": enabled, "recipient_conv_id": RECIPIENT}}}
def context(*texts):
messages = [{"account": ACCOUNT, "conv_id": CUSTOMER, "is_self": False, "content": text,
"rowid": index + 1, "send_time": 1000 + index, "dedup_key": f"d{index}", "content_type": 0}
for index, text in enumerate(texts)]
return {"account": ACCOUNT, "conv_id": CUSTOMER, "display_name": "客户甲", "messages": messages}
def state(**extra):
base = {"account": ACCOUNT, "conv_id": CUSTOMER, "display_name": "客户甲", "stage": "awaiting_review",
"awaiting_review": True, "review_reason": "人工审核后点击“通过并发送”", "reply_text": "AI 草稿",
"staged_user_text": "这个药怎么吃", "dedup_key": "d0"}
base.update(extra)
return base
class HandoffTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.config = settings()
self.assistant = ra.ReviewAssistantCoordinator(root=self.root, settings_loader=lambda: self.config,
account=ACCOUNT)
self.addCleanup(self.assistant.close)
def episode(self, episode_id):
with closing(sqlite3.connect(self.root / "review_assistant.sqlite3")) as conn:
row = conn.execute("SELECT status, data FROM episodes WHERE id=?", (episode_id,)).fetchone()
return row[0], json.loads(row[1])
def test_new_handoff_reminder_is_created_and_does_not_block(self):
episode_id = self.assistant.notify_handoff(state(), context("这个药怎么吃"))
self.assertTrue(episode_id)
status, item = self.episode(episode_id)
self.assertEqual(status, "handoff")
self.assertEqual(item["notification"], "pending")
self.assertEqual(item["recipient"], RECIPIENT)
self.assertTrue(item["notification_text"].startswith("【客户已转人工】"))
self.assertIn("客服已把该会话从自动回复队列转为人工处理", item["notification_text"])
self.assertIn("客服已转人工", item["reason"])
self.assertFalse(self.assistant.has_pending(CUSTOMER), "转人工提醒不能再挡住这个会话的自动回复")
self.assertEqual(self.assistant.notify_handoff(state(), context("这个药怎么吃")), episode_id, "重复转人工不重复登记")
def test_pending_review_not_yet_sent_becomes_a_handoff_reminder(self):
review_id = self.assistant.ensure_review(state(), context("这个药怎么吃"))
self.assertTrue(self.assistant.has_pending(CUSTOMER))
self.assertEqual(self.assistant.notify_handoff(state(assistant_review_id=review_id)), review_id)
status, item = self.episode(review_id)
self.assertEqual(status, "handoff")
self.assertTrue(item["notification_text"].startswith("【客户已转人工】"))
self.assertFalse(self.assistant.has_pending(CUSTOMER))
def test_already_sent_review_reminder_is_not_resent(self):
review_id = self.assistant.ensure_review(state(), context("这个药怎么吃"))
with self.assistant._connect() as conn:
item = self.assistant._read_episode(conn, {"assistant_review_id": review_id}, CUSTOMER)
item.update(notification="sent", attempts=1)
self.assistant._write(conn, item)
before = self.episode(review_id)[1]["notification_text"]
self.assertEqual(self.assistant.notify_handoff(state(assistant_review_id=review_id)), review_id)
status, item = self.episode(review_id)
self.assertEqual((status, item["notification"]), ("handoff", "sent"))
self.assertEqual(item["notification_text"], before, "发过的提醒不换文案、不重发")
def test_worker_guard_accepts_handoff_reminders(self):
episode_id = self.assistant.notify_handoff(state(), context("这个药怎么吃"))
item = self.episode(episode_id)[1]
self.assertTrue(self.assistant._notification_guard(item))
source = (ROOT / "review_assistant.py").read_text(encoding="utf-8")
self.assertRegex(source, r"status IN \('pending','handoff'", "发送线程要把转人工提醒一起发出去")
def test_later_cancel_or_reconcile_does_not_touch_a_handoff_reminder(self):
episode_id = self.assistant.notify_handoff(state(), context("这个药怎么吃"))
self.assertTrue(self.assistant.cancel_review(state(assistant_review_id=episode_id)))
self.assertEqual(self.episode(episode_id)[0], "handoff")
def test_disabled_assistant_returns_empty(self):
self.config = settings(enabled=False)
self.assertEqual(self.assistant.notify_handoff(state(), context("这个药怎么吃")), "")
def test_recipient_conversation_is_never_notified_about_itself(self):
self.assertEqual(self.assistant.notify_handoff(state(conv_id=RECIPIENT), context("x")), "")
def test_without_database_the_task_text_is_used(self):
episode_id = self.assistant.notify_handoff(state())
self.assertTrue(episode_id)
item = self.episode(episode_id)[1]
self.assertIn("客户:这个药怎么吃", item["context"])
self.assertEqual(self.assistant.notify_handoff(state(staged_user_text="", conv_id="S:1688856770803435_7881300000000009")), "")
def test_summary_mentions_the_handoff(self):
self.assistant.notify_handoff(state(), context("这个药怎么吃"))
summary = ra.notification_summary(self.root, ACCOUNT)
self.assertEqual(summary["status"], "handoff_pending")
self.assertIn("已转人工", summary["message"])
class HandoffCallersTest(unittest.TestCase):
"""三条转人工路径都先登记提醒,没登记上才按原方式取消。"""
def test_protocol_notifies_before_flushing_cancellations(self):
tree = ast.parse((ROOT / "protocol_engine.py").read_text(encoding="utf-8-sig"))
bot = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "ProtocolBot")
method = next(n for n in bot.body if isinstance(n, ast.FunctionDef) and n.name == "handoff_pending_replies")
source = ast.get_source_segment((ROOT / "protocol_engine.py").read_text(encoding="utf-8-sig"), method)
self.assertIn("notify_handoff", source)
self.assertLess(source.index("notify_handoff"), source.index("_flush_assistant_cancellations"))
def test_visual_and_file_paths_use_the_handoff_helper(self):
bot = (ROOT / "wechat_bot.py").read_text(encoding="utf-8-sig")
start = bot.index("def handoff_pending_replies(")
self.assertIn("handoff_assistant_review_for_state", bot[start:bot.index("def cancel_pending_replies(", start)])
runtime = (ROOT / "gui_runtime.py").read_text(encoding="utf-8-sig")
self.assertIn("handoff_assistant_review_for_state(state, directory)", runtime)
def test_file_path_helper_registers_or_falls_back(self):
import gui_runtime
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
(root / "app_settings.json").write_text(json.dumps(settings()), encoding="utf-8")
self.assertTrue(gui_runtime.handoff_assistant_review_for_state(state(), root))
with closing(sqlite3.connect(root / "review_assistant.sqlite3")) as conn:
self.assertEqual(conn.execute("SELECT status FROM episodes").fetchall(), [("handoff",)])
(root / "app_settings.json").write_text(json.dumps(settings(enabled=False)), encoding="utf-8")
self.assertFalse(gui_runtime.handoff_assistant_review_for_state(state(conv_id=RECIPIENT[:-1] + "3"), root))
if __name__ == "__main__":
unittest.main()