Files
lc-mcp/tests/test_convert_modules.py
T
Codex Agent b9e1837877 合成: "点了确认但模组没变"重试一次, 区分"上限"和"界面没响应"
convert_once() 原来只做一次尝试, 拿到"模组没变"就直接判失败。但这个结果有
两种完全不同的原因:
  1. 游戏限制了本轮/本日能换的数量 —— 正常, 重试也没用
  2. 界面这一次没响应 —— 偶发, 关掉面板重开通常就好
分不清这两者, 就没法给出对的结论。

拆成 convert_once(重试壳) + _convert_attempt(单次): 第一次没换到就关掉面板
重开再试一次, 第二次仍然不变才如实报"可能已达上限或体力不足"。
重试前必须关面板 —— 不关的话面对的还是那个没响应的界面, 重试等于白做。

mocked 验证三条路径: 一次成功不重试、第一次失败第二次成功、两次都失败报原因。
新增 4 个用例, 全套 263/263 通过。
2026-10-16 10:58:58 +08:00

281 lines
12 KiB
Python

# -*- coding: utf-8 -*-
"""convert_modules 的纯逻辑测试。
这个脚本会操作真实游戏, 所以这里只测不碰硬件的部分: 屏幕判定、资源读数、
狂气相对比对用的解析。合成动作本身靠实机验证。
"""
import sys
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
import convert_modules as cm # noqa: E402
class QuietLogMixin:
"""把脚本的 log() 静音。
cm.log 会同时写 stdout 和 ~/lc_mcp/modules/convert.log —— 那是值守时要看的
真实运行记录, 不能被测试噪音污染(实测跑一次测试就往里塞了"服务未监听"
和"等服务就绪超时"两条, 看起来像是真出事了)。
"""
def setUp(self):
patcher = mock.patch.object(cm, 'log', lambda m: None)
patcher.start()
self.addCleanup(patcher.stop)
class ScreenDetectTest(QuietLogMixin, unittest.TestCase):
def test_main_menu_needs_enough_markers(self):
good = 'Window | Sinners | Drive | Theater | Extract | Dispense'
self.assertTrue(cm.on_main_menu(good))
def test_partial_screen_is_not_main_menu(self):
# 标题页只有一两个词, 不能当成主界面 —— 否则会在标题页上找模组图标
self.assertFalse(cm.on_main_menu('TOUCH TO START | Clear all caches'))
self.assertFalse(cm.on_main_menu('Window | Sinners'))
def test_panel_marker(self):
self.assertTrue(cm.panel_open('Charge Enkephalin | Modules | Use Lunacy'))
self.assertFalse(cm.panel_open('Window | Sinners | Drive'))
class ReadOwnedTest(QuietLogMixin, unittest.TestCase):
def test_reads_owned(self):
its = [{'text': 'Enkephalin Module Owned 29', 'x': 820, 'y': 334}]
with mock.patch.object(cm, 'items', lambda: its):
self.assertEqual(cm.read_owned(), 29)
def test_falls_back_to_bare_number(self):
its = [{'text': 'Owned', 'x': 820, 'y': 334},
{'text': '29', 'x': 900, 'y': 334}]
with mock.patch.object(cm, 'items', lambda: its):
self.assertEqual(cm.read_owned(), 29)
def test_none_when_absent(self):
with mock.patch.object(cm, 'items', lambda: [{'text': 'Window', 'x': 1, 'y': 800}]):
self.assertIsNone(cm.read_owned())
class ReadEnkephalinTest(QuietLogMixin, unittest.TestCase):
"""只认主界面底栏的 x/126。
合成面板里也有一个 x/126, 但那是"合成后"的预览值 —— 拿它当余额会把
"体力不足"误判成"还有体力", 于是每轮都去点确认。
"""
def test_reads_bottom_bar(self):
its = [{'text': '13/126', 'x': 451, 'y': 827}]
with mock.patch.object(cm, 'items', lambda: its):
self.assertEqual(cm.read_enkephalin(), 13)
def test_ignores_panel_preview(self):
# y≈508 是合成面板里的预览, 不是余额
its = [{'text': '132/126', 'x': 709, 'y': 508}]
with mock.patch.object(cm, 'items', lambda: its):
self.assertIsNone(cm.read_enkephalin())
def test_handles_spaces_and_garbage(self):
its = [{'text': '13 / 126', 'x': 451, 'y': 827}]
with mock.patch.object(cm, 'items', lambda: its):
self.assertEqual(cm.read_enkephalin(), 13)
class LunacyReadTest(QuietLogMixin, unittest.TestCase):
"""狂气数字是像素艺术字, OCR 会误读(实测 6636 读成 9699)。
所以脚本不对绝对值下结论, 只做**前后相对比对**: 同一个画面同一套字体,
误读方式一致, 两次读数不同就说明数字真的变了。
"""
def _frames(self, values):
seq = list(values)
def fake():
v = seq.pop(0) if len(seq) > 1 else seq[0]
return [{'text': 'LUNACY', 'x': 670, 'y': 795},
{'text': str(v), 'x': 664, 'y': 823}]
return fake
def test_majority_wins_over_outlier(self):
with mock.patch.object(cm, 'items', self._frames([9699, 6636, 9699, 9699, 9699])), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
self.assertEqual(cm.read_lunacy(), 9699)
def test_none_when_no_label(self):
with mock.patch.object(cm, 'items', lambda: [{'text': 'Window', 'x': 1, 'y': 800}]), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
self.assertIsNone(cm.read_lunacy())
class ConvertRetryTest(QuietLogMixin, unittest.TestCase):
""""点了确认但模组没变"有两种原因, 该有不同的处置。
1. 游戏限制了本轮/本日能换的数量 —— 正常, 重试也没用
2. 界面这一次没响应 —— 偶发, 重开面板通常就好
只做一次分不清这两者, 所以默认重试一次。
"""
def _run(self, attempts):
seq = list(attempts)
with mock.patch.object(cm, '_convert_attempt', lambda: seq.pop(0)), \
mock.patch.object(cm, 'close_panel', lambda: True), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
return cm.convert_once()
def test_retries_once_then_succeeds(self):
ok, info, got = self._run([(False, '点了确认但模组没变(29)', 0),
(True, '模组 29 -> 30 (+1)', 1)])
self.assertTrue(ok)
self.assertEqual(got, 1)
self.assertIn('29 -> 30', info)
def test_both_attempts_fail_reports_the_reason(self):
ok, info, got = self._run([(False, '点了确认但模组没变(29)', 0),
(False, '点了确认但模组没变(29)', 0)])
self.assertFalse(ok)
self.assertIn('没变', info)
def test_no_retry_when_first_succeeds(self):
calls = []
def once():
calls.append(1)
return True, '模组 29 -> 30 (+1)', 1
with mock.patch.object(cm, '_convert_attempt', once):
cm.convert_once()
self.assertEqual(len(calls), 1, '成功了就不该再试')
def test_retry_closes_the_panel_first(self):
"""重试前必须把面板关掉重开 —— 不关的话还是那个没响应的界面。"""
closed = []
seq = [(False, 'no', 0), (True, 'ok', 1)]
with mock.patch.object(cm, '_convert_attempt', lambda: seq.pop(0)), \
mock.patch.object(cm, 'close_panel', lambda: closed.append(1) or True), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
cm.convert_once()
self.assertEqual(len(closed), 1)
class DisplayRecoveryTest(QuietLogMixin, unittest.TestCase):
"""断线时桌面被拆掉, 截图全黑 —— 先修显示再动游戏。
看门狗每分钟修一次, 但整轮合成只跑 3 分钟; 断线正好落在这 3 分钟里的话,
这轮必然失败而下一轮要等 4 小时。实测 2026-10-16 一天内会话掉了两次。
"""
def test_ok_when_rendering(self):
with mock.patch.object(cm, 'render_ok', lambda: True), \
mock.patch.object(cm.subprocess, 'run') as run:
self.assertTrue(cm.ensure_display())
run.assert_not_called() # 正常时不该去折腾看门狗
def test_runs_watchdog_then_rechecks(self):
seq = [False, False, True] # 先挂两次, 第三次恢复
calls = []
def fake_run(cmd, **kw):
calls.append(cmd)
return mock.Mock(returncode=0)
with mock.patch.object(cm, 'render_ok', lambda: seq.pop(0)), \
mock.patch.object(cm.subprocess, 'run', fake_run), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
self.assertTrue(cm.ensure_display(timeout_s=10))
self.assertEqual(len(calls), 1, '应该跑一次看门狗')
self.assertIn('keep_display.ps1', ' '.join(calls[0]))
def test_reports_failure_when_never_recovers(self):
with mock.patch.object(cm, 'render_ok', lambda: False), \
mock.patch.object(cm.subprocess, 'run', lambda *a, **k: mock.Mock()), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
self.assertFalse(cm.ensure_display(timeout_s=0))
def test_watchdog_launch_failure_does_not_crash(self):
# 看门狗自己起不来时也要给出结论, 而不是抛异常
def boom(*a, **k):
raise OSError('powershell not found')
with mock.patch.object(cm, 'render_ok', lambda: False), \
mock.patch.object(cm.subprocess, 'run', boom), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
self.assertFalse(cm.ensure_display(timeout_s=0))
class ServerBootstrapTest(QuietLogMixin, unittest.TestCase):
"""值守时没人手动救服务, 所以脚本要能自己确认/拉起 lc-mcp 的 TCP 服务。
计划任务 LcMCPServer 配了 RestartCount=3, 但那只在进程"崩溃"时生效;
服务压根没起来(或重启后还没登录)时, 合成会因为连不上而失败。
"""
def test_listening_returns_bool(self):
self.assertIsInstance(cm.server_listening(timeout=0.5), bool)
def test_ensure_server_short_circuits_when_listening(self):
with mock.patch.object(cm, 'server_listening', lambda **kw: True):
self.assertTrue(cm.ensure_server(timeout_s=1))
def test_ensure_server_gives_up_when_never_listening(self):
calls = []
with mock.patch.object(cm, 'server_listening', lambda **kw: False), \
mock.patch.object(cm.subprocess, 'Popen',
lambda *a, **k: calls.append(a)), \
mock.patch.object(cm.time, 'sleep', lambda s: None):
self.assertFalse(cm.ensure_server(timeout_s=0))
self.assertEqual(len(calls), 1, '应该尝试拉起服务一次')
def test_server_port_matches_the_project_default(self):
# 服务端 lc_mcp/server.py 用的就是 8765, 改这里要同步改
self.assertEqual(cm.SERVER_PORT, 8765)
class ForbiddenCoordinateTest(QuietLogMixin, unittest.TestCase):
"""Use Lunacy 页签的坐标只能用于"确认没点到它", 不能出现在任何点击路径上。
这条做成测试, 是因为以后改动布局时很容易顺手把它接进某个分支 ——
那是一步就能花掉狂气的操作。用 AST 查实参, 而不是查文本: 文本里
文档说明本来就会提到这个常量名。
"""
def _source(self):
return (Path(__file__).resolve().parents[1] / 'scripts' / 'convert_modules.py') \
.read_text(encoding='utf-8')
def test_no_click_call_passes_the_use_lunacy_tab(self):
import ast
tree = ast.parse(self._source())
offenders = []
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
f = node.func
name = getattr(f, 'id', None) or getattr(f, 'attr', None)
if name != 'click':
continue
for arg in list(node.args):
# click(*USE_LUNACY_TAB) 或 click(USE_LUNACY_TAB[0], ...)
if isinstance(arg, ast.Starred):
arg = arg.value
if isinstance(arg, ast.Name) and arg.id == 'USE_LUNACY_TAB':
offenders.append('line %d' % node.lineno)
if isinstance(arg, ast.Subscript) and \
getattr(arg.value, 'id', None) == 'USE_LUNACY_TAB':
offenders.append('line %d' % node.lineno)
self.assertFalse(offenders, 'click() 用到了 Use Lunacy 页签坐标: ' + ', '.join(offenders))
def test_the_constant_still_exists_and_is_where_we_think(self):
"""万一布局变了, 这条会提醒重新量坐标, 而不是让上面那条静静地失效。"""
self.assertEqual(cm.USE_LUNACY_TAB, (797, 283))
self.assertLess(cm.TAB_MODULES[0], cm.USE_LUNACY_TAB[0]) # Modules 在左
self.assertLess(cm.USE_LUNACY_TAB[0], cm.TAB_USE_BOXES[0]) # Use Boxes 在右
if __name__ == '__main__':
unittest.main()