This website requires JavaScript.
0
Issues
Pull Requests
Milestones
Explore
0
Create…
New Repository
New Migration
New Organization
public
Signed in as
public
Profile
Starred
Subscriptions
Settings
Help
Sign Out
yws
/
lc-mcp
Watch
1
Star
0
Fork
0
Code
Issues
Pull Requests
Actions
Packages
Projects
Releases
Wiki
Activity
Files
lc-mcp
/
tests
/
or
Cancel
Edit File
Preview
Preview Changes
Spaces
Tabs
2
4
8
Wrap
No wrap
from pathlib import Path import json import sys import tempfile import unittest from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) import auto_cycle # noqa: E402 class FakeMcp: """按脚本返回 task_status, 记录 run_task / stop_task 调用。""" def __init__(self, *runs): self.runs = [list(r) for r in runs] # 每次 run_task 后依次返回的状态 self.calls = [] def probe(self, tool, args=None, quiet=True): self.calls.append((tool, args)) if tool == 'run_task': self.current = self.runs.pop(0) return {'ok': True} if tool == 'task_status': return self.current.pop(0) if len(self.current) > 1 else self.current[0] return {'ok': True} RUNNING = {'state': 'running'} STALL = {'state': 'running', 'stall': {'empty_team': 30}} DONE = {'state': 'succeeded', 'exit_code': 0} class FakeTime: """快进时钟。 poll_task 的循环上限是按**墙钟**判断的 (time.time() - t0 < timeout_s), 而测试里 sleep 被换成了空函数 —— 只换 sleep 不换时钟的话, 那个循环会真的 空转满 timeout_s 秒, 每圈还往 mcp.calls 里塞一条记录。实测这样跑会把内存 吃爆, 让整个测试进程以 0xC0000005 退出。 """ def __init__(self, step=1.0): self.t = 0.0 self.step = step def time(self): self.t += self.step return self.t def sleep(self, _s): pass class RunAalcTest(unittest.TestCase): def run_aalc(self, mcp, **kw): with mock.patch.object(auto_cycle, 'probe', mcp.probe), \ mock.patch.object(auto_cycle, 'blocking_module_modal', return_value=None), \ mock.patch.object(auto_cycle, 'log', lambda m: None): return auto_cycle.run_aalc('daily', {}, 3600, sleep=lambda s: None, **kw) def poll(self, mcp, timeout_s, clear=None, step=60.0): """跑 poll_task, 用快进时钟, 绝不真的等。""" clock = FakeTime(step) patches = [mock.patch.object(auto_cycle, 'probe', mcp.probe), mock.patch.object(auto_cycle, 'log', lambda m: None), mock.patch.object(auto_cycle.time, 'time', clock.time), mock.patch.object(auto_cycle, 'clear_blocking_modal', return_value='已发送 Cancel')] if clear is not None: patches.append(mock.patch.object(auto_cycle, 'blocking_module_modal', clear)) else: patches.append(mock.patch.object(auto_cycle, 'blocking_module_modal', return_value=None)) for p in patches: p.start() try: return auto_cycle.poll_task('daily', timeout_s, sleep=lambda s: None) finally: for p in patches: p.stop() def tools(self, mcp): return [t for t, _ in mcp.calls if t != 'task_status'] def test_stall_is_stopped_and_rerun_once(self): mcp = FakeMcp([RUNNING, STALL, STALL], [RUNNING, DONE]) ok, info = self.run_aalc(mcp) self.assertTrue(ok, info) self.assertEqual(self.tools(mcp), ['run_task', 'stop_task', 'run_task']) def test_single_stall_poll_is_not_enough(self): mcp = FakeMcp([STALL, RUNNING, DONE]) ok, info = self.run_aalc(mcp) self.assertTrue(ok, info) self.assertEqual(self.tools(mcp), ['run_task']) def test_gives_up_after_retries(self): mcp = FakeMcp([STALL, STALL], [STALL, STALL]) ok, info = self.run_aalc(mcp, retries=1) self.assertFalse(ok) self.assertIn('卡死', info) self.assertEqual(self.tools(mcp), ['run_task', 'stop_task', 'run_task', 'stop_task']) def test_resource_out_stops_without_rerun(self): """反复缺模组 = 资源见底, 直接收工, 不要重跑也不要等超时。 实测(2026-10-13): 体力只剩 3/126、模组不足时, AALC 的 Luxcavation 流程 会一直在"not enough Enkephalin Modules"模态框后面点被挡住的 Enter 按钮。 每次都要烧满 10 分钟才被 no_progress 判据救回, 重跑还是同样的结果。 """ mcp = FakeMcp() mcp.current = [RUNNING] * 40 ok, info, stalled = self.poll(mcp, 3600, clear=lambda: '缺模组 -> 点 Cancel') self.assertFalse(ok) self.assertEqual(info, 'RESOURCE_OUT') self.assertFalse(stalled) # 连续观察到 RESOURCE_OUT_LIMIT 次就停, 不在任务运行时点击 self.assertIn('stop_task', self.tools(mcp)) def test_occasional_modal_does_not_end_the_task(self): """偶发一次模态框不该收工, 继续观察任务。""" seq = ['x'] mcp = FakeMcp() mcp.current = [RUNNING] ok, info, stalled = self.poll( mcp, 600, clear=lambda: seq.pop(0) if seq else None) self.assertNotEqual(info, 'RESOURCE_OUT') # 跑到超时收工, 而不是被当成资源耗尽 self.assertIn('超时', info) def test_separate_shortage_sightings_are_not_consecutive(self): seq = iter(['x', None, 'x', None, 'x', None]) mcp = FakeMcp() mcp.current = [RUNNING] * 6 + [DONE] ok, info, _ = self.poll(mcp, 3600, clear=lambda: next(seq)) self.assertTrue(ok, info) self.assertNotIn('stop_task', self.tools(mcp)) def test_failed_stop_prevents_retry(self): mcp = FakeMcp([STALL, STALL], [DONE]) original = mcp.probe def probe(tool, args=None): result = original(tool, args) return {'ok': False, 'error': '进程未退出'} if tool == 'stop_task' else result mcp.probe = probe with self.assertRaisesRegex(RuntimeError, '停止 AALC 任务失败'): self.run_aalc(mcp) self.assertEqual(self.tools(mcp), ['run_task', 'stop_task']) def test_status_error_stops_the_task_before_reporting_failure(self): mcp = FakeMcp([{'ok': False, 'error': '连接中断'}]) with self.assertRaisesRegex(RuntimeError, '无法读取任务状态'): self.run_aalc(mcp) self.assertEqual(self.tools(mcp), ['run_task', 'stop_task']) def test_preflight_failure_is_not_retried(self): failed = {'state': 'failed', 'exit_code': 3, 'errors': ['[ERROR] [lc_mcp] preflight: 队伍 1 的 sinner_order 没有罪人']} mcp = FakeMcp([failed]) ok, info = self.run_aalc(mcp) self.assertFalse(ok) self.assertIn('preflight', info) self.assertEqual(self.tools(mcp), ['run_task']) def test_user_stop_never_retries(self): for status in ({'state': 'stopped', 'exit_code': 130}, {'state': 'stopped'}, {'state': 'failed', 'exit_code': 130}): mcp = FakeMcp([status], [DONE]) with self.subTest(status=status), self.assertRaises(auto_cycle.UserAborted): self.run_aalc(mcp) self.assertEqual(self.tools(mcp), ['run_task']) def test_mirror_emergency_stop_ends_cycle_before_upgrade_or_navigation(self): mcp = FakeMcp([DONE], [{'state': 'stopped', 'exit_code': 130}]) poll = auto_cycle.poll_task with tempfile.TemporaryDirectory() as tmp: with mock.patch.object(auto_cycle, 'probe', mcp.probe), \ mock.patch.object(auto_cycle, 'poll_task', side_effect=lambda t, s, **kw: poll(t, s, sleep=lambda _: None)), \ mock.patch.object(auto_cycle, 'lunacy_guard', return_value=(True, 'ok')), \ mock.patch.object(auto_cycle, 'ensure_team1', return_value=True), \ mock.patch.object(auto_cycle, 'goto_identities') as navigate, \ mock.patch.object(auto_cycle, 'run') as upgrade, \ mock.patch('builtins.print'): code = auto_cycle.main(['--mirror', '1', '--report-dir', tmp]) report = json.loads(next(Path(tmp).glob('cycle_*.json')).read_text(encoding='utf-8')) self.assertEqual(code, 130) self.assertFalse(report['ok']) self.assertIn('用户停止', report['result']) navigate.assert_not_called() upgrade.assert_not_called() self.assertEqual(self.tools(mcp), ['run_task', 'run_task']) def test_exit_zero_with_errors_is_failure(self): mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])]) ok, info = self.run_aalc(mcp) self.assertFalse(ok) def test_mirror_params_are_passed_with_task(self): mcp = FakeMcp([DONE]) with mock.patch.object(auto_cycle, 'probe', mcp.probe), \ mock.patch.object(auto_cycle, 'log', lambda m: None): auto_cycle.run_aalc('mirror', {'count': 2}, 3600, sleep=lambda s: None) self.assertEqual(mcp.calls[0], ('run_task', {'count': 2, 'task': 'mirror'})) class ScreenDetectTest(unittest.TestCase): """TEAMS / 网格的界面判定。 2026-10-13 实机: OCR 把 "SIN COST" 输出成 "SINICOST"(无空格), 而判定写死了 带空格的 'SIN COST', 于是 ensure_team1() 以为不在 TEAMS 页, 去点 Sinners 按钮空转, 每轮都报 "未能确认选中 TEAMS #1"。判定必须容忍空格。 """ def test_teams_screen_without_space_is_recognised(self): # 这是本机 OCR 的真实输出 self.assertTrue(auto_cycle.on_teams_screen( 'TEAMS#1 | Details | SINICOST | 000 | Dante | All Idensities')) def test_teams_screen_with_space_still_recognised(self): self.assertTrue(auto_cycle.on_teams_screen( 'TEAMS #1 | Details | SIN COST | 000 | Dante | All E.G.O')) def test_grid_is_not_teams_screen(self): t = 'TEAMS#1 | IDENTITIES | E.G.O | Facades | Details' self.assertFalse(auto_cycle.on_teams_screen(t)) self.assertTrue(auto_cycle.on_grid(t)) def test_main_menu_is_neither(self): t = 'Inferno | MIRROROF | Window | Sinners | Drive | Extract' self.assertFalse(auto_cycle.on_teams_screen(t)) self.assertFalse(auto_cycle.on_grid(t)) class BlockingModalTest(unittest.TestCase): """挡路模态框清道夫。 2026-10-13 实测: 模组不足时游戏弹 "You don't have enough Enkephalin Modules. / Would you like to go assemble some?" AALC 的 Luxcavation 流程不认它, 一直在后面点被挡住的 Enter 按钮。 连续观察到缺资源后先停止任务, 再重新识别并点 Cancel。 """ MODAL = [{'text': "You don't have enough Enkephalin Modules.", 'x': 554, 'y': 404, 'w': 460, 'h': 24}, {'text': 'Would you like to go assemble some?', 'x': 593, 'y': 439, 'w': 380, 'h': 24}, {'text': 'X Cancel', 'x': 592, 'y': 599, 'w': 90, 'h': 26}, {'text': 'Confirm', 'x': 924, 'y': 599, 'w': 100, 'h': 26}] def test_clicks_cancel_centre(self): clicked = [] with mock.patch.object(auto_cycle, 'items', lambda: list(self.MODAL)), \ mock.patch.object(auto_cycle, 'click', lambda x, y: (clicked.append((x, y)) or {'ok': True})): msg = auto_cycle.clear_blocking_modal() self.assertIn('Cancel', msg) # 点的是识别框中心, 不是左上角 —— 实测点左上角常常落空 self.assertEqual(clicked, [(592 + 45, 599 + 13)]) def test_other_screens_are_left_alone(self): clicked = [] grid = [{'text': 'TEAMS#1', 'x': 100, 'y': 300}, {'text': 'IDENTITIES', 'x': 200, 'y': 300}] with mock.patch.object(auto_cycle, 'items', lambda: grid), \ mock.patch.object(auto_cycle, 'click', lambda x, y: (clicked.append((x, y)) or {'ok': True})): self.assertIsNone(auto_cycle.clear_blocking_modal()) self.assertEqual(clicked, []) def test_spaces_in_ocr_text_still_match(self): # OCR 常把词粘在一起或拆开, 所以标记比对前先去空格 modal = [{'text': "You don'thave enough EnkephalinModules", 'x': 10, 'y': 20, 'w': 10, 'h': 10}, {'text': 'Cancel', 'x': 30, 'y': 40, 'w': 10, 'h': 10}] clicked = [] with mock.patch.object(auto_cycle, 'items', lambda: modal), \ mock.patch.object(auto_cycle, 'click', lambda x, y: (clicked.append((x, y)) or {'ok': True})): self.assertIsNotNone(auto_cycle.clear_blocking_modal()) self.assertEqual(clicked, [(35, 45)]) def test_rejected_click_is_not_reported_as_cleared(self): with mock.patch.object(auto_cycle, 'items', return_value=self.MODAL), \ mock.patch.object(auto_cycle, 'click', return_value={'ok': False, 'error': '先 stop_task'}): with self.assertRaisesRegex(RuntimeError, '先 stop_task'): auto_cycle.clear_blocking_modal() def test_real_protocol_receives_cancel_only_after_task_stops(self): # 使用真实 Server 的输入互斥逻辑, 避免假 click 掩盖“运行中点击被拒绝”。 from lc_mcp.fake_engine import FakeEngine from lc_mcp.protocol import Server runner = mock.Mock() runner.info = {'task': 'daily'} runner.running.return_value = True runner.status.return_value = {'ok': True, 'state': 'running'} def stop(): runner.running.return_value = False return {'ok': True, 'state': 'stopped'} runner.stop.side_effect = stop engine = FakeEngine(frames=[self.MODAL]) server = Server(engine, runner) click_states = [] def click(x, y): click_states.append(runner.running()) return server.call_tool('click', {'x': x, 'y': y}) with mock.patch.object(auto_cycle, 'probe', lambda tool, args=None: server.call_tool(tool, args or {})), \ mock.patch.object(auto_cycle, 'items', lambda: server.call_tool('get_state', {})['items']), \ mock.patch.object(auto_cycle, 'click', click), \ mock.patch.object(auto_cycle, 'log'), \ mock.patch.object(auto_cycle.time, 'time', FakeTime().time): ok, info, stalled = auto_cycle.poll_task('daily', 3600, sleep=lambda s: None) self.assertEqual((ok, info, stalled), (False, 'RESOURCE_OUT', False)) self.assertEqual(click_states, [False]) self.assertEqual(engine.actions, [('click', 637, 612, 1)]) runner.stop.assert_called_once() class CycleReportTest(unittest.TestCase): def test_crashed_levelup_is_a_failed_report_with_diagnostics(self): with tempfile.TemporaryDirectory() as tmp: script = Path(tmp, 'broken_levelup.py') script.write_text('raise RuntimeError("levelup crashed")\n', encoding='utf-8') with mock.patch.multiple(auto_cycle, PY=sys.executable, LEVELUP=str(script)), \ mock.patch.object(auto_cycle, 'lunacy_guard', return_value=(True, '读数一致')), \ mock.patch.object(auto_cycle, 'ensure_team1', return_value=True), \ mock.patch.object(auto_cycle, 'run_aalc', return_value=(True, '已完成')), \ mock.patch.object(auto_cycle, 'goto_identities', return_value=True), \ mock.patch.object(auto_cycle, 'report_grid', return_value='grid'), \ mock.patch.object(auto_cycle.time, 'sleep'), \ mock.patch('builtins.print'): code = auto_cycle.main(['--report-dir', tmp]) report = json.loads(next(Path(tmp).glob('cycle_*.json')).read_text(encoding='utf-8')) output = next(Path(tmp).glob('cycle_*.log')).read_text(encoding='utf-8') self.assertEqual(code, 1) self.assertFalse(report['ok']) self.assertIn('levelup crashed', output) self.assertNotIn('无需升级', output) self.assertIsNone(auto_cycle._log_file) class LunacyReadTest(unittest.TestCase): """狂气 OCR 是辅助核查, 读不到就是没校验, 所以要重试。 2026-10-13 实测更麻烦的一种情况: 同一个画面上 OCR 会给出**两个不同的值** (放大 6 倍肉眼确认余额是 6388, 而连读 5 次得到 6388 四次、8859 一次)。 8859 被当成基线后, 之后正确的 6388 反而被判成"已消耗"并中止整轮。 所以要取众数, 不是"最后读到什么就是什么"。 """ MAIN = [{'text': 'Window', 'x': 993, 'y': 804}, {'text': 'Sinners', 'x': 1093, 'y': 811}, {'text': 'Drive', 'x': 1201, 'y': 808}, {'text': 'Extract', 'x': 1389, 'y': 809}, {'text': 'Dispense', 'x': 1486, 'y': 810}] def _frames(self, values): """按顺序返回若干帧; 每帧都是主界面 + LUNACY + 该帧的值。""" seq = list(values) def fake_items(): v = seq.pop(0) if len(seq) > 1 else seq[0] if v is None: return list(self.MAIN) return list(self.MAIN) + [{'text': 'LUNACY', 'x': 671, 'y': 795}, {'text': str(v), 'x': 664, 'y': 823}] return fake_items def test_outlier_does_not_win(self): # 5 次里 4 次 6388、1 次 8859 -> 取 6388 with mock.patch.object(auto_cycle, 'items', self._frames([6388, 8859, 6388, 6388, 6388])), \ mock.patch.object(auto_cycle.time, 'sleep', lambda s: None): self.assertEqual(auto_cycle.read_lunacy(), 6388) def test_first_pair_does_not_override_later_majority(self): with mock.patch.object(auto_cycle, 'items', self._frames([8859, 8859, 6388, 6388, 6388])), \ mock.patch.object(auto_cycle.time, 'sleep'): self.assertEqual(auto_cycle.read_lunacy(), 6388) def test_tied_readings_are_unknown(self): with mock.patch.object(auto_cycle, 'items', self._frames([8859, 8859, 6388, 6388, None])), \ mock.patch.object(auto_cycle.time, 'sleep'): self.assertIsNone(auto_cycle.read_lunacy()) def test_truncated_label_and_low_balance_are_read(self): frame = [{'text': 'UNACY', 'x': 671, 'y': 795}, {'text': '0', 'x': 664, 'y': 823}] with mock.patch.object(auto_cycle, 'items', return_value=frame), \ mock.patch.object(auto_cycle.time, 'sleep'): self.assertEqual(auto_cycle.read_lunacy(), 0) def test_retries_until_the_label_shows_up(self): with mock.patch.object(auto_cycle, 'items', self._frames([None, None, 5864, 5864, 5864])), \ mock.patch.object(auto_cycle.time, 'sleep', lambda s: None): self.assertEqual(auto_cycle.read_lunacy(), 5864) def test_gives_up_when_never_agreeing(self): # 每个值都只出现一次 -> 不采信, 宁可返回 None 也不要拿错值当基线 with mock.patch.object(auto_cycle, 'items', self._frames([1000, 2000, 3000, 4000, 5000])), \ mock.patch.object(auto_cycle.time, 'sleep', lambda s: None): self.assertIsNone(auto_cycle.read_lunacy()) def test_reads_on_any_screen_not_just_main_menu(self): # 曾经加过"只在主界面取数"的限制, 结果几乎总是读不到(轮次起止常停在副本/ # 网格/结算页), 守卫直接跳过 —— 防线等于没有。众数投票已经能压住误读, # 所以非主界面也读。 fake = [{'text': 'LUNACY', 'x': 671, 'y': 795}, {'text': '6388', 'x': 664, 'y': 823}, {'text': 'Mirror Dungeon Result', 'x': 700, 'y': 400}] with mock.patch.object(auto_cycle, 'items', lambda: fake), \ mock.patch.object(auto_cycle.time, 'sleep', lambda s: None): self.assertEqual(auto_cycle.read_lunacy(), 6388) if __name__ == '__main__': unittest.main()
Commit Changes
Add a Signed-off-by trailer by the committer at the end of the commit log message.
Commit directly to the
codex/local-wip-20261022
branch.
Create a
new branch
for this commit and start a pull request.
Commit Changes
Cancel