Files
lc-mcp/tests/test_key_hold.py
ywsandClaude Opus 5.5 96a31bc1ae 按台账修镜牢: 饰品弹窗兜底、按键扫描码、卡包按体系加分
按 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>
2026-11-15 01:24:46 +00:00

212 lines
8.3 KiB
Python

# -*- 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()