1053 lines
48 KiB
Python
1053 lines
48 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""convert_modules 的纯逻辑测试。
|
|
|
|
这个脚本会操作真实游戏, 所以这里只测不碰硬件的部分: 屏幕判定、资源读数、
|
|
狂气相对比对用的解析。合成动作本身靠实机验证。
|
|
"""
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
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 LunacyLabelTest(QuietLogMixin, unittest.TestCase):
|
|
"""⛔ 实测坑: OCR 会把 "LUNACY" 读成 "UNACY"(首字母 L 被吃掉)。
|
|
|
|
原来写的是 `'LUNACY' in text`, 而 "UNACY" 不含 "LUNACY" —— 于是每次都被判成
|
|
"读不到", 狂气校验退化成 None -> 跳过比对, 第三道防线形同虚设。同一块底栏的
|
|
体力却一直读得到, 所以只看日志很难发现, 是 dump 了底栏 OCR 才抓到的。
|
|
"""
|
|
|
|
def _with(self, its):
|
|
with mock.patch.object(cm, 'items', lambda: its):
|
|
return cm.find_lunacy_label()
|
|
|
|
def test_matches_truncated_label(self):
|
|
lab = self._with([{'text': 'UNACY', 'x': 674, 'y': 795, 'w': 44, 'h': 22}])
|
|
self.assertIsNotNone(lab)
|
|
self.assertEqual(lab['text'], 'UNACY')
|
|
|
|
def test_matches_full_label(self):
|
|
self.assertIsNotNone(self._with([{'text': 'LUNACY', 'x': 670, 'y': 795}]))
|
|
|
|
def test_full_read_works_with_truncated_label(self):
|
|
its = [{'text': 'UNACY', 'x': 674, 'y': 795, 'w': 44, 'h': 22},
|
|
{'text': '9699', 'x': 664, 'y': 823, 'w': 70, 'h': 37}]
|
|
with mock.patch.object(cm, 'items', lambda: its), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None):
|
|
self.assertEqual(cm.read_lunacy(), 9699)
|
|
|
|
def test_falls_back_to_position_when_label_unreadable(self):
|
|
# 标签整个读不出来时, 按位置兜底: 底栏那一带最靠左的短文本
|
|
its = [{'text': '???', 'x': 674, 'y': 795, 'w': 44, 'h': 22},
|
|
{'text': '9699', 'x': 664, 'y': 823, 'w': 70, 'h': 37}]
|
|
lab = self._with(its)
|
|
self.assertIsNotNone(lab)
|
|
with mock.patch.object(cm, 'items', lambda: its), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None):
|
|
self.assertEqual(cm.read_lunacy(), 9699)
|
|
|
|
def test_no_label_at_all_returns_none(self):
|
|
its = [{'text': 'Window', 'x': 994, 'y': 809}]
|
|
self.assertIsNone(self._with(its))
|
|
|
|
|
|
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 误读; 同帧取数、多帧投票仍只提供核查线索。"""
|
|
|
|
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())
|
|
|
|
def test_first_pair_does_not_override_later_majority(self):
|
|
with mock.patch.object(cm, 'items', self._frames([8859, 8859, 6388, 6388, 6388])), \
|
|
mock.patch.object(cm.time, 'sleep'):
|
|
self.assertEqual(cm.read_lunacy(), 6388)
|
|
|
|
def test_label_and_balance_must_come_from_the_same_frame(self):
|
|
# 数字和标签从未同时出现, 跨帧拼接会伪造一个有效读数。
|
|
frames = [[{'text': '9999', 'x': 664, 'y': 823}],
|
|
[{'text': 'LUNACY', 'x': 670, 'y': 795}]] * 5
|
|
with mock.patch.object(cm, 'items', side_effect=frames) as sample, \
|
|
mock.patch.object(cm.time, 'sleep'):
|
|
self.assertIsNone(cm.read_lunacy())
|
|
self.assertEqual(sample.call_count, 5)
|
|
|
|
def test_tied_readings_are_unknown(self):
|
|
with mock.patch.object(cm, 'items', self._frames([8859, 8859, 6388, 6388, 1000])), \
|
|
mock.patch.object(cm.time, 'sleep'):
|
|
self.assertIsNone(cm.read_lunacy())
|
|
|
|
|
|
class EnkephalinGateTest(QuietLogMixin, unittest.TestCase):
|
|
"""体力读数是"要不要合成"的闸门, 读不到时不能贸然去点合成。
|
|
|
|
单次读成 None 的话, 原来那层"体力不足就收工"的判断会被整个跳过 —— 于是明明
|
|
只是体力不够, 却要去点合成、最后报成 FAIL(退出码 1), 给值守留下一条误导性
|
|
的失败记录。底栏淡入时读不到是实测发生过的(2026-10-16 11:01 的狂气读数)。
|
|
|
|
⛔ main() 会把报告写进 ~/lc_mcp/modules/convert_*.json —— 那是值守要看的历史。
|
|
调用时必须把 --report-dir 指到临时目录, 否则测试会伪造出一批
|
|
"读不到体力读数" 的假记录(实测已经产生过 7 条)。
|
|
"""
|
|
|
|
def _main(self, enk_seq):
|
|
seq = list(enk_seq)
|
|
called = []
|
|
tmp = tempfile.mkdtemp()
|
|
self.addCleanup(shutil.rmtree, tmp, True)
|
|
with mock.patch.object(cm, 'read_enkephalin', lambda: seq.pop(0) if seq else None), \
|
|
mock.patch.object(cm, 'read_lunacy', lambda **k: 9699), \
|
|
mock.patch.object(cm, 'ensure_server', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_display', lambda *a: True), \
|
|
mock.patch.object(cm, 'launch_game', lambda *a: True), \
|
|
mock.patch.object(cm, 'wait_main_menu', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_window_size', lambda *a: (1600, 900)), \
|
|
mock.patch.object(cm, 'close_panel', lambda: True), \
|
|
mock.patch.object(cm, 'close_game', lambda: None), \
|
|
mock.patch.object(cm, 'convert_once',
|
|
lambda tries=2: (called.append(1),
|
|
(True, '模组 29 -> 30 (+1)', 1))[1]), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None):
|
|
code = cm.main(['--report-dir', tmp])
|
|
return code, bool(called)
|
|
|
|
def test_enough_enkephalin_goes_ahead(self):
|
|
code, called = self._main([25])
|
|
self.assertEqual(code, 0)
|
|
self.assertTrue(called)
|
|
|
|
def test_not_enough_skips_without_touching_confirm(self):
|
|
code, called = self._main([4])
|
|
self.assertEqual(code, 0, '体力不足是正常情况, 不该报失败')
|
|
self.assertFalse(called, '体力不足时绝不该去点合成')
|
|
|
|
def test_unreadable_enkephalin_skips_instead_of_failing(self):
|
|
code, called = self._main([None, None, None, None])
|
|
self.assertEqual(code, 0, '读不到就跳过, 不要报成 FAIL')
|
|
self.assertFalse(called)
|
|
|
|
def test_read_is_retried(self):
|
|
"""前几次读不到要接着读, 不能一次读不到就放弃。"""
|
|
code, called = self._main([None, None, 25])
|
|
self.assertEqual(code, 0)
|
|
self.assertTrue(called, '重试后读到了就该正常合成')
|
|
|
|
|
|
class WindowSizeTest(QuietLogMixin, unittest.TestCase):
|
|
"""RDP 断线重连会把客户区改小(实测 1600x900 -> 1278x719), 之后 OCR 明显变差。
|
|
|
|
AALC 自己的 WindowGuard 只在跑任务时才生效, 而这个脚本不跑任务, 所以要自己调。
|
|
"""
|
|
|
|
def test_missing_window_returns_none(self):
|
|
self.assertIsNone(cm.ensure_window_size(1600, 900, find=lambda: 0))
|
|
|
|
def test_correct_size_is_left_alone(self):
|
|
moved = []
|
|
r = cm.ensure_window_size(
|
|
1600, 900,
|
|
find=lambda: 123,
|
|
client=lambda h: (1600, 900),
|
|
resize=lambda *a: moved.append(a))
|
|
self.assertEqual(r, (1600, 900))
|
|
self.assertEqual(moved, [], '尺寸已经对了就不该去动窗口')
|
|
|
|
def test_wrong_size_is_fixed(self):
|
|
sizes = iter([(1278, 719), (1600, 900)])
|
|
moved = []
|
|
r = cm.ensure_window_size(
|
|
1600, 900,
|
|
find=lambda: 123,
|
|
client=lambda h: next(sizes),
|
|
resize=lambda *a: moved.append(a))
|
|
self.assertEqual(r, (1600, 900))
|
|
self.assertEqual(len(moved), 1, '尺寸不对时应该调一次')
|
|
# 传下去的是目标客户区尺寸和"调整前"的客户区
|
|
self.assertEqual(moved[0][1:], (1600, 900, (1278, 719)))
|
|
|
|
def test_reports_actual_size_even_if_resize_fails(self):
|
|
"""调不动时返回真实值, 让调用方自己能告警 —— 不要假装调好了。"""
|
|
r = cm.ensure_window_size(
|
|
1600, 900,
|
|
find=lambda: 123,
|
|
client=lambda h: (1278, 719),
|
|
resize=lambda *a: None)
|
|
self.assertEqual(r, (1278, 719))
|
|
|
|
|
|
class LunacyVerdictTest(unittest.TestCase):
|
|
"""⛔ 狂气那个数字的判据 —— 曾被"相对比对"的错假设坑过两次。
|
|
|
|
2026-10-16 22:03 实测: 合成前读到 6636、合成后读到 9699, 复读仍是 9699,
|
|
于是报了"狂气读数发生变化"并让整轮 FAIL。但那一轮脚本只点了模组图标和面板内的
|
|
» / 确认, 从没碰 Use Lunacy 页签 —— **是误报**。
|
|
|
|
根因: 我以为"同一画面的误读方式一致", 实际上真值 6636 被读过 6636 / 9699 /
|
|
6388 / 8859 四种样子, 误读根本不固定。所以"前后不同"区分不了
|
|
"真变了" 和 "换了个误读法"。
|
|
|
|
现在只有一种情况算可疑: 读到从没见过的值。
|
|
"""
|
|
|
|
KNOWN = cm.LUNACY_KNOWN_READINGS
|
|
|
|
def test_same_reading_is_clean(self):
|
|
suspicious, why = cm.lunacy_verdict(9699, 9699)
|
|
self.assertFalse(suspicious)
|
|
self.assertIn('一致', why)
|
|
|
|
def test_the_real_false_alarm_is_now_clean(self):
|
|
"""22:03 那次的真实读数 —— 必须不再被当成消费。"""
|
|
suspicious, why = cm.lunacy_verdict(6636, 9699)
|
|
self.assertFalse(suspicious, '6636 -> 9699 是已知的两种读法, 不是消费')
|
|
self.assertIn('已知读法', why)
|
|
|
|
def test_jitter_between_known_readings_is_clean(self):
|
|
for a in self.KNOWN:
|
|
for b in self.KNOWN:
|
|
suspicious, why = cm.lunacy_verdict(a, b)
|
|
self.assertFalse(suspicious, '%s -> %s 都属已知读法, 不该报' % (a, b))
|
|
|
|
def test_unreadable_is_not_a_verdict(self):
|
|
suspicious, why = cm.lunacy_verdict(9699, None)
|
|
self.assertFalse(suspicious, '读不到不等于变了')
|
|
self.assertIn('未做比对', why)
|
|
|
|
def test_unknown_value_is_suspicious(self):
|
|
"""真的被消费(或获得)狂气时会读到陌生值, 那种要报出来。"""
|
|
suspicious, why = cm.lunacy_verdict(6636, 3000)
|
|
self.assertTrue(suspicious)
|
|
self.assertIn('不在已知读法', why)
|
|
|
|
def test_unknown_value_on_the_before_side_also_alerts(self):
|
|
# 合成前就读到陌生值 -> 说明基线本身变了, 同样值得看
|
|
suspicious, why = cm.lunacy_verdict(4000, 4000)
|
|
self.assertFalse(suspicious) # 前后一致就不管(可能只是 OCR 一直这么读)
|
|
suspicious2, _ = cm.lunacy_verdict(4000, 3000)
|
|
self.assertTrue(suspicious2)
|
|
|
|
def test_new_balance_must_not_be_silently_folded_into_old_readings(self):
|
|
suspicious, _ = cm.lunacy_verdict(10000, 6636)
|
|
self.assertTrue(suspicious)
|
|
|
|
|
|
class LunacyFalseAlarmTest(QuietLogMixin, unittest.TestCase):
|
|
"""整轮跑下来: 已知读法抖动不该让这一轮 FAIL。"""
|
|
|
|
def _run(self, lunacy_seq):
|
|
s = list(lunacy_seq)
|
|
with mock.patch.object(cm, 'read_enkephalin', lambda: 25), \
|
|
mock.patch.object(cm, 'ensure_server', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_display', lambda *a: True), \
|
|
mock.patch.object(cm, 'launch_game', lambda *a: True), \
|
|
mock.patch.object(cm, 'wait_main_menu', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_window_size', lambda *a: (1600, 900)), \
|
|
mock.patch.object(cm, 'close_panel', lambda: True), \
|
|
mock.patch.object(cm, 'close_game', lambda: None), \
|
|
mock.patch.object(cm, 'convert_once',
|
|
lambda tries=2: (True, '模组 29 -> 30 (+1)', 1)), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None), \
|
|
mock.patch.object(cm, 'read_lunacy',
|
|
lambda **k: s.pop(0) if s else None):
|
|
tmp = tempfile.mkdtemp()
|
|
self.addCleanup(shutil.rmtree, tmp, True)
|
|
return cm.main(['--report-dir', tmp])
|
|
|
|
def test_consistent_reading_passes(self):
|
|
self.assertEqual(self._run([9699, 9699]), 0)
|
|
|
|
def test_real_false_alarm_case_now_passes(self):
|
|
"""22:03 那次: 6636 -> 9699 -> 复读 9699。修好后这轮必须算成功。"""
|
|
self.assertEqual(self._run([6636, 9699, 9699]), 0,
|
|
'已知读法之间的抖动不该让整轮 FAIL')
|
|
|
|
def test_unknown_value_still_fails_the_run(self):
|
|
self.assertEqual(self._run([6636, 3000, 3000]), 1,
|
|
'读到陌生值必须报出来')
|
|
|
|
def test_unreadable_after_is_not_a_failure(self):
|
|
self.assertEqual(self._run([9699, None, None, None, None]), 0)
|
|
|
|
|
|
class ConvertAttemptVerifiedTest(QuietLogMixin, unittest.TestCase):
|
|
"""⛔ 每一层"读不到"都不能被当成成功。
|
|
|
|
原来这段有两个假成功分支:
|
|
if now is not None and before is None: return True, '模组现为 %d'
|
|
return True, '模组 %s -> %s' % (before, after) # 两边都可能是 None
|
|
读不到起点就无从判断有没有换到, 却报了成功 —— 和"狂气读不到就静默跳过"
|
|
是同一类毛病: 降级路径看起来没事, 实际什么都没验证。
|
|
"""
|
|
|
|
def _clock(self):
|
|
c = {'t': 0.0}
|
|
|
|
def ft():
|
|
c['t'] += 3.0
|
|
return c['t']
|
|
return ft
|
|
|
|
def _attempt(self, owned_fn, on_tab=True):
|
|
with mock.patch.object(cm, 'open_panel', lambda *a, **k: True), \
|
|
mock.patch.object(cm, 'on_modules_tab', lambda: on_tab), \
|
|
mock.patch.object(cm, '_read_owned_once', owned_fn), \
|
|
mock.patch.object(cm, 'click', lambda *a, **k: None), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None), \
|
|
mock.patch.object(cm.time, 'time', self._clock()):
|
|
return cm._convert_attempt()
|
|
|
|
def test_unreadable_start_is_not_success(self):
|
|
ok, info, got = self._attempt(lambda: None)
|
|
self.assertFalse(ok, '读不到起点绝不能报成功')
|
|
self.assertIn('读不到合成前', info)
|
|
|
|
def test_increase_is_success(self):
|
|
seq = [29, 29, 30]
|
|
ok, info, got = self._attempt(lambda: seq.pop(0) if seq else 30)
|
|
self.assertTrue(ok)
|
|
self.assertEqual(got, 1)
|
|
self.assertIn('29 -> 30', info)
|
|
|
|
def test_unchanged_is_failure(self):
|
|
ok, info, got = self._attempt(lambda: 29)
|
|
self.assertFalse(ok)
|
|
self.assertIn('没变', info)
|
|
|
|
def test_decrease_is_not_a_successful_negative_conversion(self):
|
|
seq = [35]
|
|
ok, info, got = self._attempt(lambda: seq.pop(0) if seq else 33)
|
|
self.assertFalse(ok)
|
|
self.assertEqual(got, 0)
|
|
self.assertIn('读数下降', info)
|
|
|
|
def test_unchanged_message_does_not_blame_enkephalin(self):
|
|
"""走到这一步时体力 >= 20 已经确认过, 所以"体力不足"不可能是原因。
|
|
|
|
文案里带上它只会把排查方向带偏 —— 上限和界面没响应才是真实可能。
|
|
"""
|
|
ok, info, got = self._attempt(lambda: 29)
|
|
self.assertNotIn('体力不足', info)
|
|
self.assertIn('上限', info)
|
|
|
|
def test_unreadable_after_is_not_success(self):
|
|
seq = [29] + [None] * 60
|
|
ok, info, got = self._attempt(lambda: seq.pop(0) if seq else None)
|
|
self.assertFalse(ok, '合成后读不到也不能报成功')
|
|
self.assertIn('无法确认结果', info)
|
|
|
|
def test_wrong_tab_refuses(self):
|
|
ok, info, got = self._attempt(lambda: 29, on_tab=False)
|
|
self.assertFalse(ok)
|
|
self.assertIn('Modules', info)
|
|
|
|
|
|
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)
|
|
|
|
# session_state 固定成 None: 否则诊断用的 `query session` 也走 subprocess,
|
|
# 会混进 calls 里把"看门狗跑了几次"数错
|
|
with mock.patch.object(cm, 'render_ok', lambda: seq.pop(0)), \
|
|
mock.patch.object(cm, 'session_state', lambda: None), \
|
|
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, 'session_state', lambda: None), \
|
|
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, 'session_state', lambda: None), \
|
|
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 NoRealReportPollutionTest(unittest.TestCase):
|
|
"""测试不许往真实报告目录里写东西。
|
|
|
|
⛔ 实测: EnkephalinGateTest 调 main() 时没指 --report-dir, 于是往
|
|
~/lc_mcp/modules/convert_*.json 里写了一批 elapsed_s=0 的假记录
|
|
(内容是"读不到体力读数"), 一共 7 条。值守看报告时会以为真出过这些事。
|
|
日志那边已经用 QuietLogMixin 堵住了, 报告这边靠这条 AST 检查兜住。
|
|
"""
|
|
|
|
def test_every_main_call_passes_report_dir(self):
|
|
import ast
|
|
src = Path(__file__).read_text(encoding='utf-8')
|
|
tree = ast.parse(src)
|
|
offenders = []
|
|
for node in ast.walk(tree):
|
|
if not isinstance(node, ast.Call):
|
|
continue
|
|
f = node.func
|
|
if (getattr(f, 'attr', None) != 'main' or
|
|
getattr(getattr(f, 'value', None), 'id', None) != 'cm'):
|
|
continue
|
|
flat = ast.dump(node)
|
|
if 'report-dir' not in flat:
|
|
offenders.append('line %d' % node.lineno)
|
|
self.assertFalse(offenders,
|
|
'cm.main() 没带 --report-dir, 会写进真实报告目录: '
|
|
+ ', '.join(offenders))
|
|
|
|
|
|
class CliRoutingTest(QuietLogMixin, unittest.TestCase):
|
|
"""命令行参数的路由 —— main() 改了很多轮, 参数别在改动里被弄丢。
|
|
|
|
--report-dir 由 EnkephalinGateTest 间接覆盖(它每次都传), 这里补 --keep-game。
|
|
"""
|
|
|
|
def _main(self, argv):
|
|
closed = []
|
|
done = []
|
|
tmp = tempfile.mkdtemp()
|
|
self.addCleanup(shutil.rmtree, tmp, True)
|
|
with mock.patch.object(cm, 'read_enkephalin', lambda: 4), \
|
|
mock.patch.object(cm, 'read_lunacy', lambda **k: 9699), \
|
|
mock.patch.object(cm, 'ensure_server', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_display', lambda *a: True), \
|
|
mock.patch.object(cm, 'launch_game', lambda *a: True), \
|
|
mock.patch.object(cm, 'wait_main_menu', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_window_size', lambda *a: (1600, 900)), \
|
|
mock.patch.object(cm, 'close_panel', lambda: True), \
|
|
mock.patch.object(cm, 'close_game', lambda: closed.append(1)), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None):
|
|
code = cm.main(argv + ['--report-dir', tmp])
|
|
done.append(os.listdir(tmp))
|
|
return code, closed, done[0]
|
|
|
|
def test_default_closes_the_game(self):
|
|
code, closed, reports = self._main([])
|
|
self.assertEqual(code, 0)
|
|
self.assertEqual(len(closed), 1, '默认应该把游戏关掉')
|
|
|
|
def test_keep_game_skips_closing(self):
|
|
code, closed, reports = self._main(['--keep-game'])
|
|
self.assertEqual(code, 0)
|
|
self.assertEqual(closed, [], '--keep-game 时不该关游戏')
|
|
|
|
def test_a_skipped_run_does_not_reuse_previous_lunacy_result(self):
|
|
cm._result.update(lunacy_after=9699, lunacy_checked=True, converted=True)
|
|
code, _, _ = self._main([]) # 体力不足, 不合成也不做后读。
|
|
self.assertEqual(code, 0)
|
|
self.assertNotIn('lunacy_after', cm._result)
|
|
self.assertNotIn('lunacy_checked', cm._result)
|
|
self.assertFalse(cm._result['converted'])
|
|
|
|
def test_report_is_written_with_the_expected_fields(self):
|
|
"""报告字段要齐全 —— 值守就靠 lunacy_* 和 converted 那几项下结论。"""
|
|
import json
|
|
closed = []
|
|
tmp = tempfile.mkdtemp()
|
|
self.addCleanup(shutil.rmtree, tmp, True)
|
|
with mock.patch.object(cm, 'read_enkephalin', lambda: 25), \
|
|
mock.patch.object(cm, 'read_lunacy', lambda **k: 9699), \
|
|
mock.patch.object(cm, 'ensure_server', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_display', lambda *a: True), \
|
|
mock.patch.object(cm, 'launch_game', lambda *a: True), \
|
|
mock.patch.object(cm, 'wait_main_menu', lambda *a: True), \
|
|
mock.patch.object(cm, 'ensure_window_size', lambda *a: (1600, 900)), \
|
|
mock.patch.object(cm, 'close_panel', lambda: True), \
|
|
mock.patch.object(cm, 'close_game', lambda: closed.append(1)), \
|
|
mock.patch.object(cm, 'convert_once',
|
|
lambda tries=2: (True, '模组 1 -> 2 (+1)', 1)), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None):
|
|
cm.main(['--report-dir', tmp])
|
|
name = os.listdir(tmp)[0]
|
|
self.assertRegex(name, r'^convert_\d{8}_\d{6}\.json$')
|
|
with open(os.path.join(tmp, name), encoding='utf-8') as fh:
|
|
r = json.load(fh)
|
|
for k in ('started', 'result', 'ok', 'elapsed_s', 'steps',
|
|
'lunacy_before', 'lunacy_after', 'lunacy_checked', 'converted'):
|
|
self.assertIn(k, r, '报告缺字段 %s' % k)
|
|
self.assertTrue(r['converted'])
|
|
self.assertTrue(r['lunacy_checked'])
|
|
|
|
def test_start_timeout_is_accepted(self):
|
|
code, closed, reports = self._main(['--start-timeout', '60'])
|
|
self.assertEqual(code, 0)
|
|
|
|
|
|
class SessionTableTest(QuietLogMixin, unittest.TestCase):
|
|
"""解析 `query session` —— 用来区分"截不到图"到底是哪种情况。
|
|
|
|
两段输入都是**实测原样**(2026-10-17)。注意成功时返回码也是 1, 所以只能看输出。
|
|
|
|
⛔ 必须继承 QuietLogMixin: 这里会调 ensure_display(), 它一 log 就写进真实的
|
|
convert.log —— 又一次让值守日志里出现"看着像真出事"的行(这是第三次了)。
|
|
"""
|
|
|
|
# 用户从 RDP 连进来: console 画面是空的 -> BitBlt 失败, 看门狗按设计不会动
|
|
RDP_IN = (
|
|
' SESSIONNAME USERNAME ID STATE TYPE DEVICE \n'
|
|
' services 0 Disc \n'
|
|
'>rdp-tcp#70 YWS-HHH 1 Active \n'
|
|
' console 3 Conn \n'
|
|
' 31c5ce94259d4... 65536 Listen \n'
|
|
' rdp-tcp 65537 Listen \n')
|
|
|
|
# 已挂回 console: 显示正常
|
|
CONSOLE = (
|
|
' SESSIONNAME USERNAME ID STATE TYPE DEVICE \n'
|
|
' services 0 Disc \n'
|
|
'>console YWS-HHH 1 Active \n'
|
|
' 31c5ce94259d4... 65536 Listen \n'
|
|
' rdp-tcp 65537 Listen \n')
|
|
|
|
def test_detects_active_rdp(self):
|
|
st = cm.parse_session_table(self.RDP_IN)
|
|
self.assertEqual(st['rdp_active'], 'rdp-tcp#70')
|
|
self.assertEqual(st['console'], '3')
|
|
self.assertEqual(st['current'], 'rdp-tcp#70')
|
|
|
|
def test_console_only_has_no_active_rdp(self):
|
|
st = cm.parse_session_table(self.CONSOLE)
|
|
self.assertIsNone(st['rdp_active'], '没有 RDP 会话时不该报有')
|
|
self.assertEqual(st['console'], '1')
|
|
self.assertEqual(st['current'], 'console')
|
|
|
|
def test_empty_or_garbage_is_safe(self):
|
|
for text in ('', 'garbage\n', 'only one\n'):
|
|
st = cm.parse_session_table(text)
|
|
self.assertIsNone(st['rdp_active'])
|
|
|
|
def test_non_text_output_is_tolerated(self):
|
|
"""query session 万一没给出文本, 也不能把整轮炸掉 —— 那只是诊断信息。"""
|
|
with mock.patch.object(cm.subprocess, 'run',
|
|
lambda *a, **k: mock.Mock(stdout=object())):
|
|
self.assertIsNone(cm.session_state())
|
|
|
|
def test_display_refuses_to_fight_an_active_rdp(self):
|
|
"""RDP Active 时不能去跑看门狗(它不会动), 也不能硬踢人家下线。"""
|
|
ran = []
|
|
with mock.patch.object(cm, 'render_ok', lambda: False), \
|
|
mock.patch.object(cm, 'session_state',
|
|
lambda: {'current': 'rdp-tcp#70',
|
|
'rdp_active': 'rdp-tcp#70',
|
|
'console': '3'}), \
|
|
mock.patch.object(cm.subprocess, 'run',
|
|
lambda *a, **k: ran.append(a)):
|
|
self.assertFalse(cm.ensure_display(timeout_s=1))
|
|
self.assertEqual(ran, [], '不该去跑看门狗, 更不该踢人下线')
|
|
|
|
|
|
class LaunchGameRetryTest(QuietLogMixin, unittest.TestCase):
|
|
"""⛔ 2026-10-17 02:03 实测: exe 起来就退了。
|
|
|
|
Steam 的 content_log 里 02:0x 毫无记录(上一轮 22:03:43 还有 "App Running"),
|
|
应用事件日志也没报错, 游戏进程始终没出现; 而 13 分钟后手动启动 5 秒就起来了。
|
|
原来"点一次火干等 240 秒"的写法碰上一次静默失败就白丢一整轮。
|
|
|
|
这里的时钟是假的 —— sleep 打桩成空函数后墙钟几乎不走, 内层循环会狂转,
|
|
不控时钟就测不出"一次尝试等满 40 秒"这件事。
|
|
"""
|
|
|
|
class FakeTime:
|
|
def __init__(self):
|
|
self.t = 1000.0
|
|
|
|
def time(self):
|
|
return self.t
|
|
|
|
def sleep(self, s):
|
|
self.t += s
|
|
|
|
def _run(self, appear_after_call, tries=3, each=40):
|
|
"""appear_after_call: 第几次 game_running 调用开始返回 True(None=永不)。"""
|
|
clock = self.FakeTime()
|
|
calls = {'n': 0}
|
|
pops = []
|
|
|
|
def running():
|
|
calls['n'] += 1
|
|
return appear_after_call is not None and calls['n'] >= appear_after_call
|
|
|
|
with mock.patch.object(cm, 'game_running', running), \
|
|
mock.patch.object(cm, '_popen_psutil', lambda n: []), \
|
|
mock.patch.object(cm.subprocess, 'Popen',
|
|
lambda *a, **k: pops.append(a)), \
|
|
mock.patch.object(cm.time, 'time', clock.time), \
|
|
mock.patch.object(cm.time, 'sleep', clock.sleep):
|
|
ok = cm.launch_game(timeout_s=tries * each, tries=tries)
|
|
return ok, len(pops), clock.t
|
|
|
|
def test_first_attempt_success_is_enough(self):
|
|
# 第 1 次调用是进入函数时的"已经在运行吗"检查(返回 False),
|
|
# 之后循环里的调用才代表"点火后进程出现了" —— 所以用 3。
|
|
ok, pops, _ = self._run(appear_after_call=3)
|
|
self.assertTrue(ok)
|
|
self.assertEqual(pops, 1, '第一次就成功, 不该重复点火')
|
|
|
|
def test_silent_failure_is_retried_and_can_recover(self):
|
|
"""第一次点火后进程没出现 -> 必须再试, 第二次才出现。"""
|
|
ok, pops, _ = self._run(appear_after_call=None if False else 10)
|
|
self.assertTrue(ok, '重试之后应该成功')
|
|
self.assertGreater(pops, 1, '进程没出现时应该重新点火')
|
|
|
|
def test_already_running_never_launches(self):
|
|
# 第 1 次检查就为真 -> 直接返回, 不点火
|
|
ok, pops, _ = self._run(appear_after_call=1)
|
|
self.assertTrue(ok)
|
|
self.assertEqual(pops, 0, '已经在运行就不该点火')
|
|
|
|
def test_gives_up_after_all_tries(self):
|
|
ok, pops, _ = self._run(appear_after_call=None)
|
|
self.assertFalse(ok)
|
|
self.assertEqual(pops, 3, '试满 3 次就放弃')
|
|
|
|
def test_each_attempt_waits_its_share(self):
|
|
"""总等待要摊到每次尝试上, 不能把 240 秒全花在第一次。"""
|
|
ok, pops, elapsed = self._run(appear_after_call=None, tries=3, each=40)
|
|
self.assertAlmostEqual(elapsed - 1000.0, 120.0, delta=1.0,
|
|
msg='3 次 x 40 秒 = 120 秒总等待')
|
|
|
|
def test_already_running_does_not_relaunch(self):
|
|
with mock.patch.object(cm, 'game_running', lambda: True), \
|
|
mock.patch.object(cm, '_popen_psutil', lambda n: []), \
|
|
mock.patch.object(cm.subprocess, 'Popen',
|
|
lambda *a, **k: self.fail('已在运行还去点火')):
|
|
self.assertTrue(cm.launch_game())
|
|
|
|
|
|
class OnModulesTabTest(QuietLogMixin, unittest.TestCase):
|
|
"""确认停在免费合成页签 —— 判错的代价是整轮拒绝合成。
|
|
|
|
⛔ 2026-10-16 18:03 真出过事: 原来只看"兑换区显示体力条 x/126", 而 OCR 会把相邻
|
|
几行合并成一个元素(那次 "Enkephalin Module Owned 31" 的框高 38、宽 351, 把下面
|
|
的 x/126 一起吞了), 判定失败 -> 拒绝合成 -> 那轮一个模块没换到。
|
|
|
|
下面的元素是那次面板上**真实的 OCR 输出**, 不是我编的。
|
|
"""
|
|
|
|
# 18:03 那轮真实 dump(体力条被合并吞掉, 但问句完整成行)
|
|
REAL_FAILED_DUMP = [
|
|
{'text': 'Modules', 'x': 589, 'y': 269, 'w': 85, 'h': 27},
|
|
{'text': 'Use Lunacy', 'x': 749, 'y': 269, 'w': 101, 'h': 25},
|
|
{'text': 'Use Boxes', 'x': 921, 'y': 271, 'w': 100, 'h': 24},
|
|
{'text': 'Enkephalin Module Owned 31', 'x': 681, 'y': 331, 'w': 351, 'h': 38},
|
|
{'text': '1 Enkephalin recovered inD2:50', 'x': 658, 'y': 462, 'w': 278, 'h': 26},
|
|
{'text': 'Would you like to assemble Enkephalin Modules?',
|
|
'x': 564, 'y': 598, 'w': 472, 'h': 27},
|
|
{'text': 'X Cancel', 'x': 593, 'y': 652, 'w': 118, 'h': 31},
|
|
{'text': 'Confirm', 'x': 926, 'y': 653, 'w': 92, 'h': 30},
|
|
]
|
|
|
|
def _items(self, items):
|
|
return mock.patch.object(cm, 'items', lambda: items)
|
|
|
|
def test_recognises_the_frame_that_used_to_fail(self):
|
|
with self._items(self.REAL_FAILED_DUMP):
|
|
self.assertTrue(cm.on_modules_tab(),
|
|
'这批元素曾让判定失败, 现在必须认得出来')
|
|
|
|
def test_question_phrase_alone_is_enough(self):
|
|
with self._items([{'text': 'Would you like to assemble Enkephalin Modules?',
|
|
'x': 564, 'y': 598, 'w': 472, 'h': 27}]):
|
|
self.assertTrue(cm.on_modules_tab())
|
|
|
|
def test_question_phrase_survives_ocr_space_noise(self):
|
|
# OCR 常在词间丢空格/加空格
|
|
with self._items([{'text': 'WouldyouliketoassembleEnkephalinModules?',
|
|
'x': 564, 'y': 598, 'w': 472, 'h': 27}]):
|
|
self.assertTrue(cm.on_modules_tab())
|
|
|
|
def test_gauge_is_still_a_valid_fallback(self):
|
|
with self._items([{'text': '132/26112/126', 'x': 709, 'y': 508,
|
|
'w': 200, 'h': 30}]):
|
|
self.assertTrue(cm.on_modules_tab())
|
|
|
|
def test_unknown_screen_is_refused(self):
|
|
"""两条信号都没有时必须拒绝 —— 宁可漏一轮, 也不在不知道哪个页签上点确认。"""
|
|
with self._items([{'text': 'Window', 'x': 994, 'y': 809},
|
|
{'text': 'Inventory', 'x': 759, 'y': 834}]):
|
|
self.assertFalse(cm.on_modules_tab())
|
|
|
|
def test_tab_labels_alone_are_not_enough(self):
|
|
"""只有三个页签名(面板刚开、还没点页签)时不能算数。
|
|
|
|
页签名一直显示, 分不出当前选中哪个, 所以不能当依据。
|
|
"""
|
|
with self._items([{'text': 'Modules', 'x': 589, 'y': 269},
|
|
{'text': 'Use Lunacy', 'x': 749, 'y': 269},
|
|
{'text': 'Use Boxes', 'x': 921, 'y': 271}]):
|
|
self.assertFalse(cm.on_modules_tab())
|
|
|
|
def test_refusal_prevents_clicking_confirm(self):
|
|
"""面板开着但认不出页签时, 绝不点确认。
|
|
|
|
夹具要含面板标记(Charge Enkephalin), 否则走的是"打不开面板"那条更早的路径,
|
|
测不到这里真正想守的东西。
|
|
"""
|
|
clicked = []
|
|
panel_but_no_tab_info = [
|
|
{'text': 'Charge Enkephalin', 'x': 700, 'y': 180, 'w': 200, 'h': 30},
|
|
{'text': 'Modules', 'x': 589, 'y': 269, 'w': 85, 'h': 27},
|
|
{'text': 'Use Lunacy', 'x': 749, 'y': 269, 'w': 101, 'h': 25},
|
|
{'text': 'Confirm', 'x': 926, 'y': 653, 'w': 92, 'h': 30},
|
|
]
|
|
with self._items(panel_but_no_tab_info), \
|
|
mock.patch.object(cm, 'click', lambda *a: clicked.append(a)), \
|
|
mock.patch.object(cm, 'read_owned', lambda: 31), \
|
|
mock.patch.object(cm.time, 'sleep', lambda s: None):
|
|
ok, info, got = cm._convert_attempt()
|
|
self.assertFalse(ok)
|
|
self.assertEqual(got, 0)
|
|
self.assertIn('页签', info, '应该报"认不出页签", 实际: %s' % info)
|
|
self.assertFalse(any(cm.BTN_CONFIRM == tuple(a) for a in clicked),
|
|
'判不出页签还点了确认: %s' % clicked)
|
|
|
|
|
|
class SafeClickTargetsTest(QuietLogMixin, unittest.TestCase):
|
|
"""脚本能点到的地方必须逐个安全 —— 用户的两条硬约束就靠这几个坐标。
|
|
|
|
整个脚本只有 7 处输入调用(其余全在合成面板内部或底栏模组图标上), 所以这个
|
|
审查面很小, 值得把它钉死: 任何新增的裸坐标点击都要有明确的理由。
|
|
"""
|
|
|
|
SAFE_LITERALS = {
|
|
(800, 450): '屏幕中央, 推进标题/剧情/公告 —— 任何界面上都无害',
|
|
(656, 670): 'BTN_CANCEL, 只关面板',
|
|
}
|
|
|
|
def _calls(self):
|
|
import ast
|
|
src = (Path(__file__).resolve().parents[1] / 'scripts' / 'convert_modules.py') \
|
|
.read_text(encoding='utf-8')
|
|
out = []
|
|
for node in ast.walk(ast.parse(src)):
|
|
if isinstance(node, ast.Call):
|
|
name = getattr(node.func, 'id', None) or getattr(node.func, 'attr', None)
|
|
if name in ('click', 'long_press'):
|
|
out.append(node)
|
|
return out
|
|
|
|
def test_literal_click_coordinates_are_whitelisted(self):
|
|
import ast
|
|
bad = []
|
|
for node in self._calls():
|
|
if len(node.args) != 2:
|
|
continue # click(*CONST) 形式, 由常量保证
|
|
vals = []
|
|
for a in node.args:
|
|
if isinstance(a, ast.Constant) and isinstance(a.value, int):
|
|
vals.append(a.value)
|
|
else:
|
|
vals = None
|
|
break
|
|
if not vals:
|
|
continue
|
|
if tuple(vals) not in self.SAFE_LITERALS:
|
|
bad.append('line %d: click(%d, %d)' % (node.lineno, *vals))
|
|
self.assertFalse(bad,
|
|
'出现了未经审查的裸坐标点击, 请先确认它不会误触:\n '
|
|
+ '\n '.join(bad))
|
|
|
|
def test_advance_click_is_not_on_the_bottom_bar(self):
|
|
"""推进用的点击不能落在底栏 —— 那里有 Inventory 等按钮。
|
|
|
|
⛔ 曾经用 (800,830), 而 Inventory 按钮实测是 @(759,834) w=91(跨度 759~850),
|
|
正好把它包住。画面恰在检查与点击之间切到主界面时就会误触。
|
|
"""
|
|
import ast
|
|
for node in self._calls():
|
|
if len(node.args) != 2:
|
|
continue
|
|
try:
|
|
x = node.args[0].value
|
|
y = node.args[1].value
|
|
except AttributeError:
|
|
continue
|
|
self.assertLess(y, 780,
|
|
'line %d 的点击在 y=%d, 落在底栏区(>=780)' % (node.lineno, y))
|
|
|
|
|
|
class NoDeadConstantsTest(unittest.TestCase):
|
|
"""顶层的全大写常量必须真的被用到。
|
|
|
|
删过一个 TAB_USE_BOXES(界面上的第三个页签, 本项目不用) —— 它从来没被引用过。
|
|
留着它的坏处不是占地方, 而是**会让人以为某条代码路径处理了它**。
|
|
死代码比没有更糟, 这条测试把口子堵上。
|
|
|
|
统计范围包含测试文件: 有些常量(比如 USE_LUNACY_TAB)只被测试引用, 那是有意的
|
|
—— 它的存在就是为了让"绝不许点"这件事有个可断言的锚点。
|
|
"""
|
|
|
|
def test_every_module_level_constant_is_referenced(self):
|
|
import ast
|
|
root = Path(__file__).resolve().parents[1]
|
|
src = (root / 'scripts' / 'convert_modules.py').read_text(encoding='utf-8')
|
|
tree = ast.parse(src)
|
|
|
|
names = []
|
|
for node in tree.body:
|
|
if isinstance(node, ast.Assign):
|
|
for t in node.targets:
|
|
if isinstance(t, ast.Name) and t.id.isupper():
|
|
names.append(t.id)
|
|
|
|
others = ((root / 'scripts' / 'convert_modules.py').read_text(encoding='utf-8'),
|
|
(root / 'tests' / 'test_convert_modules.py').read_text(encoding='utf-8'))
|
|
dead = []
|
|
for n in names:
|
|
uses = 0
|
|
for text in others:
|
|
for line in text.splitlines():
|
|
s = line.strip()
|
|
if s.startswith(n + ' =') or s.startswith(n + '='):
|
|
continue # 定义行本身不算
|
|
if n in line:
|
|
uses += 1
|
|
if uses == 0:
|
|
dead.append(n)
|
|
self.assertFalse(dead, '这些常量从没被引用过, 请删掉或说明理由: ' + ', '.join(dead))
|
|
|
|
|
|
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):
|
|
"""万一布局变了, 这条会提醒重新量坐标, 而不是让上面那条静静地失效。
|
|
|
|
只锁"我们会点的那个"和"绝不能点的那个"。Use Boxes 的坐标只写在源码注释里
|
|
—— 本项目不用它, 所以不定义常量(定义了却没人用, 会让人以为某条路径处理了它)。
|
|
"""
|
|
self.assertEqual(cm.USE_LUNACY_TAB, (797, 283))
|
|
self.assertLess(cm.TAB_MODULES[0], cm.USE_LUNACY_TAB[0]) # Modules 在左
|
|
self.assertAlmostEqual(cm.TAB_MODULES[1], cm.USE_LUNACY_TAB[1], delta=5)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|