# -*- 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_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.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) def free_port(): with socket.socket() as s: s.bind(('127.0.0.1', 0)) return s.getsockname()[1] class TransportTest(unittest.TestCase): 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) 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']) 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()