157 lines
6.4 KiB
Python
157 lines
6.4 KiB
Python
"""Real pipe regressions with a dummy worker; never connects to a game service."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
|
from mcp_session import Session, SessionCancelled, SessionTimeout
|
|
|
|
WORKER = '''import json,os,sys,time
|
|
mode=os.environ['WORKER_MODE']
|
|
for line in sys.stdin:
|
|
message=json.loads(line)
|
|
with open(os.environ['WORKER_LOG'],'a',encoding='utf-8') as log:
|
|
log.write(json.dumps(message)+'\\n')
|
|
mid=message.get('id')
|
|
if mode=='initialize-failure':
|
|
sys.exit(1)
|
|
if mid is None:
|
|
continue
|
|
if message['method']=='initialize':
|
|
if mode=='stderr-burst':
|
|
sys.stderr.write('diagnostic\\n'*50000)
|
|
sys.stderr.flush()
|
|
result={}
|
|
elif mode=='silent':
|
|
continue
|
|
elif mode=='malformed':
|
|
print('invalid json',flush=True)
|
|
continue
|
|
else:
|
|
result={'content':[{'type':'text','text':json.dumps({'ok':True,'text':'中文'})}]}
|
|
print(json.dumps({'jsonrpc':'2.0','id':mid,'result':result}),flush=True)
|
|
if mode=='no-read':
|
|
time.sleep(60)
|
|
'''
|
|
|
|
|
|
class SessionTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.folder = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.folder.cleanup)
|
|
self.log = Path(self.folder.name) / 'requests.jsonl'
|
|
self.children = []
|
|
|
|
def worker(self, mode, **options):
|
|
real_popen = subprocess.Popen
|
|
def launch(*args, **kwargs):
|
|
kwargs['env'] = dict(kwargs['env'], WORKER_MODE=mode, WORKER_LOG=str(self.log))
|
|
child = real_popen([sys.executable, '-u', '-c', WORKER], **kwargs)
|
|
self.children.append(child)
|
|
return child
|
|
with mock.patch('mcp_session.subprocess.Popen', side_effect=launch):
|
|
return Session(**options)
|
|
|
|
def test_silent_response_times_out_without_retry_and_closes_child(self):
|
|
client = self.worker('silent', timeout=.5)
|
|
self.addCleanup(client.close)
|
|
started = time.monotonic()
|
|
with self.assertRaises(SessionTimeout) as caught:
|
|
client.call('click', {'x': 1, 'y': 2})
|
|
self.assertTrue(caught.exception.outcome_unknown)
|
|
self.assertEqual(caught.exception.tool, 'click')
|
|
self.assertLess(time.monotonic() - started, 3)
|
|
self.assertIsNotNone(client.process.poll())
|
|
rows = [json.loads(line) for line in self.log.read_text().splitlines()]
|
|
self.assertEqual(sum(row['method'] == 'tools/call' for row in rows), 1)
|
|
with self.assertRaises(ConnectionError):
|
|
client.call('get_state')
|
|
|
|
def test_stop_interrupts_pending_response(self):
|
|
cancelled = threading.Event()
|
|
client = self.worker('silent', timeout=5, cancelled=cancelled.is_set)
|
|
self.addCleanup(client.close)
|
|
timer = threading.Timer(.2, cancelled.set)
|
|
timer.start()
|
|
self.addCleanup(timer.cancel)
|
|
started = time.monotonic()
|
|
with self.assertRaises(SessionCancelled) as caught:
|
|
client.call('keypress', {'key': 'enter'})
|
|
self.assertTrue(caught.exception.outcome_unknown)
|
|
self.assertLess(time.monotonic() - started, 3)
|
|
self.assertIsNotNone(client.process.poll())
|
|
|
|
def test_stderr_burst_does_not_block_handshake_and_chinese_response(self):
|
|
with self.worker('stderr-burst', timeout=5) as client:
|
|
self.assertEqual(client.call('get_state')['text'], '中文')
|
|
self.assertLessEqual(len(client.stderr_tail), 20)
|
|
|
|
def test_initialization_failure_closes_every_pipe(self):
|
|
with self.assertRaises(ConnectionError):
|
|
self.worker('initialize-failure', timeout=2)
|
|
child = self.children[0]
|
|
self.assertIsNotNone(child.poll())
|
|
self.assertTrue(all(stream.closed for stream in (child.stdin, child.stdout, child.stderr)))
|
|
|
|
def test_invalid_response_closes_session(self):
|
|
client = self.worker('malformed', timeout=2)
|
|
self.addCleanup(client.close)
|
|
with self.assertRaises(ConnectionError):
|
|
client.call('get_state')
|
|
self.assertIsNotNone(client.process.poll())
|
|
|
|
def test_blocked_stdin_write_is_also_bounded(self):
|
|
client = self.worker('no-read', timeout=.5)
|
|
self.addCleanup(client.close)
|
|
started = time.monotonic()
|
|
with self.assertRaises(SessionTimeout):
|
|
client.call('type_text', {'text': 'x' * 500000})
|
|
self.assertLess(time.monotonic() - started, 3)
|
|
self.assertIsNotNone(client.process.poll())
|
|
self.assertFalse(any(thread.is_alive() for thread in client._threads))
|
|
|
|
def test_long_wait_tool_has_a_response_budget_beyond_its_polling_timeout(self):
|
|
client = Session.__new__(Session)
|
|
client.timeout = 30
|
|
client.request = mock.Mock(return_value={'content': [{'text': '{"ok":true}'}]})
|
|
client.call('wait_for_text', {'text': '开始', 'timeout': 300})
|
|
self.assertEqual(client.request.call_args.args[2], 305)
|
|
|
|
def test_session_uses_real_bridge_against_isolated_fake_server(self):
|
|
from lc_mcp.fake_engine import FakeEngine
|
|
from lc_mcp.protocol import Server
|
|
from lc_mcp.server import make_tcp
|
|
from lc_mcp.tasks import TaskRunner
|
|
home = Path(self.folder.name)
|
|
runtime = home / 'lc_mcp'
|
|
runtime.mkdir()
|
|
(runtime / 'token').write_text('test-only-token')
|
|
engine = FakeEngine()
|
|
tcp = make_tcp(Server(engine, TaskRunner(str(home / 'runs'))), '127.0.0.1', 0, 'test-only-token')
|
|
serving = threading.Thread(target=tcp.serve_forever, daemon=True)
|
|
serving.start()
|
|
try:
|
|
with mock.patch.dict(os.environ, {'LCP_PORT': str(tcp.server_address[1]),
|
|
'HOME': str(home), 'USERPROFILE': str(home)}):
|
|
with Session(timeout=5) as client:
|
|
self.assertTrue(client.call('get_state')['ok'])
|
|
self.assertTrue(client.call('drag', {'from_x': 1, 'from_y': 2,
|
|
'to_x': 3, 'to_y': 4})['ok'])
|
|
self.assertTrue(client.call('type_text', {'text': '中文'})['ok'])
|
|
self.assertEqual(engine.actions[-1], ('type', '中文'))
|
|
finally:
|
|
tcp.shutdown()
|
|
tcp.server_close()
|
|
serving.join(2)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|