296 lines
15 KiB
Python
296 lines
15 KiB
Python
"""Search latency, cancellation and binding checks with synthetic contacts only."""
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
from PySide6.QtCore import QCoreApplication
|
|
import proactive_contact_ui as ui
|
|
from proactive_contact_service import PatientGateway, ContactService
|
|
from test_proactive_contact import FakeGateway, FakeTransport
|
|
|
|
|
|
def context(conversation):
|
|
return dict(available=True, permissions={'can_search': True},
|
|
conversation={'external_id': conversation, 'source_account': '1'},
|
|
people=[dict(id='person', identities=[{'external_id': conversation[2:]}],
|
|
patient_bindings=[dict(id='binding', patient_id=123, patient_name='测试患者',
|
|
status='active', updated_at='v1')])])
|
|
|
|
|
|
class ReadonlySearchValidationTest(unittest.TestCase):
|
|
def test_nested_search_scopes_reuse_hash_but_file_or_process_changes_invalidate(self):
|
|
import wecom_native_sender as native
|
|
cache = {}
|
|
with patch.object(native, '_path_file_identity', return_value=('file', 1)) as identity, \
|
|
patch.object(native, '_process_creation_id', return_value=10) as created, \
|
|
patch.object(native, '_hash_client_file', return_value=('digest', ('file', 1))) as digest:
|
|
# The real function accesses verified[2] for size metrics.
|
|
identity.return_value = ('file', 1, 123)
|
|
digest.return_value = ('digest', identity.return_value)
|
|
for _ in range(2):
|
|
with native.readonly_build_validation_scope(cache):
|
|
with native.readonly_build_validation_scope():
|
|
native._client_file_digest('fake.exe', 1, None, readonly=True)
|
|
self.assertEqual(digest.call_count, 1)
|
|
with native.readonly_build_validation_scope(cache):
|
|
native._client_file_digest('fake.exe', 1, None, readonly=False)
|
|
self.assertEqual(digest.call_count, 2) # sending never uses display cache
|
|
created.return_value = 11
|
|
with native.readonly_build_validation_scope(cache):
|
|
native._client_file_digest('fake.exe', 1, None, readonly=True)
|
|
self.assertEqual(digest.call_count, 3)
|
|
identity.return_value = ('changed', 2, 456)
|
|
digest.return_value = ('new-digest', identity.return_value)
|
|
with native.readonly_build_validation_scope(cache):
|
|
native._client_file_digest('fake.exe', 1, None, readonly=True)
|
|
self.assertEqual(digest.call_count, 4)
|
|
|
|
def test_cached_file_validation_does_not_cache_current_account(self):
|
|
from review_assistant_contacts import active_context
|
|
from wecom_native_sender import readonly_build_validation_scope
|
|
with patch('wecom_native_sender.discover', side_effect=[{'accountId': '1'}, {'accountId': '2'}]) as discover:
|
|
with readonly_build_validation_scope({}):
|
|
self.assertEqual(active_context()['account_id'], '1')
|
|
self.assertEqual(active_context()['account_id'], '2')
|
|
self.assertEqual(discover.call_count, 2)
|
|
|
|
|
|
class CandidateGatewayTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.gateway = PatientGateway()
|
|
self.addCleanup(lambda: self.gateway._candidate_pool.shutdown(wait=True, cancel_futures=True))
|
|
self.owner = self.enterContext(patch.object(self.gateway, 'owner', return_value='owner'))
|
|
self.enterContext(patch('backend_client.load_settings', return_value={'desktop_token_protected': 'session'}))
|
|
self.enterContext(patch('review_assistant_contacts.active_context', return_value={'ready': True, 'account_id': '1'}))
|
|
self.directory = self.enterContext(patch('review_assistant_contacts.list_recipients', return_value={
|
|
'ready': True, 'items': [dict(id=f'M:{n}', name=f'客户{n}') for n in range(2, 10)],
|
|
'has_more': False, 'total': 8}))
|
|
self.request = self.enterContext(patch('backend_client.desktop_patient_context',
|
|
side_effect=lambda account, conversation, **kw: context(conversation)))
|
|
|
|
def test_local_rows_publish_before_binding_requests_finish_and_parallelism_is_bounded(self):
|
|
release, first, four = threading.Event(), threading.Event(), threading.Event()
|
|
self.addCleanup(release.set)
|
|
lock = threading.Lock()
|
|
active, peak = [0], [0]
|
|
def lookup(account, conversation, **kw):
|
|
self.assertEqual(kw['timeout'], 4.0)
|
|
with lock:
|
|
active[0] += 1; peak[0] = max(peak[0], active[0])
|
|
if active[0] == 4: four.set()
|
|
release.wait(3)
|
|
with lock: active[0] -= 1
|
|
return context(conversation)
|
|
self.request.side_effect = lookup
|
|
updates = []
|
|
def progress(page):
|
|
updates.append(page)
|
|
first.set()
|
|
worker = threading.Thread(target=lambda: self.gateway.candidates(progress=progress))
|
|
worker.start()
|
|
try:
|
|
self.assertTrue(first.wait(1))
|
|
self.assertEqual(len(updates[0]['items']), 8)
|
|
self.assertTrue(all(r['binding_loading'] for r in updates[0]['items']))
|
|
self.assertTrue(four.wait(1))
|
|
self.assertTrue(worker.is_alive())
|
|
finally:
|
|
release.set(); worker.join(4)
|
|
self.assertFalse(worker.is_alive())
|
|
self.assertEqual(peak[0], 4)
|
|
self.assertTrue(all(r['bindings'] and not r['binding_loading'] for r in updates[-1]['items']))
|
|
|
|
def test_repeated_search_uses_scoped_cache_and_binding_edit_invalidates_it(self):
|
|
self.gateway.candidates('客户')
|
|
self.gateway.candidates('客')
|
|
self.assertEqual(self.request.call_count, 8)
|
|
self.gateway.invalidate_candidates()
|
|
self.gateway.candidates('客户')
|
|
self.assertEqual(self.request.call_count, 16)
|
|
self.owner.return_value = 'different-owner'
|
|
self.gateway.candidates('客户')
|
|
self.assertEqual(self.request.call_count, 24)
|
|
with patch('backend_client.load_settings', return_value={'desktop_token_protected': 'new-session'}):
|
|
self.gateway.candidates('客户')
|
|
self.assertEqual(self.request.call_count, 32)
|
|
|
|
def test_timeout_and_wrong_conversation_never_enable_a_candidate(self):
|
|
self.request.side_effect = TimeoutError('slow')
|
|
page = self.gateway.candidates()
|
|
self.assertTrue(all(r['binding_error'] and not r['bindings'] for r in page['items']))
|
|
|
|
self.request.side_effect = lambda *args, **kw: context('M:other')
|
|
page = self.gateway.candidates()
|
|
self.assertEqual(self.request.call_count, 16) # errors are retryable
|
|
self.assertTrue(all(r['binding_error'] and not r['bindings'] for r in page['items']))
|
|
|
|
def test_explicit_search_rechecks_revoked_binding_without_waiting_for_cache_expiry(self):
|
|
self.assertTrue(all(r['bindings'] for r in self.gateway.candidates()['items']))
|
|
def unbound(account, conversation, **kwargs):
|
|
value = context(conversation)
|
|
value['people'][0]['patient_bindings'] = []
|
|
return value
|
|
self.request.side_effect = unbound
|
|
page = self.gateway.candidates(refresh_bindings=True)
|
|
self.assertTrue(all(not r['bindings'] and not r['binding_loading'] for r in page['items']))
|
|
self.assertEqual(self.request.call_count, 16)
|
|
self.assertTrue(all(not r['bindings'] for r in self.gateway.candidates()['items']))
|
|
self.assertEqual(self.request.call_count, 16)
|
|
|
|
def test_failed_explicit_refresh_never_resurrects_cached_binding(self):
|
|
self.gateway.candidates()
|
|
self.request.side_effect = TimeoutError('offline')
|
|
for force in (True, False):
|
|
page = self.gateway.candidates(refresh_bindings=force)
|
|
self.assertTrue(all(not r['bindings'] and r['binding_error'] for r in page['items']))
|
|
|
|
def test_trimmed_query_and_only_complete_active_bindings_are_exposed(self):
|
|
def lookup(account, conversation, **kwargs):
|
|
value = context(conversation)
|
|
binding = value['people'][0]['patient_bindings'][0]
|
|
value['people'][0]['patient_bindings'] = [binding, binding,
|
|
{**binding, 'id': 'empty', 'patient_name': ''},
|
|
{**binding, 'id': 'deleted', 'status': 'inactive'},
|
|
{**binding, 'id': 'invalid', 'patient_id': 'bad'},
|
|
{**binding, 'id': 'zero', 'patient_id': 0}]
|
|
return value
|
|
self.request.side_effect = lookup
|
|
page = self.gateway.candidates(' 客户 ')
|
|
self.assertEqual(page['query'], '客户')
|
|
self.assertEqual(self.directory.call_args.args[1], '客户')
|
|
self.assertTrue(all(len(r['bindings']) == 1 for r in page['items']))
|
|
|
|
def test_cancel_does_not_wait_for_slow_network_or_fill_cache(self):
|
|
release, started, cancel = threading.Event(), threading.Event(), threading.Event()
|
|
self.addCleanup(release.set)
|
|
def lookup(account, conversation, **kw):
|
|
started.set(); release.wait(3)
|
|
return context(conversation)
|
|
self.request.side_effect = lookup
|
|
worker = threading.Thread(target=lambda: self.gateway.candidates(cancelled=cancel.is_set))
|
|
worker.start()
|
|
try:
|
|
self.assertTrue(started.wait(1))
|
|
cancel.set(); worker.join(.5)
|
|
self.assertFalse(worker.is_alive())
|
|
finally:
|
|
release.set(); worker.join(3)
|
|
self.gateway._candidate_pool.shutdown(wait=True)
|
|
self.assertEqual(len(self.gateway._candidate_cache), 0)
|
|
|
|
def test_cached_bound_row_is_not_proof_for_add(self):
|
|
page = self.gateway.candidates()
|
|
row = page['items'][0]
|
|
self.assertTrue(row['bindings'])
|
|
revoked = context(row['conversation'])
|
|
revoked['people'][0]['patient_bindings'] = []
|
|
self.request.side_effect = None; self.request.return_value = revoked
|
|
with tempfile.TemporaryDirectory() as root, \
|
|
patch('review_assistant_contacts.validate_recipient', return_value={'ok': True, 'recipient': {'name': '客户'}}), \
|
|
patch('conversation_blacklist.blocked_reason', return_value=''):
|
|
service = ContactService(root, self.gateway, FakeTransport())
|
|
result = service.add('owner', [{**row, 'binding_id': 'binding'}])
|
|
self.assertEqual(result['added'], [])
|
|
self.assertTrue(result['rejected'])
|
|
self.assertEqual(service.store.customers('owner'), [])
|
|
|
|
|
|
class CandidateControllerTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.app = QCoreApplication.instance() or QCoreApplication([])
|
|
|
|
def setUp(self):
|
|
self.temp = tempfile.TemporaryDirectory()
|
|
self.gateway = FakeGateway()
|
|
self.gateway.candidates = lambda query, offset, **kw: dict(query=query, items=[], total=0)
|
|
self.enterContext(patch.object(ui, 'PatientGateway', return_value=self.gateway))
|
|
self.enterContext(patch.object(ui, 'NativeContactTransport', return_value=FakeTransport()))
|
|
self.controller = ui.ProactiveController(self.temp.name)
|
|
self.addCleanup(self.cleanup)
|
|
|
|
def cleanup(self):
|
|
self.controller.close()
|
|
for thread in (self.controller._thread, self.controller._candidate_thread):
|
|
if thread: thread.join(4)
|
|
self.app.processEvents()
|
|
self.temp.cleanup()
|
|
|
|
def wait_for(self, predicate):
|
|
end = time.monotonic()+3
|
|
while time.monotonic() < end:
|
|
self.app.processEvents()
|
|
if predicate(): return
|
|
time.sleep(.01)
|
|
self.fail('search response timed out')
|
|
|
|
def search(self, query):
|
|
self.controller.submit(dict(action='candidates', query=query, request_id=query))
|
|
|
|
def test_search_finishes_while_scheduler_is_blocked(self):
|
|
started, release = threading.Event(), threading.Event()
|
|
def tick(*args):
|
|
started.set(); release.wait(3); return False
|
|
with patch.object(ui.ContactScheduler, 'tick', side_effect=tick):
|
|
self.controller.start()
|
|
self.assertTrue(started.wait(1))
|
|
try:
|
|
self.search('quick')
|
|
self.wait_for(lambda: self.controller.state.get('candidateSearch', {}).get('status') == 'success')
|
|
self.assertFalse(self.controller.state.get('busy'))
|
|
finally: release.set()
|
|
|
|
def test_newest_query_wins_and_old_callbacks_are_ignored(self):
|
|
started, release = threading.Event(), threading.Event()
|
|
seen = []
|
|
def candidates(query, offset, **kw):
|
|
seen.append(query)
|
|
if query == 'old': started.set(); release.wait(3)
|
|
page = dict(query=query, items=[dict(name=query, bindings=[], binding_loading=False)])
|
|
kw['progress'](page) # deliberately ignore cancelled in this fake
|
|
return page
|
|
self.gateway.candidates = candidates
|
|
self.search('old'); self.assertTrue(started.wait(1))
|
|
try:
|
|
self.search('middle'); self.search('latest')
|
|
finally: release.set()
|
|
self.wait_for(lambda: self.controller.state.get('candidateSearch', {}).get('status') == 'success')
|
|
self.assertEqual(seen, ['old', 'latest'])
|
|
self.assertEqual(self.controller.state['candidates']['query'], 'latest')
|
|
self.controller.submit({'action': 'snapshot'})
|
|
self.wait_for(lambda: bool(self.controller.state.get('enabled')))
|
|
self.assertEqual(self.controller.state['candidates']['query'], 'latest')
|
|
|
|
def test_owner_change_discards_inflight_candidate_data(self):
|
|
def candidates(query, offset, **kw):
|
|
self.gateway.identity = 'other'
|
|
return dict(query=query, items=[dict(name='must not display')])
|
|
self.gateway.candidates = candidates
|
|
self.search('test')
|
|
self.wait_for(lambda: self.controller.state.get('candidateSearch', {}).get('status') == 'error')
|
|
self.assertEqual(self.controller.state['candidates'], {})
|
|
|
|
def test_binding_refresh_preserves_the_current_search(self):
|
|
self.search('selected customer')
|
|
self.wait_for(lambda: self.controller.state.get('candidateSearch', {}).get('status') == 'success')
|
|
self.controller.submit({'action': 'candidates'})
|
|
self.wait_for(lambda: self.controller.state.get('candidateSearch', {}).get('serverInitiated')
|
|
and self.controller.state['candidateSearch']['status'] == 'success')
|
|
self.assertEqual(self.controller.state['candidates']['query'], 'selected customer')
|
|
|
|
def test_explicit_refresh_is_forwarded_to_candidate_gateway(self):
|
|
requests = []
|
|
def candidates(query, offset, **kwargs):
|
|
requests.append(kwargs)
|
|
return dict(query=query, items=[], total=0)
|
|
self.gateway.candidates = candidates
|
|
self.controller.submit(dict(action='candidates', query='客户', request_id='fresh', refresh_bindings=True))
|
|
self.wait_for(lambda: self.controller.state.get('candidateSearch', {}).get('status') == 'success')
|
|
self.assertIs(requests[0]['refresh_bindings'], True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|