- 返回按钮(I-15): V1.6.2 在首次引导页拿 click_element 的返回值当坐标再点, 它返回 True → TypeError, 镜牢任务退出。install_back_button_result 只在 `x := auto.click_element(返回)` 这种调用时只找不点, 由上游点一次; 只看真假的调用照常点; 上游源码里没有这种写法就不装 - 事件兜底(I-16): LCP_EVENT_FALLBACK=1 时每轮都抢先点第 1 项, 上游走不到判定/继续/开始战斗; runs 里 1014 条 fallback_first, 73 段同屏连点 10~11 次, 最长 110 次。改成每屏只点一次、与按表共用 5 次上限 - 事件点击点只在这一项自己那行 OCR 字里取(原来整屏找子串, 叙述或别的选项是它的子串时会点错) - 截图熔断(I-17): 只在任务主线程计数和中止(retry_monitor 线程里抛只会打死那条线程, 两次熔断都记了两条); 要求连续出错满 30 秒、至少 20 次, 一闪而过的坏帧不再停掉任务 - 卡包: 优选阈值默认 1 与注释/提交说明/实机一致(LCP_THEME_PACK_THRESHOLD=0 不动上游); 「刷新」OCR 范围按 set_win_size/1440 缩放 - .gitignore 放行 docs/feedback/runs/**/logs/*.log(INDEX 说的过滤日志此前被 *.log 挡掉, 没进仓库) - README 补 LCP_EVENT_FALLBACK / LCP_THEME_PACK_THRESHOLD; BACKLOG 记 V1.6.2 影响; ISSUES 加 I-15~I-17 单测: 769 passed(新增上游真实 select_battle_team 端到端: 不装补丁 TypeError, 装了点一次)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
455 lines
22 KiB
Python
455 lines
22 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""镜牢事件按选项表选择(BACKLOG P1-4)。
|
|
|
|
2026-11-14 核对: Mirror.event_handling() 不认事件, 有 "???"/直接拿饰品/优势判定就选它, 否则点第一个选项。
|
|
补丁在上游每轮挑选项前按选项原文认事件、按表点; 端到端用例执行上游真实的 event_handling
|
|
(以及小指良单通模式用的 click_option_avoiding_unknown)。
|
|
"""
|
|
import ast
|
|
import functools
|
|
import json
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import types
|
|
import unittest
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest import mock
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(REPO))
|
|
from lc_mcp import aalc_patches as ap # noqa: E402
|
|
|
|
MIRROR = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'mirror.py'
|
|
EVENT = REPO / 'vendor' / 'aalc' / 'tasks' / 'event' / 'event_handling.py'
|
|
SCALE = 720 / 1440
|
|
MARKER_X = 699 # 选项框左边缘(1280x720, 由 2560 模板换算)
|
|
ROW_GAP = 60
|
|
|
|
SHEEP = ['你是特别的。', '你不是特别的。']
|
|
CHICKEN = ['鸡肉就是鸡肉喽。', '绝对是鸡腿,满满的汁液。', '鸡胸,肯定的,纯净无瑕。']
|
|
STATUE = ['侧耳倾听。', '摘下黄铜戒指。', '放上钱币。']
|
|
|
|
|
|
def markers(count):
|
|
return [(MARKER_X, 200 + ROW_GAP * i) for i in range(count)]
|
|
|
|
|
|
def rule(name='e', options=('别的选项',), text='要点的'):
|
|
return {'name': name, 'id': None, 'options': tuple(options), 'text': text}
|
|
|
|
|
|
def upstream_function(path, name, cls=None):
|
|
tree = ast.parse(path.read_text(encoding='utf-8'))
|
|
body = tree.body
|
|
if cls:
|
|
body = next(n for n in body if isinstance(n, ast.ClassDef) and n.name == cls).body
|
|
return next(n for n in body if isinstance(n, ast.FunctionDef) and n.name == name)
|
|
|
|
|
|
class NormalizeEventTextTest(unittest.TestCase):
|
|
|
|
def test_punctuation_width_and_spaces_are_ignored(self):
|
|
self.assertEqual(ap.normalize_event_text('鸡胸,肯定的, 纯净 无瑕。'), '鸡胸肯定的纯净无瑕')
|
|
self.assertEqual(ap.normalize_event_text('“我不特别吗?”'), '我不特别吗')
|
|
self.assertEqual(ap.normalize_event_text('施加震颐'), '施加震颤')
|
|
|
|
|
|
class EventOptionsTest(unittest.TestCase):
|
|
|
|
def test_lines_attach_to_the_nearest_option_on_the_right(self):
|
|
lines = [('你是特别的', 900, 200),
|
|
('你不是', 900, 255), ('特别的。', 1000, 265), # 一项换成两行
|
|
('离开', 900, 322),
|
|
('侧耳倾听', 300, 260), # 左边的叙述文字不算选项
|
|
('梦中的电子羊', 200, 60)] # 标题
|
|
options = ap.event_options(list(reversed(markers(3))), lines, SCALE)
|
|
self.assertEqual([text for _, text in options], ['你是特别的', '你不是特别的', '离开'])
|
|
self.assertEqual([pos for pos, _ in options], markers(3))
|
|
|
|
def test_text_far_below_the_last_option_is_ignored(self):
|
|
options = ap.event_options(markers(1), [('继续', 900, 200 + 31)], SCALE)
|
|
self.assertEqual(options[0][1], '')
|
|
|
|
def test_click_point_is_the_longest_line_of_that_option(self):
|
|
lines = [('离开', 900, 200), ('不听故事', 900, 255), ('就这样离开', 1000, 265)]
|
|
rows = ap.option_rows(markers(2), lines, SCALE)
|
|
# 第 2 项「不听故事就这样离开」: 不会因为「离开」是它的子串去点第 1 项
|
|
self.assertEqual(ap.option_click_pos(*rows[1]), (1000.0, 265.0))
|
|
self.assertEqual(ap.option_click_pos(*rows[0]), (900.0, 200.0))
|
|
|
|
def test_click_point_falls_back_to_the_marker(self):
|
|
rows = ap.option_rows(markers(1), [], SCALE)
|
|
self.assertEqual(ap.option_click_pos(*rows[0]), (float(MARKER_X), 200.0))
|
|
|
|
|
|
class ChooseEventOptionTest(unittest.TestCase):
|
|
|
|
def test_event_is_recognised_by_its_other_options(self):
|
|
rules = [rule('羊', ['你是特别的'], '你不是特别的')]
|
|
self.assertEqual(ap.choose_event_option(rules, ('你是特别的', '你不是特别的')), (rules[0], 1))
|
|
self.assertEqual(ap.choose_event_option(rules, ('你不是特别的', '离开')), (None, None))
|
|
|
|
def test_all_listed_options_must_be_on_screen(self):
|
|
rules = [rule('鸡', ['绝对是鸡腿', '鸡胸肯定的'], '鸡肉就是鸡肉喽')]
|
|
self.assertEqual(ap.choose_event_option(rules, ('鸡肉就是鸡肉喽', '绝对是鸡腿满满的汁液')), (None, None))
|
|
|
|
def test_recognised_but_target_not_read(self):
|
|
rules = [rule('鸡', ['绝对是鸡腿'], '鸡肉就是鸡肉喽')]
|
|
self.assertEqual(ap.choose_event_option(rules, ('鸡肉就是鸡', '绝对是鸡腿')), (rules[0], None))
|
|
|
|
def test_first_matching_rule_wins(self):
|
|
rules = [rule('a', ['离开'], '战斗'), rule('b', ['离开'], '交谈')]
|
|
self.assertEqual(ap.choose_event_option(rules, ('交谈', '战斗', '离开')), (rules[0], 1))
|
|
|
|
|
|
class EventTableTest(unittest.TestCase):
|
|
|
|
def test_shipped_table_is_valid(self):
|
|
rules = ap.load_event_choices()
|
|
self.assertGreaterEqual(len(rules), 5)
|
|
for r in rules:
|
|
with self.subTest(event=r['name']):
|
|
self.assertIsInstance(r['id'], int) # 零协汉化 ActionEvents 的事件 id, 方便回查
|
|
|
|
def test_shipped_events_come_from_the_event_reference(self):
|
|
reference = (REPO / 'docs/skills/limbus-mirror-speedrun/references/event-choices.md').read_text(encoding='utf-8')
|
|
for r in ap.load_event_choices():
|
|
with self.subTest(event=r['name']):
|
|
self.assertIn(r['name'].split('(')[0], reference)
|
|
|
|
def test_each_shipped_event_picks_its_own_option(self):
|
|
rules = ap.load_event_choices()
|
|
for r in rules:
|
|
with self.subTest(event=r['name']):
|
|
screen = (r['text'],) + r['options']
|
|
self.assertEqual(ap.choose_event_option(rules, screen), (r, 0))
|
|
|
|
def test_bad_tables_raise_value_error(self):
|
|
bad = ['[]', '{"events": {}}', '{"events": [1]}',
|
|
'{"events": [{"name": "a", "options": ["x"]}]}',
|
|
'{"events": [{"name": "a", "options": [], "text": "y"}]}',
|
|
'{"events": [{"name": "a", "options": "x", "text": "y"}]}',
|
|
'{"events": [{"name": "a", "options": ["x"], "text": ["y"]}]}',
|
|
'{"events": [{"name": "a", "options": ["。"], "text": "y"}]}',
|
|
'{"events": [{"name": "a", "options": ["离开"], "text": "离开。"}]}',
|
|
'{"events": [{"name": "a", "match": ["x"], "index": 2}]}']
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, 'e.json')
|
|
for content in bad:
|
|
with self.subTest(content=content):
|
|
with open(path, 'w', encoding='utf-8') as f:
|
|
f.write(content)
|
|
with self.assertRaises(ValueError):
|
|
ap.load_event_choices(path)
|
|
|
|
|
|
class EventScreen:
|
|
"""事件界面: 依次几屏选项, 点了一项就进下一屏, 最后回到地图。unknown 是带 "???" 标签的那一项。"""
|
|
|
|
def __init__(self, screens, unknown=None, ignore_clicks=0):
|
|
self.screens = [list(s) for s in screens]
|
|
self.unknown = unknown
|
|
self.stage = 0
|
|
self.ignore_clicks = ignore_clicks
|
|
self.chosen = []
|
|
self.model = None
|
|
self.screenshot = object()
|
|
self.ocr_runs = 0
|
|
|
|
@property
|
|
def options(self):
|
|
return self.screens[self.stage] if self.stage < len(self.screens) else None
|
|
|
|
def take_screenshot(self, *args, **kwargs):
|
|
self.screenshot = object() # 每次截图都是新对象, 与 AALC 一致
|
|
return self.screenshot
|
|
|
|
def mouse_to_blank(self, *args, **kwargs):
|
|
pass
|
|
|
|
def find_element(self, target, find_type='image', threshold=0.8, **kwargs):
|
|
options = self.options
|
|
if target == 'mirror/road_in_mir/legend_assets.png':
|
|
return options is None
|
|
if target == ap.EVENT_OPTION and options:
|
|
return markers(len(options)) if find_type == 'image_with_multiple_targets' else markers(1)[0]
|
|
if target == ap.EVENT_HOOK and options and self.stage == 0 and self.unknown is not None:
|
|
x, y = markers(len(options))[self.unknown]
|
|
return (x + 300, y + 20) # 标签画在所属选项框里面, 比左边缘靠下
|
|
if target == 'event/choices_assets.png':
|
|
return bool(options)
|
|
return [] if find_type == 'image_with_multiple_targets' else False
|
|
|
|
def click_element(self, target, **kwargs):
|
|
if target == ap.EVENT_OPTION and self.options:
|
|
self.mouse_click(*markers(1)[0])
|
|
return True
|
|
return False
|
|
|
|
def mouse_click(self, x, y, *args, **kwargs):
|
|
if not self.options:
|
|
return
|
|
rows = markers(len(self.options))
|
|
above = [i for i, (_, my) in enumerate(rows) if my <= y]
|
|
self.chosen.append(max(above) if above else 0)
|
|
if self.ignore_clicks:
|
|
self.ignore_clicks -= 1
|
|
return
|
|
self.stage += 1
|
|
|
|
def find_language_text(self, *args, **kwargs):
|
|
return False
|
|
|
|
def find_text_element(self, *args, **kwargs):
|
|
return False
|
|
|
|
def run(self, image):
|
|
self.ocr_runs += 1
|
|
lines = [('事件叙述文字', 200, 60)] + list(getattr(self, 'narration', ()))
|
|
for (x, y), text in zip(markers(len(self.options or ())), self.options or ()):
|
|
lines.append((text, x + 200, y))
|
|
return SimpleNamespace(txts=tuple(t for t, _, _ in lines),
|
|
boxes=[[[x - 10, y - 5], [x + 10, y - 5], [x + 10, y + 5], [x - 10, y + 5]]
|
|
for _, x, y in lines])
|
|
|
|
|
|
class StickyEventScreen(EventScreen):
|
|
"""点了选项后选项框还留在画面上, 要上游点「继续」才进下一屏(实机表外事件就是这样)。"""
|
|
|
|
def __init__(self, screens):
|
|
super().__init__(screens)
|
|
self.picked = False
|
|
self.continues = 0
|
|
self.clicks = 0
|
|
|
|
def mouse_click(self, x, y, *args, **kwargs):
|
|
if not self.options:
|
|
return
|
|
self.clicks += 1
|
|
if self.clicks > 50:
|
|
raise RuntimeError('同一屏点了 50 次还没走完事件')
|
|
if not self.picked:
|
|
rows = markers(len(self.options))
|
|
above = [i for i, (_, my) in enumerate(rows) if my <= y]
|
|
self.chosen.append(max(above) if above else 0)
|
|
self.picked = True
|
|
|
|
def click_element(self, target, **kwargs):
|
|
if target == 'event/continue_assets.png' and self.options and self.picked:
|
|
self.continues += 1
|
|
self.picked = False
|
|
self.stage += 1
|
|
return True
|
|
return super().click_element(target, **kwargs)
|
|
|
|
|
|
@unittest.skipUnless(MIRROR.is_file() and EVENT.is_file(), 'vendor/aalc 子模块未检出')
|
|
class UpstreamEventHandlingTest(unittest.TestCase):
|
|
"""执行上游真实的 Mirror.event_handling, 看每屏点了第几项。"""
|
|
|
|
def setUp(self):
|
|
self.lines = []
|
|
self.fn_node = upstream_function(MIRROR, 'event_handling', cls='Mirror')
|
|
self.avoid_node = upstream_function(EVENT, 'click_option_avoiding_unknown', cls='EventHandling')
|
|
|
|
def play(self, screens, patched=True, env=None, unknown=None, solo=False, ignore_clicks=0, screen=None):
|
|
if screen is None:
|
|
screen = EventScreen(screens, unknown=unknown, ignore_clicks=ignore_clicks)
|
|
cfg = SimpleNamespace(set_win_size=720)
|
|
avoid_ns = dict(auto=screen, log=mock.Mock())
|
|
exec(compile(ast.Module(body=[self.avoid_node], type_ignores=[]), str(EVENT), 'exec'), avoid_ns)
|
|
ns = dict(auto=screen, retry=lambda: True, log=mock.Mock(), time=time, back_init_menu=mock.Mock(),
|
|
ImageUtils=SimpleNamespace(get_bbox=lambda image: (0, 0, 10, 10), load_image=lambda path: None))
|
|
exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(MIRROR), 'exec'), ns)
|
|
method = ns['event_handling']
|
|
ns['event_handling'] = SimpleNamespace( # 上游模块 tasks.event.event_handling 的同名单例
|
|
decision_event_handling=lambda: False,
|
|
click_option_avoiding_unknown=functools.partial(avoid_ns['click_option_avoiding_unknown'], None))
|
|
mirror_cls = type('Mirror', (), {'event_handling': method})
|
|
mirror_mod = types.ModuleType('tasks.mirror.mirror')
|
|
mirror_mod.Mirror = mirror_cls
|
|
package = types.ModuleType('tasks.mirror')
|
|
package.mirror = mirror_mod
|
|
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod,
|
|
'module': types.ModuleType('module'),
|
|
'module.automation': SimpleNamespace(auto=screen),
|
|
'module.config': SimpleNamespace(cfg=cfg),
|
|
'module.ocr': SimpleNamespace(ocr=screen)}
|
|
with mock.patch.dict(sys.modules, modules):
|
|
if patched:
|
|
self.assertIsNotNone(ap.install_event_choices(log=self.lines.append, env=env or {}))
|
|
mirror = mirror_cls()
|
|
mirror.event_total_time, mirror.event_times = 0, 0
|
|
mirror.defense_for_solo = solo
|
|
mirror.event_handling()
|
|
self.assertEqual(mirror.event_times, 1)
|
|
self.assertNotIn('find_element', vars(screen), 'find_element 必须还原')
|
|
self.assertNotIn('mouse_click', vars(screen), 'mouse_click 必须还原')
|
|
self.screen = screen
|
|
return screen.chosen
|
|
|
|
@property
|
|
def log(self):
|
|
return '\n'.join(self.lines)
|
|
|
|
def test_patch_hooks_into_the_current_upstream(self):
|
|
self.play([SHEEP])
|
|
self.assertIn('patch: 镜牢事件按选项表选择', self.log)
|
|
self.assertNotIn('[ERROR]', self.log)
|
|
|
|
def test_table_choice_is_clicked_exactly_once(self):
|
|
self.assertEqual(self.play([SHEEP], patched=False), [0])
|
|
self.assertEqual(self.play([SHEEP]), [1]) # 上游拿返回的位置再点一次会被吞掉
|
|
self.assertIn('事件 梦中的电子羊: 1=你是特别的 | 2=你不是特别的; 按表选第 2 项「你不是特别的」', self.log)
|
|
|
|
def test_table_beats_the_unknown_tag(self):
|
|
# 上游有 "???" 就点 "???"; 表里的事件按表点
|
|
self.assertEqual(self.play([CHICKEN[::-1]], unknown=0, patched=False), [0])
|
|
self.assertEqual(self.play([CHICKEN[::-1]], unknown=0), [2])
|
|
|
|
def test_solo_mode_does_not_click_a_second_option(self):
|
|
# 小指良单通模式会再找一次 "???" 并改点别的选项; 已按表点过时它必须什么也不做
|
|
self.assertEqual(self.play([STATUE], unknown=0, solo=True, patched=False), [1])
|
|
self.assertEqual(self.play([STATUE], unknown=0, solo=True), [0])
|
|
|
|
def test_unknown_event_behaves_like_upstream(self):
|
|
for kwargs in ({}, {'unknown': 1}, {'unknown': 1, 'solo': True}):
|
|
with self.subTest(**kwargs):
|
|
options = [['战斗', '离开']]
|
|
self.assertEqual(self.play(options, **kwargs), self.play(options, patched=False, **kwargs))
|
|
self.assertIn('事件选项: 1=战斗 | 2=离开; 表里没有这个事件, 交给 AALC', self.log)
|
|
|
|
def test_one_ocr_per_screenshot_in_solo_mode(self):
|
|
# 单通模式下上游会再找一次 "???"; 同一张截图不再整屏 OCR 第二遍
|
|
self.assertEqual(self.play([['战斗', '离开']], unknown=1, solo=True), [0])
|
|
self.assertEqual(self.screen.ocr_runs, 1)
|
|
|
|
def test_misread_target_falls_back_to_upstream(self):
|
|
options = [['鸡肉就是鸡', CHICKEN[1], CHICKEN[2]]]
|
|
self.assertEqual(self.play(options), [0])
|
|
self.assertIn('表里要点的「鸡肉就是鸡肉喽」没读到, 交给 AALC', self.log)
|
|
|
|
def test_later_screens_not_in_the_table_go_to_upstream(self):
|
|
self.assertEqual(self.play([CHICKEN[::-1], ['好', '不好']]), [2, 0])
|
|
|
|
def test_unresponsive_clicks_are_capped(self):
|
|
chosen = self.play([SHEEP], ignore_clicks=ap.EVENT_TEXT_CLICKS + 1)
|
|
self.assertEqual(chosen[:ap.EVENT_TEXT_CLICKS + 1], [1] * ap.EVENT_TEXT_CLICKS + [0])
|
|
self.assertIn('这次事件已按表点了 %d 次, 交给 AALC' % ap.EVENT_TEXT_CLICKS, self.log)
|
|
|
|
def test_decisions_are_recorded_once_per_screen(self):
|
|
with mock.patch.object(ap.decisions, 'record') as record:
|
|
self.play([SHEEP])
|
|
self.play([['战斗', '离开']])
|
|
self.assertEqual(record.call_args_list, [
|
|
mock.call('event', 2, 'text', event='梦中的电子羊', event_id=901038, options=['你是特别的', '你不是特别的']),
|
|
mock.call('event', None, 'not_in_table', options=['战斗', '离开'])])
|
|
|
|
def test_env_zero_keeps_upstream(self):
|
|
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: '0'}))
|
|
|
|
# ---- LCP_EVENT_FALLBACK=1: 表外事件先点第 1 项 ----
|
|
FALLBACK = {ap.EVENT_FALLBACK_ENV: '1'}
|
|
|
|
def test_fallback_clicks_first_option_once_then_lets_upstream_continue(self):
|
|
# 11-18~11-21 实机: 点完第 1 项选项框还在, 补丁每轮抢先再点, 上游走不到「继续」(同屏连点 10~110 次)
|
|
screen = StickyEventScreen([['战斗', '离开']])
|
|
with mock.patch.object(ap.decisions, 'record') as record:
|
|
self.assertEqual(self.play(None, env=self.FALLBACK, screen=screen), [0])
|
|
self.assertEqual(screen.continues, 1)
|
|
self.assertEqual(record.call_args_list, [mock.call('event', 1, 'fallback_first', options=['战斗', '离开'])])
|
|
self.assertEqual(self.log.count('兜底点第 1 项'), 1)
|
|
|
|
def test_fallback_handles_each_new_screen_once(self):
|
|
screen = StickyEventScreen([['战斗', '离开'], ['好', '不好']])
|
|
self.assertEqual(self.play(None, env=self.FALLBACK, screen=screen), [0, 0])
|
|
self.assertEqual(screen.continues, 2)
|
|
|
|
def test_fallback_still_upstream_without_env(self):
|
|
screen = StickyEventScreen([['战斗', '离开']])
|
|
self.play(None, screen=screen)
|
|
self.assertNotIn('兜底点第 1 项', self.log)
|
|
self.assertIn('表里没有这个事件, 交给 AALC', self.log)
|
|
|
|
def test_click_lands_on_the_option_row_not_on_matching_narration(self):
|
|
# 叙述里正好有「特别的」: 原来整屏找子串, 会点到叙述那一行(第 1 项上方)
|
|
screen = EventScreen([SHEEP])
|
|
screen.narration = [('特别的', 200, 60)]
|
|
self.assertEqual(self.play(None, screen=screen), [1])
|
|
|
|
|
|
class InstallEventChoicesTest(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.lines = []
|
|
self.original = mock.Mock(side_effect=RuntimeError('boom'))
|
|
self.mirror_cls = type('Mirror', (), {'event_handling': self.original})
|
|
mirror_mod = types.ModuleType('tasks.mirror.mirror')
|
|
mirror_mod.Mirror = self.mirror_cls
|
|
package = types.ModuleType('tasks.mirror')
|
|
package.mirror = mirror_mod
|
|
self.auto = SimpleNamespace(find_element=mock.Mock(return_value=False), mouse_click=mock.Mock())
|
|
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod,
|
|
'module': types.ModuleType('module'),
|
|
'module.automation': SimpleNamespace(auto=self.auto),
|
|
'module.config': SimpleNamespace(cfg=SimpleNamespace(set_win_size=720))}
|
|
patcher = mock.patch.dict(sys.modules, modules)
|
|
patcher.start()
|
|
self.addCleanup(patcher.stop)
|
|
|
|
def test_methods_are_restored_after_an_exception(self):
|
|
find, click = self.auto.find_element, self.auto.mouse_click
|
|
ap.install_event_choices(log=self.lines.append, env={})
|
|
with self.assertRaises(RuntimeError):
|
|
self.mirror_cls().event_handling()
|
|
self.assertIs(self.auto.find_element, find)
|
|
self.assertIs(self.auto.mouse_click, click)
|
|
|
|
def test_unreadable_table_is_an_error(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, 'e.json')
|
|
with open(path, 'w', encoding='utf-8') as f:
|
|
json.dump({'events': [{'name': 'a', 'match': ['x'], 'index': 1}]}, f)
|
|
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: path}))
|
|
self.assertIs(self.mirror_cls.event_handling, self.original)
|
|
self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 事件选项表补丁跳过'))
|
|
|
|
def test_upstream_without_the_hook_is_an_error(self):
|
|
auto = self.auto
|
|
|
|
def event_handling(mirror):
|
|
return auto.click_element("event/unknown_event.png") # 旧写法: 补丁挂不上
|
|
|
|
self.mirror_cls.event_handling = event_handling
|
|
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={}))
|
|
self.assertIs(self.mirror_cls.event_handling, event_handling)
|
|
self.assertIn('[ERROR] [lc_mcp] 事件选项表补丁跳过: 上游 Mirror.event_handling 不再调用 find_element',
|
|
'\n'.join(self.lines))
|
|
|
|
def test_decision_error_falls_back_to_upstream_find(self):
|
|
calls = []
|
|
auto = self.auto
|
|
|
|
def find(target, *args, **kwargs):
|
|
if target == ap.EVENT_OPTION:
|
|
raise RuntimeError('template')
|
|
return False
|
|
|
|
def event_handling(mirror):
|
|
calls.append(auto.find_element("event/unknown_event.png"))
|
|
|
|
self.auto.find_element = mock.Mock(side_effect=find)
|
|
self.mirror_cls.event_handling = event_handling
|
|
ap.install_event_choices(log=self.lines.append, env={})
|
|
self.mirror_cls().event_handling()
|
|
self.assertEqual(calls, [False])
|
|
self.assertEqual(self.auto.find_element.call_args_list[-1], mock.call(ap.EVENT_HOOK))
|
|
self.assertIn('事件选项表出错(RuntimeError: template)', '\n'.join(self.lines))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|