按台账修镜牢: 饰品弹窗兜底、按键扫描码、卡包按体系加分

Browse Source
按 docs/ISSUES.md 处理本机回归后待修/待数据的条目:

- I-06/R-04 开局「获得E.G.O饰品」弹窗死循环: 确认模板连续第 3 次命中起改点
  按钮中心(勾号 +76/1440), 连续 20 次还在就记 [ERROR]、抛 TaskAbort 结束任务
  (上游 continue 跳过了循环计数)。单测执行上游真实 select_init_ego_gift。
- I-05/R-03 键盘寻路 0 成功: 前台按键改发带扫描码和扩展键标志的 keybd_event,
  各模式按住 0.12 秒(上游注释: Unity 6 校验扫描码/扩展键); 连续 3 个节点进不去
  就本次任务停用键盘寻路(方案 B)。MCP key 工具前台同样处理。LCP_KEY_HOLD=0 关。
- I-07/R-02 事件表 6 -> 9 条: 蜘蛛巢、归乡路途两段(拿「归途」), 按 wiki.gg 核对结果;
  全表按本机装的零协 release 2026111301 重新核对唯一性。
- I-13 复查 5992827: 「进入」先模板确认再 OCR(原来每轮都跑一次整屏 OCR);
  选队页重试重新截图; 入场切队失败记 [ERROR] 且本局不再重翻列表。
- R-01/I-08 卡包按体系加分: wiki.gg 122 个卡包(楼层/专属饰品/Featured 分类) +
  零协中文名生成 lc_mcp/data/theme_pack_systems.json(scripts/build_theme_pack_systems.py);
  灰机 wiki 对云端 403、BWIKI 无卡包条目, 中文社区攻略用 codex CLI 联网检索,
  推荐/避开并入表的 community。选卡包时临时加到 AALC 权重上, 按当前难度只看会出现
  的卡包; 审计记 system_bonus。LCP_THEME_PACK_SYSTEMS=0 关。
- 文档: ISSUES/BACKLOG/README 更新, 新增 docs/feedback/2026-11-15/REGRESSION.md
  (本轮回归清单)和 theme-pack-research.md(检索记录)。

单测 703 个全过(Linux)。实机未验。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-11-15 01:24:46 +00:00
co-authored by Claude Opus 5.5
parent 599282729c
commit 96a31bc1ae
19 changed files with 2121 additions and 56 deletions
+241
View File
@@ -0,0 +1,241 @@
# -*- coding: utf-8 -*-
"""「获得E.G.O饰品」确认弹窗兜底(ISSUES I-06 / R-04)。
2026-11-14 18:45: AALC 一直点确认模板的匹配点(勾号), 弹窗不关, 连点 5 分钟; 手动点按钮中心一次就过。
上游 select_init_ego_gift 点到确认就 continue, 循环底部的 loop_count 退出判断永远走不到。
端到端用例执行上游真实的 select_init_ego_gift。
"""
import ast
import sys
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'
CONFIRM = ap.GIFT_CONFIRM
TICK = (602.0, 531.75) # 1280x720 下确认模板(勾号)的中心
BUTTON = (640, 532) # 按钮中心: 勾号 + 76 * 720/1440
class Popup:
"""只有确认弹窗的假 auto: 点按钮中心才关(closes_on_button), 点勾号永远不关。"""
def __init__(self, closes_on_button=True):
self.open = True
self.closes_on_button = closes_on_button
self.template_clicks = 0
self.button_clicks = []
self.other_ok = False
def click_element(self, target, *args, click=True, **kwargs):
if target == CONFIRM and self.open:
if not click:
return TICK
self.template_clicks += 1
return True
if target == 'other' and self.other_ok:
return True if click else (1, 1)
return False
def mouse_click(self, x, y, *args, **kwargs):
self.button_clicks.append((x, y))
if self.closes_on_button and abs(x - BUTTON[0]) <= 15 and abs(y - BUTTON[1]) <= 15:
self.open = False
return True
class GuardTest(unittest.TestCase):
def install(self, auto, clock=None):
self.lines = []
self.now = [0.0]
modules = {'module': types.ModuleType('module'),
'module.automation': SimpleNamespace(auto=auto),
'module.config': SimpleNamespace(cfg=SimpleNamespace(set_win_size=720))}
with mock.patch.dict(sys.modules, modules):
self.assertIsNotNone(ap.install_gift_confirm_guard(
log=self.lines.append, clock=clock or (lambda: self.now[0])))
return auto
def hit(self, auto, times=1, step=1.5):
results = []
for _ in range(times):
self.now[0] += step
results.append(auto.click_element(CONFIRM))
return results
def test_first_two_hits_are_upstream_clicks(self):
auto = self.install(Popup())
self.assertEqual(self.hit(auto, 2), [True, True])
self.assertEqual(auto.template_clicks, 2)
self.assertEqual(auto.button_clicks, [])
def test_third_hit_clicks_the_button_center_and_closes_it(self):
auto = self.install(Popup())
with mock.patch.object(ap.decisions, 'record') as record:
self.assertEqual(self.hit(auto, 3), [True, True, True])
self.assertEqual(auto.button_clicks, [BUTTON])
self.assertFalse(auto.open)
self.assertIn('确认点了 2 次还在, 改点按钮中心 (640,532)', '\n'.join(self.lines))
record.assert_called_once_with('gift_confirm', 'button_center', 'repeated', clicks=2)
self.assertEqual(auto.click_element(CONFIRM), False) # 关了就找不到
def test_stuck_popup_ends_the_task(self):
auto = self.install(Popup(closes_on_button=False))
with mock.patch.object(ap.decisions, 'record'), self.assertRaises(ap.TaskAbort):
self.hit(auto, ap.GIFT_CONFIRM_LIMIT)
self.assertEqual(len(auto.button_clicks), ap.GIFT_CONFIRM_LIMIT - ap.GIFT_CONFIRM_SHIFT_AT)
self.assertIn('[ERROR] [lc_mcp] 「获得E.G.O饰品」确认连点 20 次弹窗还在, 结束任务', '\n'.join(self.lines))
# 不是 Exception: AALC 的 onetime_mir_process 吞不掉它
self.assertFalse(issubclass(ap.TaskAbort, Exception))
def test_other_successful_click_resets_the_streak(self):
auto = self.install(Popup(closes_on_button=False))
self.hit(auto, 2)
auto.other_ok = True
self.assertTrue(auto.click_element('other'))
self.hit(auto, 2)
self.assertEqual(auto.button_clicks, [])
self.assertEqual(auto.template_clicks, 4)
def test_other_lookup_or_failed_click_does_not_reset(self):
auto = self.install(Popup())
self.hit(auto, 2)
auto.click_element('missing')
auto.other_ok = True
auto.click_element('other', click=False) # 只查不点
self.hit(auto, 1)
self.assertEqual(auto.button_clicks, [BUTTON])
def test_missing_popup_resets_the_streak(self):
auto = self.install(Popup())
self.hit(auto, 2)
auto.open = False
self.assertEqual(self.hit(auto, 1), [False])
auto.open = True
self.hit(auto, 2)
self.assertEqual(auto.button_clicks, [])
def test_hits_far_apart_are_not_a_streak(self):
auto = self.install(Popup())
self.hit(auto, 2)
self.hit(auto, 1, step=ap.GIFT_CONFIRM_GAP + 1)
self.assertEqual(auto.button_clicks, [])
self.assertEqual(auto.template_clicks, 3)
def test_confirm_lookup_without_click_is_untouched(self):
auto = self.install(Popup())
for _ in range(5):
self.assertEqual(auto.click_element(CONFIRM, click=False), TICK)
self.assertEqual(auto.template_clicks, 0)
self.assertEqual(self.hit(auto, 2), [True, True])
self.assertEqual(auto.button_clicks, [])
class Spinning(Exception):
pass
class InitGiftScreen:
"""开局选饰品后的「获得E.G.O饰品」弹窗。点勾号不关, 点按钮中心才关, 关了就是卡包页。"""
def __init__(self, closes_on_button=True, max_shots=200):
self.state = 'popup'
self.closes_on_button = closes_on_button
self.max_shots = max_shots
self.shots = 0
self.model = 'clam'
self.template_clicks = 0
def take_screenshot(self, *args, **kwargs):
self.shots += 1
if self.shots > self.max_shots:
raise Spinning(self.shots)
return object()
def find_element(self, target, *args, **kwargs):
if target == 'mirror/theme_pack/feature_theme_pack_assets.png':
return (640, 100) if self.state == 'theme' else None
if target == CONFIRM and self.state == 'popup':
return TICK
return None
def click_element(self, target, *args, click=True, **kwargs):
pos = self.find_element(target)
if not pos:
return False
if not click:
return pos
self.template_clicks += 1 # 上游点的是匹配点(勾号) ±10 像素, 点不到按钮
return True
def mouse_click(self, x, y, *args, **kwargs):
if self.closes_on_button and abs(x - BUTTON[0]) <= 15 and abs(y - BUTTON[1]) <= 15:
self.state = 'theme'
return True
def mouse_to_blank(self, *args, **kwargs):
pass
def mouse_drag(self, *args, **kwargs):
pass
@unittest.skipUnless(MIRROR.is_file(), 'vendor/aalc 子模块未检出')
class UpstreamInitGiftTest(unittest.TestCase):
"""执行上游真实的 Mirror.select_init_ego_gift。"""
def setUp(self):
tree = ast.parse(MIRROR.read_text(encoding='utf-8'))
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Mirror')
self.fn_node = next(n for n in cls.body
if isinstance(n, ast.FunctionDef) and n.name == 'select_init_ego_gift')
self.lines = []
def play(self, screen, patched=True):
cfg = SimpleNamespace(set_win_size=720)
ns = dict(auto=screen, cfg=cfg, log=mock.Mock(), sleep=lambda *a: None, retry=lambda: True,
back_init_menu=mock.Mock(), all_systems={}, start_gift={})
exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(MIRROR), 'exec'), ns)
mirror = SimpleNamespace(system='bleed', opening_items=False, observe_ego_gift=False,
observe_ego_gift_selected=[], observe_bbox=None,
_click_init_gift_row=lambda gift_id: False)
if patched:
modules = {'module': types.ModuleType('module'),
'module.automation': SimpleNamespace(auto=screen),
'module.config': SimpleNamespace(cfg=cfg)}
with mock.patch.dict(sys.modules, modules):
ap.install_gift_confirm_guard(log=self.lines.append)
with mock.patch.object(ap.decisions, 'record'):
return ns['select_init_ego_gift'](mirror)
def test_upstream_spins_on_a_popup_its_click_cannot_close(self):
screen = InitGiftScreen()
with self.assertRaises(Spinning):
self.play(screen, patched=False)
self.assertEqual(screen.state, 'popup')
self.assertGreater(screen.template_clicks, 100) # 计数早就负了, 照点不误
def test_guard_clicks_the_button_and_the_loop_moves_on(self):
screen = InitGiftScreen()
self.play(screen)
self.assertEqual(screen.state, 'theme')
self.assertEqual(screen.template_clicks, ap.GIFT_CONFIRM_SHIFT_AT - 1)
self.assertLess(screen.shots, 10)
def test_guard_ends_the_task_when_nothing_closes_it(self):
screen = InitGiftScreen(closes_on_button=False)
with self.assertRaises(ap.TaskAbort):
self.play(screen)
self.assertLessEqual(screen.shots, ap.GIFT_CONFIRM_LIMIT + 1)
self.assertIn('[ERROR]', '\n'.join(self.lines))
if __name__ == '__main__':
unittest.main()
+211
View File
@@ -0,0 +1,211 @@
# -*- coding: utf-8 -*-
"""按键补丁(ISSUES I-05): 前台按键带扫描码和扩展键标志, 各模式按住再松开。
2026-11-14 镜牢键盘寻路 24/24 没进去。AALC 前台 key_press 是 pyautogui.press: 扫描码 0、方向键没有
扩展键标志、down/up 紧挨着; 上游后台模式的注释写明 Unity 6+ 会校验扫描码和扩展键标志。
"""
import ast
import sys
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
INPUT = REPO / 'vendor' / 'aalc' / 'module' / 'automation' / 'input_handlers' / 'input.py'
VK_UP, VK_P, VK_RETURN = 0x26, 0x50, 0x0D
SCANS = {VK_UP: 0x48, VK_P: 0x19, VK_RETURN: 0x1C}
pyautogui = SimpleNamespace(press=mock.Mock()) # 假 Input.key_press 的源码里要有 pyautogui.press
class User32:
def __init__(self, events):
self.events = events
def MapVirtualKeyW(self, vk, kind):
assert kind == 0
return SCANS.get(vk, 0)
def keybd_event(self, vk, scan, flags, extra):
self.events.append(('keybd', vk, scan, flags))
class Handle:
def __init__(self, active=True, activates=True):
self.active = active
self.activates = activates
self.foreground_calls = 0
@property
def isActive(self):
return self.active
def setForeground(self):
self.foreground_calls += 1
self.active = self.activates
def fake_input_module(events):
class Input:
def key_press(self, key):
return pyautogui.press(key)
class BackgroundInput:
def set_active(self):
events.append(('active',))
def key_down(self, key):
events.append(('down', key))
def key_up(self, key):
events.append(('up', key))
def key_press(self, key):
self.set_active()
self.key_down(key)
self.key_up(key)
class WindowMoveInput(BackgroundInput):
def key_press(self, key):
self.set_active()
self.key_down(key)
self.key_up(key)
module = types.ModuleType('module.automation.input_handlers.input')
module.key_list = {'up': VK_UP, 'p': VK_P, 'enter': VK_RETURN}
module.EXTENDED_KEY_VKS = frozenset({VK_UP})
module.Input, module.BackgroundInput, module.WindowMoveInput = Input, BackgroundInput, WindowMoveInput
return module
class KeyHoldTest(unittest.TestCase):
def setUp(self):
self.events = []
self.lines = []
self.input_mod = fake_input_module(self.events)
self.handle = Handle()
pyautogui.press.reset_mock()
sleep = mock.patch.object(ap.time, 'sleep', side_effect=lambda s: self.events.append(('sleep', s)))
sleep.start()
self.addCleanup(sleep.stop)
def install(self, env=None):
handlers = types.ModuleType('module.automation.input_handlers')
handlers.input = self.input_mod
modules = {'module': types.ModuleType('module'),
'module.automation': types.ModuleType('module.automation'),
'module.automation.input_handlers': handlers,
'module.automation.input_handlers.input': self.input_mod,
'module.game_and_screen': SimpleNamespace(screen=SimpleNamespace(handle=self.handle))}
with mock.patch.dict(sys.modules, modules):
return ap.install_key_hold(log=self.lines.append, env=env or {}, user32=User32(self.events))
def test_arrow_key_has_scan_code_extended_flag_and_is_held(self):
self.assertEqual(sorted(self.install()), ['BackgroundInput', 'Input', 'WindowMoveInput'])
self.input_mod.Input().key_press('UP')
self.assertEqual(self.events, [('keybd', VK_UP, 0x48, 0x1), ('sleep', ap.KEY_HOLD),
('keybd', VK_UP, 0x48, 0x3)])
pyautogui.press.assert_not_called()
def test_letter_key_has_scan_code_without_extended_flag(self):
self.install()
self.input_mod.Input().key_press('p')
self.assertEqual(self.events, [('keybd', VK_P, 0x19, 0x0), ('sleep', ap.KEY_HOLD),
('keybd', VK_P, 0x19, 0x2)])
def test_inactive_game_window_is_activated_first(self):
self.handle.active = False
self.install()
self.input_mod.Input().key_press('enter')
self.assertEqual(self.handle.foreground_calls, 1)
self.assertEqual([e for e in self.events if e[0] == 'keybd'],
[('keybd', VK_RETURN, 0x1C, 0x0), ('keybd', VK_RETURN, 0x1C, 0x2)])
def test_key_is_not_sent_to_another_window(self):
self.handle = Handle(active=False, activates=False)
self.install()
self.input_mod.Input().key_press('enter')
self.assertEqual([e for e in self.events if e[0] == 'keybd'], [])
pyautogui.press.assert_not_called()
self.assertIn('按键 enter 没发: 游戏窗口不在前台', '\n'.join(self.lines))
def test_unknown_key_goes_to_upstream(self):
self.install()
self.input_mod.Input().key_press('f13')
pyautogui.press.assert_called_once_with('f13')
self.assertEqual(self.events, [])
def test_background_modes_hold_between_down_and_up(self):
self.install()
for cls in (self.input_mod.BackgroundInput, self.input_mod.WindowMoveInput):
self.events.clear()
cls().key_press('up')
self.assertEqual(self.events, [('active',), ('down', 'up'), ('sleep', ap.KEY_HOLD), ('up', 'up')])
def test_background_key_is_released_even_if_interrupted(self):
self.install()
with mock.patch.object(ap.time, 'sleep', side_effect=InterruptedError):
with self.assertRaises(InterruptedError):
self.input_mod.BackgroundInput().key_press('p')
self.assertEqual(self.events[-1], ('up', 'p'))
def test_foreground_key_is_released_even_if_interrupted(self):
self.install()
with mock.patch.object(ap.time, 'sleep', side_effect=InterruptedError):
with self.assertRaises(InterruptedError):
self.input_mod.Input().key_press('up')
self.assertEqual(self.events[-1], ('keybd', VK_UP, 0x48, 0x3))
def test_env_zero_keeps_upstream(self):
original = self.input_mod.Input.key_press
self.assertIsNone(self.install(env={ap.KEY_HOLD_ENV: '0'}))
self.assertIs(self.input_mod.Input.key_press, original)
def test_changed_upstream_foreground_is_reported_not_patched(self):
def key_press(self, key):
return None
self.input_mod.Input.key_press = key_press
self.assertEqual(sorted(self.install()), ['BackgroundInput', 'WindowMoveInput'])
self.assertIs(self.input_mod.Input.key_press, key_press)
self.assertIn('[ERROR] [lc_mcp] 按键补丁: 上游前台 Input.key_press 不再用 pyautogui.press', '\n'.join(self.lines))
@unittest.skipUnless(INPUT.is_file(), 'vendor/aalc 子模块未检出')
class UpstreamInputTest(unittest.TestCase):
"""补丁依赖的上游写法: 前台 pyautogui.press, 后台 set_active + key_down + key_up, 方向键在扩展键表里。"""
def setUp(self):
self.source = INPUT.read_text(encoding='utf-8')
self.tree = ast.parse(self.source)
def method_source(self, cls_name, name):
cls = next(n for n in self.tree.body if isinstance(n, ast.ClassDef) and n.name == cls_name)
node = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == name)
return ast.get_source_segment(self.source, node)
def test_foreground_uses_pyautogui_press(self):
self.assertIn('pyautogui.press(key)', self.method_source('Input', 'key_press'))
def test_background_modes_send_down_up_back_to_back(self):
for cls in ('BackgroundInput', 'WindowMoveInput'):
body = self.method_source(cls, 'key_press')
self.assertIn('self.set_active()', body)
self.assertLess(body.index('self.key_down(key)'), body.index('self.key_up(key)'))
self.assertNotIn('sleep', body)
def test_arrow_keys_are_extended(self):
for vk in ('VK_UP', 'VK_DOWN', 'VK_LEFT', 'VK_RIGHT'):
self.assertIn('win32con.%s' % vk, self.source.split('EXTENDED_KEY_VKS', 1)[1].split(')', 1)[0])
if __name__ == '__main__':
unittest.main()
+12 -3
View File
@@ -9,7 +9,9 @@ import sys
import tempfile
import threading
import time
import types
import unittest
from types import SimpleNamespace
from unittest import mock
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -387,12 +389,19 @@ class RuntimeTest(unittest.TestCase):
mock.patch('lc_mcp.aalc_engine.time.sleep', side_effect=[None, RuntimeError('interrupted')]):
with self.assertRaises(RuntimeError):
engine.click(100, 200)
with mock.patch.dict(sys.modules, pyautogui=pointer), \
mock.patch('lc_mcp.aalc_engine.time.sleep', side_effect=RuntimeError('interrupted')):
user32 = mock.Mock()
user32.MapVirtualKeyW.return_value = 0x1C
tables = types.ModuleType('module.automation.input_handlers.input')
tables.key_list, tables.EXTENDED_KEY_VKS = {'enter': 0x0D}, frozenset({0x26})
with mock.patch.dict(sys.modules, {'module.automation.input_handlers.input': tables}), \
mock.patch('ctypes.windll', SimpleNamespace(user32=user32), create=True), \
mock.patch('time.sleep', side_effect=RuntimeError('interrupted')):
with self.assertRaises(RuntimeError):
engine.keypress('enter')
pointer.mouseUp.assert_called_once_with(580, 657)
pointer.keyUp.assert_called_once_with('enter')
# 前台按键带扫描码; 按住期间被打断也要抬起
self.assertEqual(user32.keybd_event.call_args_list, [mock.call(0x0D, 0x1C, 0, 0), mock.call(0x0D, 0x1C, 2, 0)])
pointer.keyDown.assert_not_called()
def test_foreground_move_settle_failure_sends_no_button_press(self):
from lc_mcp.aalc_engine import AalcEngine
+148 -3
View File
@@ -421,9 +421,6 @@ class InstallSystemTeamSelectionTest(unittest.TestCase):
self.assertIsNone(self.install())
if __name__ == '__main__':
unittest.main()
class TeamScreenDetectionTest(unittest.TestCase):
def setUp(self):
@@ -471,3 +468,151 @@ class TeamScreenGuardTest(unittest.TestCase):
with mock.patch.object(aalc_patches, '_is_starlight_screen', return_value=False):
self.assertEqual(auto.find_element(aalc_patches.TEAM_SCREEN_STARS), (640, 360))
self.assertFalse(auto.find_element('mirror/other.png'))
class _LoadingTeamScreen(_FakeTeamScreen):
"""选队页刚加载: 第 loaded_at 张截图之前编队图标和列表都还没出来。"""
def __init__(self, screens, loaded_at=2, **kwargs):
super().__init__(screens, **kwargs)
self.loaded_at = loaded_at
self.shots = 0
def take_screenshot(self):
self.shots += 1
return object()
@property
def loaded(self):
return self.shots >= self.loaded_at
def find_element(self, *args, **kwargs):
return self.loaded
def read(self):
if not self.loaded:
return SimpleNamespace(txts=(), boxes=[])
return super().read()
class SelectTeamScreenWaitTest(unittest.TestCase):
def setUp(self):
self.lines = []
engine = SimpleNamespace(ocr=SimpleNamespace(run=lambda screen: screen.read()))
for patcher in (mock.patch.dict(sys.modules, {'module': types.ModuleType('module'), 'module.ocr': engine}),
mock.patch.object(aalc_patches.time, 'sleep'),
mock.patch.object(aalc_patches.decisions, 'record')):
patcher.start()
self.addCleanup(patcher.stop)
def test_waits_for_a_fresh_screenshot_of_the_team_screen(self):
# 旧写法对着同一张截图认 3 次, 页面加载慢一点就报"不在编队界面"
auto = _LoadingTeamScreen([['剧情关卡', '流血', '震颤']], loaded_at=3)
self.assertTrue(aalc_patches._select_team_by_name(auto, ('流血',), log=self.lines.append))
self.assertEqual(auto.header, '流血')
def test_gives_up_when_the_team_screen_never_shows(self):
auto = _LoadingTeamScreen([['剧情关卡', '流血']], loaded_at=99)
self.assertFalse(aalc_patches._select_team_by_name(auto, ('流血',), log=self.lines.append))
self.assertIn('不在编队界面, 跳过按名字选队', '\n'.join(self.lines))
self.assertEqual(auto.clicks, [])
class _EnterScreen(_FakeTeamScreen):
"""选队页右下角有「进入」; 记下点「进入」时顶栏是哪支队, 以及整屏 OCR 跑了几次。"""
def __init__(self, screens, enter=True, **kwargs):
super().__init__(screens, **kwargs)
self.enter = enter
self.entered_with = []
self.ocr_runs = 0
def click_element(self, target, *args, click=True, **kwargs):
if target != aalc_patches.ENTER_ASSET or not self.enter:
return False
if not click:
return (1100, 650)
self.entered_with.append(self.header)
return True
def read(self):
self.ocr_runs += 1
return super().read()
class EnterSwitchTest(unittest.TestCase):
"""镜牢入场时 AALC 直接点「进入」, 不走 select_battle_team; 补丁在点之前切队。"""
TOP = ['剧情关卡', '斩击', '突刺', '打击', '烧伤']
MIDDLE = ['流血', '震颤', '破裂', '沉沦', '呼吸法']
def install(self, auto, system='bleed'):
self.lines = []
self.mirror_mod = types.ModuleType('tasks.mirror.mirror')
self.mirror_mod.Mirror = type('Mirror', (_FakeMirror,), {})
self.mirror_mod.select_battle_team = lambda num: False
tasks_pkg, mirror_pkg = types.ModuleType('tasks'), types.ModuleType('tasks.mirror')
mirror_pkg.mirror = self.mirror_mod
engine = SimpleNamespace(ocr=SimpleNamespace(run=lambda screen: screen.read()))
for patcher in (mock.patch.dict(sys.modules, {
'tasks': tasks_pkg, 'tasks.mirror': mirror_pkg, 'tasks.mirror.mirror': self.mirror_mod,
'module': types.ModuleType('module'), 'module.ocr': engine,
'module.automation': SimpleNamespace(auto=auto)}),
mock.patch.object(aalc_patches.time, 'sleep'),
mock.patch.object(aalc_patches.decisions, 'record')):
patcher.start()
self.addCleanup(patcher.stop)
aalc_patches.install_system_team_selection(log=self.lines.append)
self.mirror_mod.Mirror({'system': system}, 1)
return auto
@property
def log(self):
return '\n'.join(self.lines)
def test_no_enter_button_means_no_ocr(self):
# 主循环每轮都会问一次「进入」; 按钮不在画面上时不该为它跑整屏 OCR
auto = self.install(_EnterScreen([self.TOP], enter=False))
for _ in range(5):
self.assertFalse(auto.click_element(aalc_patches.ENTER_ASSET))
self.assertEqual(auto.ocr_runs, 0)
def test_switches_to_the_system_team_before_entering(self):
auto = self.install(_EnterScreen([self.TOP, self.MIDDLE]))
self.assertTrue(auto.click_element(aalc_patches.ENTER_ASSET))
self.assertEqual(auto.entered_with, ['流血'])
self.assertIn('入场前切队伍: 流血', self.log)
def test_already_on_the_team_just_enters(self):
auto = self.install(_EnterScreen([self.TOP, self.MIDDLE], header='流血'))
self.assertTrue(auto.click_element(aalc_patches.ENTER_ASSET))
self.assertEqual(auto.entered_with, ['流血'])
self.assertEqual(auto.clicks, [])
self.assertNotIn('入场前切队伍:', self.log)
def test_failed_switch_is_an_error_and_is_not_retried_this_run(self):
auto = self.install(_EnterScreen([self.TOP, ['破裂', '沉沦', '编队#13']]))
self.assertTrue(auto.click_element(aalc_patches.ENTER_ASSET))
self.assertEqual(auto.entered_with, ['剧情关卡'])
self.assertIn('[ERROR] [lc_mcp] 入场前没切到 流血, 本局按游戏当前编队进入', self.log)
runs = auto.ocr_runs
self.assertTrue(auto.click_element(aalc_patches.ENTER_ASSET)) # 上游再点一次「进入」
self.assertEqual(auto.ocr_runs, runs) # 不再从头翻列表
self.mirror_mod.Mirror({'system': 'bleed'}, 1) # 下一局重新试
auto.click_element(aalc_patches.ENTER_ASSET)
self.assertGreater(auto.ocr_runs, runs)
def test_lookup_without_click_is_passed_through(self):
auto = self.install(_EnterScreen([self.TOP, self.MIDDLE]))
self.assertEqual(auto.click_element(aalc_patches.ENTER_ASSET, click=False), (1100, 650))
self.assertEqual((auto.ocr_runs, auto.entered_with), (0, []))
def test_other_targets_are_untouched(self):
auto = self.install(_EnterScreen([self.TOP]))
self.assertFalse(auto.click_element('mirror/road_to_mir/resume_assets.png'))
self.assertEqual(auto.ocr_runs, 0)
if __name__ == '__main__':
unittest.main()
+358
View File
@@ -0,0 +1,358 @@
# -*- coding: utf-8 -*-
"""镜牢卡包按体系加分(BACKLOG R-01 / ISSUES I-08)。
theme_pack_list.yaml 几乎全是 0, 所有卡包并列最高分, 每层拿最左边那个。补丁在 AALC 选卡包时把
「卡包对当局体系的加分」(lc_mcp/data/theme_pack_systems.json, 数据来自 wiki.gg)临时加到权重表上。
端到端用例执行上游真实的 select_theme_pack, 卡面按 AALC 的规则(按表顺序取第一个子串命中的键)认。
"""
import ast
import json
import logging
import os
import re
import sys
import tempfile
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
THEME = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'select_theme_pack.py'
EXAMPLE = REPO / 'vendor' / 'aalc' / 'assets' / 'config' / 'theme_pack_list.example.yaml'
BONUS = {'featured': 6, 'unique': (0, 1, 4, 6), 'recommend': 6, 'avoid': 3}
BUILD = REPO / 'scripts' / 'build_theme_pack_systems.py'
def example_weights(*sections):
"""读 AALC 自带的 theme_pack_list.example.yaml(只认 `键: 整数` 这种行)。"""
found, current = {}, None
for line in EXAMPLE.read_text(encoding='utf-8').splitlines():
header = re.match(r'^(\w+):\s*$', line)
if header:
current = header.group(1)
continue
item = re.match(r'^\s+(\S.*?):\s*(-?\d+)', line)
if item and current in sections:
found[item.group(1)] = int(item.group(2))
return found
def pack(zh, en='x', featured=(), recommend=(), avoid=(), normal='1F', hard='1F', **unique):
return {'zh': zh, 'en': en, 'featured': list(featured), 'unique': unique, 'recommend': set(recommend),
'avoid': set(avoid), 'normal': normal, 'hard': hard}
class ThemePackTableTest(unittest.TestCase):
def setUp(self):
self.bonus, self.packs = ap.load_theme_pack_systems()
self.by_name = {p['zh']: p for p in self.packs}
def test_table_covers_the_current_theme_packs(self):
self.assertEqual(len(self.packs), len({p['id'] for p in self.packs}))
self.assertGreaterEqual(len(self.packs), 120)
self.assertEqual(self.bonus, BONUS)
def test_keyword_packs_and_story_packs(self):
# wiki.gg: Featured Gifts 用体系分类的就是体系包; 专属饰品按体系计数
self.assertEqual(self.by_name['电闪雷鸣']['featured'], ['charge'])
self.assertEqual(self.by_name['动力渐盈']['featured'], ['charge'])
self.assertEqual(self.by_name['尸山血海']['featured'], ['bleed'])
self.assertEqual(self.by_name['LCB定期体检']['featured'], ['burn', 'rupture'])
self.assertEqual(self.by_name['当斩之物']['featured'], ['slash'])
self.assertEqual(self.by_name['WARP快车谋杀案']['unique']['charge'], 5)
self.assertEqual(self.by_name['时间杀人时间']['unique']['tremor'], 5)
self.assertEqual(self.by_name['被遗忘者们']['unique'], {})
def test_community_entries_are_attached(self):
self.assertEqual(self.by_name['憎恶与绝望']['recommend'], {'burn', 'tremor', 'sinking', 'charge'})
self.assertEqual(self.by_name['被遗忘者们']['avoid'], {'*'})
self.assertEqual(self.by_name['琥珀色的黄昏']['avoid'], {'bleed'})
self.assertEqual(self.by_name['琥珀色的黄昏']['recommend'], {'sinking'})
def test_community_tiers(self):
b = self.bonus
self.assertEqual(ap.theme_pack_bonus(self.by_name['憎恶与绝望'], 'charge', b), 6) # 专属 2 件 4, 推荐 6
self.assertEqual(ap.theme_pack_bonus(self.by_name['地狱鸡'], 'poise', b), 6)
self.assertEqual(ap.theme_pack_bonus(self.by_name['琥珀色的黄昏'], 'bleed', b), 0) # 专属 3 件, 但攻略说不划算
self.assertEqual(ap.theme_pack_bonus(self.by_name['被遗忘者们'], 'charge', b), -3)
self.assertEqual(ap.theme_pack_bonus(self.by_name['当碎之物'], 'blunt', b), 3) # 体系包 6, 拖时间 -3
def test_bonus_tiers(self):
self.assertEqual(ap.theme_pack_bonus(self.by_name['电闪雷鸣'], 'charge', self.bonus), 6)
self.assertEqual(ap.theme_pack_bonus(self.by_name['WARP快车谋杀案'], 'charge', self.bonus), 6)
self.assertEqual(ap.theme_pack_bonus(self.by_name['开店抢购'], 'charge', self.bonus), 4)
self.assertEqual(ap.theme_pack_bonus(self.by_name['WARP快车谋杀案'], 'bleed', self.bonus), 1)
self.assertEqual(ap.theme_pack_bonus(self.by_name['电闪雷鸣'], 'bleed', self.bonus), 0)
def test_bad_tables_are_rejected(self):
for data in ({'bonus': {'featured': 6, 'unique': []}, 'packs': [pack('a')]},
{'bonus': BONUS | {'unique': [0, 1]}, 'packs': []},
{'bonus': {'featured': 6, 'unique': [0, 1]}, 'packs': [pack('a', featured=['fire'])]},
{'bonus': {'featured': 6, 'unique': [0, 1]}, 'packs': [pack('a', burn=0)]},
{'bonus': {'featured': 6, 'unique': [0, 1]}, 'packs': [pack('', 'x')]},
{'bonus': {'featured': 6, 'unique': [0, 1]}, 'packs': [pack('a')],
'community': {'recommend': [{'pack': '不存在', 'systems': ['burn']}]}},
{'bonus': {'featured': 6, 'unique': [0, 1]}, 'packs': [pack('a')],
'community': {'recommend': [{'pack': 'a', 'systems': ['*']}]}},
{'bonus': {'featured': 6, 'unique': [0, 1]}, 'packs': [pack('a')],
'community': {'avoid': [{'pack': 'a', 'systems': []}]}}):
with self.subTest(data=data), tempfile.TemporaryDirectory() as d:
path = os.path.join(d, 't.json')
with open(path, 'w', encoding='utf-8') as fh:
json.dump(data, fh, ensure_ascii=False, default=list)
with self.assertRaises(ValueError):
ap.load_theme_pack_systems(path)
class BoostTest(unittest.TestCase):
def setUp(self):
self.bonus, self.packs = ap.load_theme_pack_systems()
def boost(self, weights, system, language='zh_cn', packs=None):
return ap.boost_theme_pack_weights(dict(weights), packs or self.packs, system, self.bonus, language)
@unittest.skipUnless(EXAMPLE.is_file(), 'vendor/aalc 子模块未检出')
def test_charge_team_in_normal_mode(self):
weights = example_weights('theme_pack_list_cn')
result, info = self.boost(weights, 'charge')
self.assertEqual((result['谋杀'], result['开店']), (1, 1)) # WARP 专属 5 件充能, 开店 2 件
self.assertEqual((result['绝望'], result['绞丝']), (1, 1)) # 社区推荐
self.assertEqual(result['赌徒'], 0)
self.assertEqual((result['遗忘'], result['自动']), (-3, -5)) # 速刷攻略说拖时间
self.assertEqual(result['地狱鸡'], 1)
self.assertEqual(info['谋杀'], {'packs': ['WARP快车谋杀案', 'WARP快车谋杀案 复刻'], 'system': 'charge',
'from': -5, 'to': 1})
self.assertEqual(set(result), set(weights) | {k for k in info if k not in weights})
# 加过分的键排在最前面
self.assertEqual(list(result)[:len(info)], list(info))
@unittest.skipUnless(EXAMPLE.is_file(), 'vendor/aalc 子模块未检出')
def test_keyword_packs_in_hard_mode(self):
weights = example_weights('theme_pack_list_cn', 'theme_pack_list_hard_cn')
result, _ = self.boost(weights, 'charge')
self.assertEqual((result['电闪雷鸣'], result['动力']), (6, 6))
result, _ = self.boost(weights, 'bleed')
self.assertEqual(result['渗出的'], 6)
@unittest.skipUnless(EXAMPLE.is_file(), 'vendor/aalc 子模块未检出')
def test_shared_key_takes_the_smaller_bonus_and_the_reprint_gets_its_full_name(self):
# 「谋杀」同时命中原版(流血 1 件)和复刻(流血 3 件)
result, info = self.boost(example_weights('theme_pack_list_cn'), 'bleed')
self.assertEqual(result['谋杀'], -4)
self.assertEqual(result['WARP快车谋杀案 复刻'], 1)
order = list(result)
self.assertLess(order.index('WARP快车谋杀案 复刻'), order.index('谋杀'))
@unittest.skipUnless(EXAMPLE.is_file(), 'vendor/aalc 子模块未检出')
def test_key_shared_with_an_unrelated_pack_is_left_alone(self):
# 「区的奇」= 20区的奇迹 + 复刻; 只有复刻有震颤专属饰品
result, info = self.boost(example_weights('theme_pack_list_cn'), 'tremor')
self.assertEqual(result['区的奇'], 0)
self.assertEqual(result['20区的奇迹 复刻'], 1)
self.assertNotIn('区的奇', info)
def test_pack_unknown_to_aalc_starts_from_the_unknown_weight(self):
packs = [pack('黎明后贯穿而来之楔', pierce=3)]
result, info = self.boost({'遗忘': 0, '未知': -5}, 'pierce', packs=packs)
self.assertEqual(result['黎明后贯穿而来之楔'], 1)
self.assertEqual(result['未知'], -5)
def test_english_keys(self):
packs = [pack('WARP快车谋杀案', 'Murder on the WARP Express', charge=5),
pack('电闪雷鸣', 'Thunder and Lightning', featured=['charge']),
pack('被遗忘者们', 'The Forgotten')]
result, _ = self.boost({'forgot': 0, 'warp': -5, 'thunder': 0, 'unknown': -5}, 'charge', 'en', packs)
self.assertEqual(result, {'thunder': 6, 'warp': 1, 'forgot': 0, 'unknown': -5})
def test_unrelated_keys_keep_their_weight(self):
weights = {'信仰': 0, '赌徒': -1}
result, info = self.boost(weights, 'charge')
self.assertEqual((result['信仰'], result['赌徒']), (0, -1))
self.assertNotIn('信仰', info)
# 表里没有的充能卡包补全名键, 从「未知」(表里也没有就 -5)起算
self.assertEqual(result['电闪雷鸣'], 1)
@unittest.skipUnless(EXAMPLE.is_file(), 'vendor/aalc 子模块未检出')
def test_packs_missing_from_the_difficulty_do_not_block_a_key(self):
# 「海·边」也是活动专用包 去·海·边·激·蟹 的一部分; 普通/困难都不会出现它, 不算冲突
weights = example_weights('theme_pack_list_cn')
self.assertEqual(self.boost(weights, 'pierce')[0]['海·边'], 0)
result, _ = ap.boost_theme_pack_weights(dict(weights), self.packs, 'pierce', self.bonus, 'zh_cn', False)
self.assertEqual((result['海·边'], result['区的奇'], result['赌徒']), (6, 6, 6))
# 困难模式 20区的奇迹 复刻 也会出现, 它和突刺无关, 「区的奇」就不动
weights = example_weights('theme_pack_list_cn', 'theme_pack_list_hard_cn')
result, _ = ap.boost_theme_pack_weights(dict(weights), self.packs, 'pierce', self.bonus, 'zh_cn', True)
self.assertEqual(result['区的奇'], 0)
def test_penalties_follow_the_same_shared_key_rule(self):
packs = [pack('被遗忘者们', avoid=['*']), pack('自动工厂', avoid=['*']), pack('遗忘的工厂')]
result, info = self.boost({'遗忘': 0, '工厂': -2}, 'charge', packs=packs)
self.assertEqual(result['遗忘'], 0) # 遗忘的工厂 不减分, 有加有不加就不动短键
self.assertEqual(result['被遗忘者们'], -3) # 改用全名
self.assertEqual(result['工厂'], -2)
self.assertEqual(result['自动工厂'], -5)
def test_system_without_any_pack_changes_nothing(self):
packs = [pack('被遗忘者们'), pack('电闪雷鸣', featured=['charge'])]
weights = {'遗忘': 0, '电闪雷鸣': -5}
self.assertEqual(self.boost(weights, 'burn', packs=packs), (weights, {}))
@unittest.skipUnless(BUILD.is_file(), 'scripts 目录缺失')
class GeneratorFormatTest(unittest.TestCase):
def test_generator_writes_the_shipped_file_byte_for_byte(self):
import importlib.util
spec = importlib.util.spec_from_file_location('build_theme_pack_systems', BUILD)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
text = Path(ap.THEME_PACK_SYSTEMS_FILE).read_text(encoding='utf-8')
self.assertEqual(module.dump_table(json.loads(text)), text)
class Match:
def __init__(self, value, text):
self.value, self.text, self.position = value, text, [0, 0]
@unittest.skipUnless(THEME.is_file(), 'vendor/aalc 子模块未检出')
class UpstreamSelectThemePackTest(unittest.TestCase):
"""执行上游真实的 select_theme_pack(普通模式, 中文)。"""
def setUp(self):
self.lines = []
tree = ast.parse(THEME.read_text(encoding='utf-8'))
self.node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'select_theme_pack')
self.node.decorator_list = []
def play(self, cards, system, patched=True, audit=False, env=None):
positions = [(300 + 300 * i, 300) for i in range(len(cards))]
weights = example_weights('theme_pack_list_cn')
lookups = []
def find_language_text(zh, en, crop):
# AALC: 按表的顺序, 第一个(去空格、不分大小写)是卡面文字子串的键
x = (crop[0] + crop[2]) / 2
text = cards[min(range(len(cards)), key=lambda i: abs(positions[i][0] - x))].replace(' ', '').lower()
lookups.append(zh)
for key, value in zh.items():
if key.replace(' ', '').lower() in text:
return Match(value, key)
return None
auto = SimpleNamespace(
model=None, take_screenshot=lambda: object(), mouse_to_blank=lambda *a, **k: None,
find_element=lambda target, **kw: list(positions) if 'theme_pack_features' in target else False,
find_language_text=find_language_text, mouse_drag_down=mock.Mock(),
click_element=lambda *a, **k: False)
theme_list = SimpleNamespace(preferred_thresholds=0, get_effective_theme_pack_list=lambda *a: dict(weights))
ns = dict(auto=auto, TextMatchResult=Match, sleep=lambda *a: None, back_init_menu=mock.Mock(),
log=logging.getLogger('AALC'), theme_list=theme_list,
cfg=SimpleNamespace(set_win_size=720, select_event_pack=False, skip_event_pack=False),
path_manager=SimpleNamespace(current_language='zh_cn'))
exec(compile(ast.Module(body=[self.node], type_ignores=[]), str(THEME), 'exec'), ns)
theme_mod = types.ModuleType('tasks.mirror.select_theme_pack')
theme_mod.theme_list = theme_list
mirror_mod = types.ModuleType('tasks.mirror.mirror')
mirror_mod.select_theme_pack = ns['select_theme_pack']
mirror_mod.Mirror = type('Mirror', (), {'__init__': lambda self, system: setattr(self, 'system', system)})
package = types.ModuleType('tasks.mirror')
package.mirror, package.select_theme_pack = mirror_mod, theme_mod
logger = logging.getLogger('AALC')
with mock.patch.dict(sys.modules, {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package,
'tasks.mirror.mirror': mirror_mod,
'tasks.mirror.select_theme_pack': theme_mod}), \
mock.patch.object(logger, 'level', logging.DEBUG), mock.patch.object(logger, 'propagate', False), \
mock.patch.object(ap.decisions, 'record') as record:
if patched:
self.assertIsNotNone(ap.install_theme_pack_systems(log=self.lines.append, env=env or {}))
if audit:
ap.install_theme_pack_audit(log=self.lines.append)
mirror_mod.Mirror(system)
mirror_mod.select_theme_pack(False, 4, 1, False)
self.assertEqual(theme_list.get_effective_theme_pack_list(), weights, '权重表的原方法必须还原')
drag = auto.mouse_drag_down.call_args[0]
picked = cards[positions.index(drag)]
return picked, record, lookups
@property
def log(self):
return '\n'.join(self.lines)
FLOOR4 = ['伏行深渊', '落泪者们', 'WARP快车谋杀案', '堕落的忧郁']
def test_upstream_takes_the_leftmost_of_equal_weights(self):
self.assertEqual(self.play(self.FLOOR4, 'charge', patched=False)[0], '落泪者们')
def test_charge_team_takes_the_charge_pack(self):
picked, _, _ = self.play(self.FLOOR4, 'charge')
self.assertEqual(picked, 'WARP快车谋杀案')
self.assertIn('patch: 镜牢卡包按体系加分(theme_pack_systems.json', self.log)
self.assertIn('卡包按体系 charge 加分: ', self.log)
self.assertIn('谋杀 -5→1', self.log)
FLOOR1 = ['被遗忘者们', '身无分文的赌徒', '钉与锤']
def test_slow_pack_is_avoided_and_pierce_takes_its_route(self):
self.assertEqual(self.play(self.FLOOR1, 'charge', patched=False)[0], '被遗忘者们')
self.assertEqual(self.play(self.FLOOR1, 'charge')[0], '身无分文的赌徒') # 被遗忘者们 -3
self.assertEqual(self.play(['钉与锤', '身无分文的赌徒'], 'pierce')[0], '身无分文的赌徒')
def test_bleed_team_does_not_take_the_original_warp(self):
# 原版 WARP 只有 1 件流血专属饰品, 加 1 分仍然低于 0 分的卡包
self.assertEqual(self.play(self.FLOOR4, 'bleed')[0], '落泪者们')
def test_audit_records_the_system_bonus(self):
picked, record, _ = self.play(self.FLOOR4, 'charge', audit=True)
args, kwargs = record.call_args
self.assertEqual(args, ('theme_pack', '谋杀', 'preferred'))
# 普通模式: 复刻只在困难出现, 不算进「谋杀」这个键
self.assertEqual(kwargs['system_bonus'], {'packs': ['WARP快车谋杀案'], 'system': 'charge', 'from': -5, 'to': 1})
def test_audit_without_bonus_has_no_system_field(self):
_, record, _ = self.play(self.FLOOR4, 'bleed', audit=True)
self.assertNotIn('system_bonus', record.call_args[1])
def test_unknown_system_keeps_upstream_weights(self):
picked, _, lookups = self.play(self.FLOOR4, 'unknown_system')
self.assertEqual(picked, '落泪者们')
self.assertEqual(lookups[0], example_weights('theme_pack_list_cn'))
def test_env_zero_and_bad_table(self):
self.assertIsNone(ap.install_theme_pack_systems(log=self.lines.append, env={ap.THEME_PACK_SYSTEMS_ENV: '0'}))
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, 'bad.json')
with open(path, 'w', encoding='utf-8') as fh:
fh.write('{}')
self.assertIsNone(ap.install_theme_pack_systems(log=self.lines.append,
env={ap.THEME_PACK_SYSTEMS_ENV: path}))
self.assertIn('[ERROR] [lc_mcp] 卡包体系表读不了', self.log)
def test_upstream_without_the_weight_lookup_is_an_error(self):
with mock.patch('inspect.getsource', return_value='def select_theme_pack(): pass'):
theme_mod = types.ModuleType('tasks.mirror.select_theme_pack')
theme_mod.theme_list = SimpleNamespace()
mirror_mod = types.ModuleType('tasks.mirror.mirror')
mirror_mod.select_theme_pack = lambda *a: None
package = types.ModuleType('tasks.mirror')
package.mirror, package.select_theme_pack = mirror_mod, theme_mod
with mock.patch.dict(sys.modules, {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package,
'tasks.mirror.mirror': mirror_mod,
'tasks.mirror.select_theme_pack': theme_mod}):
self.assertIsNone(ap.install_theme_pack_systems(log=self.lines.append, env={}))
self.assertIn('[ERROR] [lc_mcp] 上游 select_theme_pack 不再从 theme_list.get_effective_theme_pack_list 取权重',
self.log)
def test_current_upstream_source_has_the_weight_lookup(self):
self.assertIn('theme_list.get_effective_theme_pack_list(', THEME.read_text(encoding='utf-8'))
if __name__ == '__main__':
unittest.main()
+30
View File
@@ -180,6 +180,36 @@ class TypedKeyboardRoadTest(unittest.TestCase):
self.assertEqual(self.road.search_road_simple_keyboard(), 'original')
self.road.identify_nodes.assert_not_called()
def test_gives_up_keyboard_after_consecutive_failed_nodes(self):
# 2026-11-14 实机 24/24 没进去: 每个节点白按 5 次键。连续 3 个节点都不行就别再按了
self.install()
self.original.return_value = False
self.entered = [False] * 3 * ap.ROAD_KEY_GIVE_UP
for _ in range(ap.ROAD_KEY_GIVE_UP):
self.assertFalse(self.road.search_road_simple_keyboard())
self.assertIn('连续 3 个节点按键都没进去, 本次任务不再按键寻路', '\n'.join(self.lines))
self.records.assert_any_call('road', None, 'keyboard_off', fails=3)
pressed, recognised = len(self.keys), self.road.identify_nodes.call_count
self.original.reset_mock()
self.assertIs(self.road.search_road_simple_keyboard(), False) # 上游接着走常规寻路
self.assertEqual((len(self.keys), self.road.identify_nodes.call_count), (pressed, recognised))
self.original.assert_not_called()
def test_entering_once_resets_the_failure_count(self):
self.install()
self.original.return_value = False
self.entered = [False] * 6 + [True] + [False] * 6
results = [bool(self.road.search_road_simple_keyboard()) for _ in range(5)]
self.assertEqual(results, [False, False, True, False, False])
self.assertNotIn('不再按键寻路', '\n'.join(self.lines))
def test_falling_back_to_up_and_entering_counts_as_success(self):
self.install()
self.entered = [False] * 3 * (ap.ROAD_KEY_GIVE_UP + 1)
for _ in range(ap.ROAD_KEY_GIVE_UP + 1):
self.assertEqual(self.road.search_road_simple_keyboard(), 'original') # 原 ↑ 进去了
self.assertNotIn('不再按键寻路', '\n'.join(self.lines))
def test_env_switch_leaves_upstream_untouched(self):
self.assertIsNone(self.install(env={ap.TYPED_ROAD_ENV: '0'}))
self.assertIs(self.road.search_road_simple_keyboard, self.original)