Files
lc-mcp/tests/test_lc_mcp.py
T

336 lines
16 KiB
Python

# -*- coding: utf-8 -*-
"""不需要 Windows/AALC 的测试: python -m unittest discover -s tests"""
import json
import os
import socket
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from unittest import mock
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, REPO)
from lc_mcp import server as srv_mod # noqa: E402
from lc_mcp.engine import find_hits # noqa: E402
from lc_mcp.fake_engine import FakeEngine # noqa: E402
from lc_mcp.protocol import Server, TOOLS # noqa: E402
from lc_mcp.tasks import TaskRunner # noqa: E402
START = {'text': '开始', 'x': 100, 'y': 200, 'w': 40, 'h': 20}
def call(server, tool, **args):
resp = server.handle({'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call',
'params': {'name': tool, 'arguments': args}})
res = resp['result']
data = json.loads(res['content'][0]['text'])
assert res['isError'] == (not data.get('ok', False)), res
return data
def sleeper_argv(seconds):
code = 'import sys,time; print("child", sys.argv[1:], flush=True); time.sleep(%s)' % seconds
return lambda task, params: [sys.executable, '-c', code, task, json.dumps(params)]
class MatchTest(unittest.TestCase):
def test_ignores_spaces_and_case(self):
items = [{'text': 'Hong Lu', 'x': 0, 'y': 0, 'w': 10, 'h': 10}]
self.assertEqual(find_hits('honglu', items)[0]['x'], 5)
def test_exact_first(self):
items = [{'text': '开始战斗', 'x': 0, 'y': 0, 'w': 10, 'h': 10}, START]
self.assertEqual(find_hits('开始', items)[0]['text'], '开始')
def test_empty_matches_nothing(self):
self.assertEqual(find_hits(' ', [START]), [])
class ProtocolTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.tasks = TaskRunner(self.tmp.name, argv_factory=sleeper_argv(5))
self.engine = FakeEngine(frames=[[START]], images={'battle/turn_assets.png': (50, 60)})
self.s = Server(self.engine, self.tasks)
def tearDown(self):
self.tasks.stop()
self.tmp.cleanup()
def test_initialize_and_list(self):
r = self.s.handle({'jsonrpc': '2.0', 'id': 7, 'method': 'initialize', 'params': {}})
self.assertEqual(r['id'], 7)
names = [t['name'] for t in self.s.handle({'jsonrpc': '2.0', 'id': 8, 'method': 'tools/list'})['result']['tools']]
self.assertEqual(names, [t['name'] for t in TOOLS])
self.assertIsNone(self.s.handle({'jsonrpc': '2.0', 'method': 'notifications/initialized'}))
self.assertEqual(self.s.handle({'jsonrpc': '2.0', 'id': 9, 'method': 'nope'})['error']['code'], -32601)
def test_click_text(self):
r = call(self.s, 'click_text', text='开 始')
self.assertTrue(r['ok'])
self.assertEqual(self.engine.actions, [('click', 120, 210, 1)])
self.assertFalse(call(self.s, 'click_text', text='不存在')['ok'])
self.assertFalse(call(self.s, 'click_text', text='开始', index=3)['ok'])
self.assertFalse(call(self.s, 'click_text', text='')['ok'])
def test_bad_arguments_are_tool_errors(self):
r = call(self.s, 'click', x='abc', y=1)
self.assertIn('bad arguments', r['error'])
self.assertFalse(call(self.s, 'click')['ok'])
def test_drag_duration_and_rejected_arguments(self):
r = call(self.s, 'drag', from_x=200, from_y=300, to_x=200, to_y=600, duration=1.5)
self.assertTrue(r['ok'])
self.assertEqual(self.engine.actions[-1], ('drag', 200, 300, 200, 600, 1.5))
action_count = len(self.engine.actions)
for duration in (-1, 0, 11, float('nan'), float('inf')):
self.assertFalse(call(self.s, 'drag', from_x=1, from_y=2,
to_x=3, to_y=4, duration=duration)['ok'])
self.assertEqual(len(self.engine.actions), action_count)
def test_images(self):
self.assertEqual(call(self.s, 'find_image', name='battle/turn_assets.png')['x'], 50)
r = call(self.s, 'find_image', name='home/x.png')
self.assertTrue(r['ok'])
self.assertFalse(r['found'])
self.assertFalse(call(self.s, 'click_image', name='home/x.png')['ok'])
call(self.s, 'click_image', name='battle/turn_assets.png')
self.assertEqual(self.engine.actions[-1], ('click', 50, 60, 1))
self.assertEqual(call(self.s, 'list_images', prefix='battle/')['count'], 1)
def test_wait_for_text(self):
self.engine.frames = [[], [], [START]]
with mock.patch('lc_mcp.protocol.WAIT_INTERVAL', 0.01):
r = call(self.s, 'wait_for_text', text='开始', timeout=2)
self.assertTrue(r['ok'])
self.engine.frames = [[START]]
r = call(self.s, 'wait_for_text_gone', text='开始', timeout=0.05)
self.assertFalse(r['ok'])
self.assertIn('timeout', r['error'])
def test_task_lifecycle_blocks_manual_input(self):
self.assertEqual(call(self.s, 'task_status')['state'], 'idle')
r = call(self.s, 'run_task', task='mirror', count=2, exp=9) # exp 不属于 mirror, 忽略
self.assertTrue(r['ok'], r)
self.assertFalse(call(self.s, 'run_task', task='daily')['ok'])
self.assertIn('stop_task', call(self.s, 'click', x=1, y=1)['error'])
self.assertIn('stop_task', call(self.s, 'drag', from_x=1, from_y=2,
to_x=3, to_y=4)['error'])
self.assertTrue(call(self.s, 'get_state')['ok']) # 只读工具仍可用
time.sleep(0.5)
st = call(self.s, 'task_status')
self.assertEqual(st['state'], 'running')
self.assertEqual(st['params'], {'count': 2})
self.assertIn("child ['mirror', '{\"count\": 2}']", '\n'.join(st['log_tail']))
self.assertEqual(call(self.s, 'stop_task')['state'], 'stopped')
self.assertEqual(call(self.s, 'task_status')['state'], 'stopped')
self.assertTrue(call(self.s, 'click', x=1, y=1)['ok'])
self.assertFalse(call(self.s, 'run_task', task='bogus')['ok'])
def test_task_exit_codes(self):
self.tasks.argv_factory = lambda t, p: [sys.executable, '-c', 'import sys; sys.exit(3)']
call(self.s, 'run_task', task='reward')
self.tasks.proc.wait(5)
st = call(self.s, 'task_status')
self.assertEqual((st['state'], st['exit_code']), ('failed', 3))
def test_engine_unavailable(self):
s = Server(None, self.tasks, engine_error='no windows')
self.assertIn('no windows', call(s, 'get_state')['error'])
self.assertEqual(call(s, 'task_status')['state'], 'idle')
class AalcTaskArgsTest(unittest.TestCase):
def test_rejects_unknown_params(self):
from lc_mcp import aalc_task
self.assertEqual(aalc_task.main(['x', 'mirror', '{"exp": 1}']), 2)
self.assertEqual(aalc_task.main(['x', 'nope']), 2)
class RuntimeTest(unittest.TestCase):
def test_background_keypress_holds_and_releases_on_error(self):
from lc_mcp.aalc_engine import AalcEngine
engine = AalcEngine.__new__(AalcEngine)
engine.key_names = ['enter']
engine.cfg = mock.Mock(simulator=False, win_input_type='background')
engine.auto = mock.Mock()
with mock.patch('lc_mcp.aalc_engine.time.sleep') as sleep:
engine.keypress('enter')
sleep.assert_called_once_with(0.12)
engine.auto.input_handler.key_down.assert_called_once_with('enter')
engine.auto.input_handler.key_up.assert_called_once_with('enter')
engine.auto.key_press.assert_not_called()
with mock.patch('lc_mcp.aalc_engine.time.sleep', side_effect=RuntimeError('interrupted')):
with self.assertRaises(RuntimeError):
engine.keypress('enter')
self.assertEqual(engine.auto.input_handler.key_up.call_count, 2)
def test_pythonw_streams_are_redirected_to_log(self):
with tempfile.TemporaryDirectory() as directory:
with mock.patch.object(srv_mod, 'HOME', directory), \
mock.patch('sys.stdout', None), mock.patch('sys.stderr', None):
stream = srv_mod._configure_streams()
try:
print('启动')
srv_mod.log('ready')
finally:
stream.close()
with open(os.path.join(directory, 'server.log'), encoding='utf-8') as f:
self.assertEqual(f.read(), '启动\n[lc_mcp] ready\n')
def test_stdio_isolates_bootstrap_output_and_uses_utf8(self):
code = '''
from lc_mcp import server
from lc_mcp.protocol import Server
from lc_mcp.fake_engine import FakeEngine
from lc_mcp.tasks import TaskRunner
import tempfile
directory = tempfile.TemporaryDirectory()
def build(fake=False):
print('bootstrap notice')
return Server(FakeEngine(frames=[[{'text':'开始', 'x':1,'y':2,'w':3,'h':4}]]), TaskRunner(directory.name))
server.build_server = build
server.main(['--stdio'])
'''
request = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call',
'params': {'name': 'get_state'}}, ensure_ascii=False) + '\n'
env = dict(os.environ, PYTHONUTF8='0', PYTHONIOENCODING='cp936')
p = subprocess.run([sys.executable, '-c', code], cwd=REPO, input=request.encode('utf-8'),
capture_output=True, env=env, timeout=20)
self.assertEqual(p.returncode, 0, p.stderr.decode('utf-8', 'replace'))
result = json.loads(p.stdout.decode('utf-8'))
data = json.loads(result['result']['content'][0]['text'])
self.assertEqual(data['items'][0]['text'], '开始')
self.assertIn(b'bootstrap notice', p.stderr)
def test_drag_checks_bounds_before_sending_input(self):
from lc_mcp.aalc_engine import AalcEngine
engine = AalcEngine.__new__(AalcEngine)
engine._grab = mock.Mock(return_value=mock.Mock(width=800, height=600))
engine.auto = mock.Mock()
with self.assertRaises(ValueError):
engine.drag(100, 100, 800, 500)
engine.auto.mouse_drag.assert_not_called()
engine.drag(100, 100, 100, 500, 1.5)
engine.auto.mouse_drag.assert_called_once_with(100, 100, drag_time=1.5, dx=0, dy=400)
def test_template_scale_tracks_client_and_restores_config_on_error(self):
from lc_mcp.aalc_engine import AalcEngine
engine = AalcEngine.__new__(AalcEngine)
engine.list_images = mock.Mock(return_value=['battle/setting_assets.png'])
engine._grab = mock.Mock(return_value=mock.Mock(width=1278, height=731))
engine.cfg = mock.Mock(set_win_size=1080)
engine.cfg.unsaved_set_value.side_effect = lambda key, value: setattr(engine.cfg, key, value)
engine.auto = mock.Mock()
def match(*args, **kwargs):
self.assertEqual(engine.cfg.set_win_size, 718.875)
return (1233, 42)
engine.auto.find_image_element.side_effect = match
self.assertEqual(engine.find_image('battle/setting_assets.png'), (1233, 42))
self.assertEqual(engine.cfg.set_win_size, 1080)
self.assertEqual(engine.auto.clear_img_cache.call_count, 2)
engine.auto.find_image_element.side_effect = RuntimeError('match failed')
with self.assertRaises(RuntimeError):
engine.find_image('battle/setting_assets.png')
self.assertEqual(engine.cfg.set_win_size, 1080)
self.assertEqual(engine.auto.clear_img_cache.call_count, 4)
engine.cfg.set_value.assert_not_called()
def free_port():
with socket.socket() as s:
s.bind(('127.0.0.1', 0))
return s.getsockname()[1]
class TransportTest(unittest.TestCase):
def test_client_disconnect_is_not_a_server_error(self):
handler = srv_mod._Handler.__new__(srv_mod._Handler)
for error in (ConnectionResetError, BrokenPipeError):
handler._handle_session = mock.Mock(side_effect=error('client closed'))
handler.handle()
handler._handle_session.assert_called_once_with()
handler._handle_session = mock.Mock(side_effect=ValueError('internal bug'))
with self.assertRaises(ValueError):
handler.handle()
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.token_file = os.path.join(self.tmp.name, 'token')
with open(self.token_file, 'w') as f:
f.write('secret-token')
self.port = free_port()
mcp = Server(FakeEngine(frames=[[START]]), TaskRunner(self.tmp.name))
self.tcp = srv_mod.make_tcp(mcp, '127.0.0.1', self.port, 'secret-token')
threading.Thread(target=self.tcp.serve_forever, daemon=True).start()
def tearDown(self):
self.tcp.shutdown()
self.tcp.server_close()
self.tmp.cleanup()
def test_wrong_token_rejected(self):
with socket.create_connection(('127.0.0.1', self.port)) as s:
s.sendall(b'AUTH wrong\n')
self.assertEqual(s.makefile('rb').readline().strip(), b'DENIED')
def test_bridge_end_to_end(self):
env = dict(os.environ, LCP_PORT=str(self.port), HOME=self.tmp.name, USERPROFILE=self.tmp.name)
os.makedirs(os.path.join(self.tmp.name, 'lc_mcp'))
os.replace(self.token_file, os.path.join(self.tmp.name, 'lc_mcp', 'token'))
lines = [
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}',
'',
'not json',
'{"jsonrpc":"2.0","method":"notifications/initialized"}',
'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"click_text","arguments":{"text":"开始"}}}',
]
p = subprocess.run([sys.executable, os.path.join(REPO, 'lc_mcp', 'bridge.py')],
input='\n'.join(lines) + '\n', capture_output=True, text=True,
encoding='utf-8', env=env, timeout=20)
out = [json.loads(x) for x in p.stdout.splitlines()]
self.assertEqual([o.get('id') for o in out], [1, None, 2], p.stdout + p.stderr)
self.assertEqual(out[1]['error']['code'], -32700)
self.assertFalse(out[2]['result']['isError'])
def test_bridge_offline(self):
env = dict(os.environ, LCP_PORT=str(free_port()), HOME=self.tmp.name, USERPROFILE=self.tmp.name,
PYTHONUTF8='0', PYTHONIOENCODING='cp936')
os.makedirs(os.path.join(self.tmp.name, 'lc_mcp'))
os.replace(self.token_file, os.path.join(self.tmp.name, 'lc_mcp', 'token'))
req = ('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'
'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_state"}}\n')
p = subprocess.run([sys.executable, os.path.join(REPO, 'lc_mcp', 'bridge.py')], input=req,
capture_output=True, text=True, encoding='utf-8', env=env, timeout=20)
out = [json.loads(x) for x in p.stdout.splitlines()]
self.assertIn('offline', out[0]['result']['serverInfo']['name'])
self.assertIn('未运行', out[1]['error']['message'])
self.assertEqual(p.returncode, 1)
self.assertIn('服务未运行或不可达', p.stderr)
def test_stdio_server(self):
req = ('{"jsonrpc":"2.0","id":1,"method":"ping"}\n'
'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_state"}}\n')
env = dict(os.environ, HOME=self.tmp.name, USERPROFILE=self.tmp.name)
p = subprocess.run([sys.executable, '-m', 'lc_mcp.server', '--stdio', '--fake'], cwd=REPO, input=req,
capture_output=True, text=True, encoding='utf-8', env=env, timeout=20)
out = [json.loads(x) for x in p.stdout.splitlines()]
self.assertEqual(out[0]['result'], {})
state = json.loads(out[1]['result']['content'][0]['text'])
self.assertEqual((state['ok'], state['items']), (True, []))
if __name__ == '__main__':
unittest.main()