Files
xieyi-weixin-/test_contact_reply_guard.py
T
2026-09-21 10:56:48 +08:00

134 lines
8.3 KiB
Python

import tempfile
import unittest
from pathlib import Path
from unittest import mock
import numpy as np
from contact_reply_guard import *
from wechat_bot import WeChatBot
import test_native_protocol_pipeline as pipeline
from test_native_protocol_pipeline import message, ACCOUNT, CONV, session_key, DeliveryFailed
NOTICE='一个小迷糊开启了联系人验证,你还不是他(她)的联系人。请先发送联系人验证请求,对方验证通过后,才能聊天。'
class NoticeTests(unittest.TestCase):
def test_complete_notice_and_wrapped_ocr(self):
self.assertEqual(contact_verification_reason(NOTICE),CONTACT_REASON)
self.assertEqual(contact_verification_reason(NOTICE.replace('联系人','联 系\n人')),CONTACT_REASON)
def test_discussing_verification_or_single_failure_icon_is_not_evidence(self):
for text in ('联系人验证怎么开', '请加我为联系人', '消息发送失败', '网络不可用', '我已经通过联系人验证了'):
self.assertEqual(contact_verification_reason(text),'')
def scene(self,shade=160):
image=np.full((100,800,3),245,dtype=np.uint8)
image[20:36:2,85:715:3]=shade
return image,[{'x1':80,'y1':18,'x2':720,'y2':40,'text':NOTICE,'score':.99}]
def test_grey_centered_system_notice(self):
self.assertEqual(visual_contact_reason(*self.scene()),CONTACT_REASON)
def test_black_chat_quote_is_not_a_system_banner(self):
self.assertEqual(visual_contact_reason(*self.scene(25)),'')
def test_low_confidence_does_not_blacklist(self):
scene,items=self.scene();items[0]['score']=.55
self.assertEqual(visual_contact_reason(scene,items),'')
def test_customer_quote_is_not_a_protocol_system_notice(self):
self.assertEqual(system_contact_status(message(text=NOTICE)),'')
def test_system_restoration_supersedes_old_restriction(self):
blocked={**message(text=NOTICE),'content_type':11}
restored={**message(2,text='你已添加了客户,现在可以开始聊天了'),'content_type':11}
self.assertEqual(conversation_contact_reason({'messages':[blocked,message(2)]}),CONTACT_REASON)
self.assertEqual(conversation_contact_reason({'messages':[blocked,restored,message(3)]}),'')
class VisualSkipTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.bot=WeChatBot.__new__(WeChatBot);self.fp=b'\xab'*40
b=self.bot
b._unrepliable_path=str(Path(self.tmp.name)/'skip.json');b._unrepliable_sessions={}
b._pending_reply_path='';b._pending_reply_sessions={self.fp.hex():{'staged_reply_text':'不得发送'}}
b._pending_exchanges={self.fp.hex():('客户','回复')};b._pending_scan_progress={}
b._log_queue_event=mock.Mock();b._composer_geometry_valid=True
scene,items=NoticeTests().scene()
b._chat_rel_x=0;b._chat_rel_y=0;b._chat_rel_w=800;b._chat_rel_h=100
b._capture_full_window=mock.Mock(return_value=scene)
b._name_reader_instance=mock.Mock();b._name_reader_instance.read_layout.return_value=items
def test_skip_clears_pending_and_uncommitted_exchange_then_persists(self):
self.assertFalse(self.bot._session_accepts_replies(self.fp))
self.assertFalse(self.bot._pending_reply_sessions);self.assertFalse(self.bot._pending_exchanges)
self.assertTrue(self.bot._session_is_unrepliable(self.fp))
self.assertIn(self.fp.hex(),self.bot._load_unrepliable_sessions())
self.bot._log_queue_event.assert_called_once_with(self.fp,'跳过',CONTACT_REASON)
# Even if the unread scan recreated a task, a known blocked chat immediately loses it.
self.bot._pending_reply_sessions[self.fp.hex()]={}
self.assertFalse(self.bot._session_accepts_replies(self.fp))
self.assertFalse(self.bot._pending_reply_sessions)
self.bot._name_reader_instance.read_layout.assert_called_once()
def test_uncertain_send_with_rejection_skips_without_receipt_or_retry(self):
self.bot._send_receipt_matches=mock.Mock()
self.assertEqual(self.bot._reconcile_uncertain_send(self.fp,{'send_state':'uncertain'}),'skipped')
self.bot._send_receipt_matches.assert_not_called()
self.assertFalse(self.bot._pending_reply_sessions)
def test_failed_outgoing_bubble_is_never_archived_as_success(self):
self.bot._commit_staged_exchange=mock.Mock()
self.bot._database_chat_text=mock.Mock(return_value='我:不得发送')
self.assertTrue(self.bot._nothing_left_to_answer(self.fp))
self.bot._commit_staged_exchange.assert_not_called()
self.bot._database_chat_text.assert_not_called()
self.assertFalse(self.bot._pending_reply_sessions)
def test_ocr_error_keeps_customer_task(self):
self.bot._name_reader_instance.read_layout.side_effect=RuntimeError('OCR temporarily unavailable')
self.assertTrue(self.bot._session_accepts_replies(self.fp))
self.assertIn(self.fp.hex(),self.bot._pending_reply_sessions)
self.assertFalse(self.bot._unrepliable_sessions)
class ProtocolContactTests(unittest.TestCase):
setUp=pipeline.EngineTests.setUp
make_bot=pipeline.EngineTests.make_bot
enqueue=pipeline.EngineTests.enqueue
def test_notice_blocks_one_chat_and_another_chat_still_sends(self):
self.db.add({**message(2,text=NOTICE),'content_type':11})
self.db.add(message(3,text='吃饭了吗'))
self.db.add(message(4,conv='S:100_201'))
self.bot.poll_once()
self.assertEqual([call[2] for call in self.sender.calls],['S:100_201'])
self.assertFalse(self.bot._pending);self.assertFalse(self.bot.needs_attention)
def test_existing_system_notice_is_checked_before_generation(self):
self.db.messages.append({**message(2,text=NOTICE),'content_type':11})
self.enqueue(message(3))
self.gen.assert_not_called();self.assertFalse(self.sender.calls)
def test_rejection_during_send_is_not_retried_after_restart(self):
self.sender.error=DeliveryFailed('该用户不是你的联系人')
self.enqueue()
self.assertFalse(self.bot._pending);self.assertFalse(self.bot.needs_attention)
restored=self.make_bot();self.db.add(message(3));restored.poll_once()
self.assertEqual(len(self.sender.calls),1)
def test_other_send_failure_remains_protected(self):
self.sender.error=DeliveryFailed('network unavailable');self.enqueue()
self.assertEqual(self.bot._pending[session_key(ACCOUNT,CONV)]['send_state'],'failed')
self.assertFalse(self.bot._contact_blocked)
def test_restore_notice_allows_later_message(self):
self.db.add({**message(2,text=NOTICE),'content_type':11});self.bot.poll_once()
self.db.add({**message(3,text='我通过了你的联系人验证,现在可以开始聊天了'),'content_type':11})
self.db.add(message(4));self.bot.poll_once()
self.assertEqual(len(self.sender.calls),1);self.assertFalse(self.bot._contact_blocked)
def test_unknown_receipt_with_contact_notice_isolated_without_resending(self):
def rejected(*args,**kwargs):
self.db.add({**message(2,text=NOTICE),'content_type':11})
raise pipeline.DeliveryUnknown('callback timeout')
self.sender.send=rejected;self.enqueue()
self.assertFalse(self.bot._pending);self.assertFalse(self.bot.needs_attention)
self.assertIn(session_key(ACCOUNT,CONV),self.bot._contact_blocked)
def test_failed_notice_lookup_keeps_unknown_send_protected(self):
def rejected(*args,**kwargs):
self.db.get_conversation_context_by_id=mock.Mock(side_effect=RuntimeError('db unavailable'))
raise pipeline.DeliveryUnknown('callback timeout')
self.sender.send=rejected;self.enqueue()
self.assertTrue(self.bot.needs_attention)
self.assertEqual(self.bot._pending[session_key(ACCOUNT,CONV)]['send_state'],'uncertain')
def test_user_quoting_notice_does_not_disable_chat(self):
self.enqueue(message(text=NOTICE));self.assertEqual(len(self.sender.calls),1)
def test_notice_arriving_during_generation_cancels_draft(self):
def generate(context):
self.db.add({**message(2,text=NOTICE),'content_type':11});return '不应发送'
self.bot.generate=generate;self.enqueue();self.assertFalse(self.sender.calls)
self.assertFalse(self.bot._pending)
if __name__=='__main__':unittest.main()