Files
lc-mcp/tests/test_driver_input.py
T

460 lines
22 KiB
Python

# -*- coding: utf-8 -*-
"""驱动级输入接管。
⛔ 这个模块的每一条"拒绝"都比"接管"更重要: 接管错了会让任务点错地方,
而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。
背景(2026-10-22 实测):
* RDP 独立会话不能靠前台窗口判定, 必须核对进程与 console 会话 ID。
* 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素),
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
"""
import sys
import os
import ast
import inspect
import threading
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from lc_mcp import driver_input as di # noqa: E402
from lc_mcp import aalc_patches as ap # noqa: E402
class PreflightTest(unittest.TestCase):
"""能不能用, 必须说得清楚; 不能用时一条都不能含糊。"""
def _drv(self, dll_ok=True, fg=True, accel=False, console=True):
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = dll_ok
with mock.patch.object(di, 'has_foreground', lambda: fg), \
mock.patch.object(di, 'is_console_session', lambda: console), \
mock.patch.object(di, 'acceleration_on', lambda: accel):
return d.preflight()
def test_ok_when_everything_is_right(self):
ok, why = self._drv()
self.assertTrue(ok)
self.assertEqual(why, 'ok')
def test_refuses_without_driver(self):
ok, why = self._drv(dll_ok=False)
self.assertFalse(ok)
self.assertIn('device_open', why)
def test_refuses_in_a_session_without_foreground(self):
"""RDP 独立会话的典型特征 —— 这种会话里驱动级输入无效。"""
ok, why = self._drv(fg=False)
self.assertFalse(ok)
self.assertIn('前台窗口', why)
def test_remote_session_is_rejected_even_with_foreground(self):
ok, why = self._drv(console=False, fg=True)
self.assertFalse(ok)
self.assertIn('console', why)
def test_refuses_when_acceleration_is_on(self):
ok, why = self._drv(accel=True)
self.assertFalse(ok)
self.assertIn('加速', why)
def test_refuses_missing_dll_file(self):
d = di.DriverInput(dll_path=r'Z:\nope\nope.dll', log=lambda m: None)
self.assertFalse(d.open())
self.assertFalse(d.ready)
class MoveToTest(unittest.TestCase):
"""定位必须是闭环: 发位移 -> 读回 -> 不够再发。不依赖标定常数。"""
def test_converges_when_moves_are_exact(self):
pos = {'v': (0, 0)}
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
def moveR(dx, dy, _):
pos['v'] = (pos['v'][0] + dx, pos['v'][1] + dy)
d._dll.moveR.side_effect = moveR
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertTrue(d.move_to(300, 200))
self.assertEqual(pos['v'], (300, 200))
def test_gives_up_when_moves_do_nothing(self):
"""驱动不理人时不能假称到位 —— 那样会点错地方。"""
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
with mock.patch.object(di, 'get_cursor', lambda: (0, 0)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertFalse(d.move_to(300, 200, iters=4))
def test_tolerance_is_respected(self):
"""已经在容差内就不该再发位移 —— 白折腾还容易引入抖动。"""
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
with mock.patch.object(di, 'get_cursor', lambda: (100, 100)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertTrue(d.move_to(101, 101, tol=1))
self.assertEqual(d._dll.moveR.call_count, 0, '容差内不该发位移')
def test_out_of_tolerance_does_move(self):
"""超出容差就必须尝试移动, 只是驱动不动时要如实返回失败。"""
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
with mock.patch.object(di, 'get_cursor', lambda: (100, 100)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertFalse(d.move_to(105, 105, tol=1, iters=3))
self.assertGreater(d._dll.moveR.call_count, 0)
class ClickTest(unittest.TestCase):
"""没到位置就绝不点。"""
def _drv(self, reachable):
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
return d
def test_clicks_only_after_positioning(self):
pos = {'v': (0, 0)}
d = self._drv(True)
d._dll.moveR.side_effect = lambda dx, dy, _: pos.update(
{'v': (pos['v'][0] + dx, pos['v'][1] + dy)})
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertTrue(d.click(500, 400))
self.assertEqual(pos['v'], (500, 400))
d._dll.mouse_down.assert_called_once_with(1)
d._dll.mouse_up.assert_called_once_with(1)
def test_never_clicks_when_positioning_fails(self):
d = self._drv(False)
with mock.patch.object(di, 'get_cursor', lambda: (0, 0)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertFalse(d.click(500, 400))
d._dll.mouse_down.assert_not_called()
d._dll.mouse_up.assert_not_called()
class InstallTest(unittest.TestCase):
"""接管 AALC 的点击: 条件不满足时**一个都不许改**。"""
def _auto(self):
auto = SimpleNamespace()
auto.input_handler = mock.Mock()
auto.mouse_click = auto.input_handler.mouse_click
return auto
def test_refuses_quietly_when_preflight_fails(self):
auto = self._auto()
before = auto.input_handler
drv = mock.Mock()
drv.preflight.return_value = (False, '不是物理会话')
got = ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda m: None)
self.assertIsNone(got)
self.assertIs(auto.input_handler, before, '条件不满足就不该换 handler')
def test_rebinds_the_aliases_captured_at_init(self):
"""automation.py 初始化时把方法绑成了别名, 光换 handler 影响不到那些别名。"""
auto = self._auto()
old_click = auto.mouse_click
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
got = ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda m: None)
self.assertIs(got, drv)
self.assertIsNot(auto.mouse_click, old_click, '别名必须重绑')
def test_proxy_other_methods_fall_through(self):
"""拖拽/滑动/滚轮等仍走 AALC 原逻辑, 不能被吞掉。"""
handler = mock.Mock()
proxy = ap.DriverClickProxy(handler, mock.Mock(), mock.Mock(), log=lambda m: None)
proxy.mouse_drag(10, 20, 0.5, 0, 100, True)
handler.mouse_drag.assert_called_once()
proxy.wait_pause()
handler.wait_pause.assert_called_once()
class ClientToScreenTest(unittest.TestCase):
def test_uses_client_to_screen(self):
def fake(hwnd, byref_pt):
ptr = byref_pt._obj
ptr.x, ptr.y = ptr.x + 100, ptr.y + 50
return 1
api = mock.Mock()
api.user32.ClientToScreen.side_effect = fake
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
self.assertEqual(di.client_to_screen(123, 7, 9), (107, 59))
def vendor_auto():
"""执行 vendor 的真实接线与交互门方法, 只隔离 Windows 输入后端。"""
root = Path(__file__).resolve().parents[1] / 'vendor/aalc/module/automation'
abstract = ast.parse((root / 'input_handlers/__init__.py').read_text())
abstract.body = [n for n in abstract.body if isinstance(n, ast.ClassDef)]
namespace = {'log': mock.Mock(), 'sleep': lambda _: None, 'time': lambda: 0}
exec(compile(abstract, str(root / 'input_handlers/__init__.py'), 'exec'), namespace)
base = namespace['AbstractInput']
class Handler(base):
def mouse_click(self, *args, **kwargs):
raise AssertionError('旧点击后端不应被调用')
def mouse_click_blank(self, *args, **kwargs):
raise AssertionError('空白点击不应回落到旧后端')
source = ast.parse((root / 'automation.py').read_text())
cls = next(n for n in source.body if isinstance(n, ast.ClassDef) and n.name == 'Automation')
keep = {'init_input', '_run_business_interaction', 'monitor_mouse_click',
'suspend_interactions', 'resume_interactions'}
cls.body = [n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in keep]
cls.keywords = []
namespace = {'__name__': 'module.automation.automation', '__package__': 'module.automation',
'inspect': inspect, 'AbstractInput': base, 'log': mock.Mock(),
'cfg': SimpleNamespace(simulator=False, win_input_type='foreground',
memory_protection=False), 'GATE_WAIT_TIMEOUT': 30}
exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'automation.py'), 'exec'), namespace)
auto = namespace['Automation']()
auto.input_handler = None
auto._input_lock = threading.RLock()
auto._interaction_gate = threading.Event()
auto._interaction_gate.set()
with mock.patch.dict(sys.modules, {'module.automation.input_handlers.input':
SimpleNamespace(Input=Handler)}):
auto.init_input()
return auto, Handler
class DriverWiringTest(unittest.TestCase):
def test_real_business_gate_and_monitor_share_the_input_lock(self):
auto, _ = vendor_auto()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
locked = []
drv.click.side_effect = lambda *a, **k: locked.append(auto._input_lock._is_owned()) or True
ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda _: None)
auto.suspend_interactions()
entered = threading.Event()
wait = auto._interaction_gate.wait
def waiting(*args, **kwargs):
entered.set()
return wait(*args, **kwargs)
with mock.patch.object(auto.input_handler, '_screen_pos', return_value=(10, 20)), \
mock.patch.object(auto._interaction_gate, 'wait', side_effect=waiting):
worker = threading.Thread(target=auto.mouse_click, args=(10, 20), daemon=True)
worker.start()
try:
self.assertTrue(entered.wait(1), '业务点击必须等待交互门')
drv.click.assert_not_called()
# 监控点击允许绕过门, 但仍必须持有同一把锁。
auto.monitor_mouse_click(10, 20)
finally:
auto.resume_interactions()
worker.join(2)
self.assertFalse(worker.is_alive())
self.assertEqual(locked, [True, True])
def test_blank_click_uses_driver_and_move_back_is_honored(self):
auto, _ = vendor_auto()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda _: None)
with mock.patch.object(auto.input_handler, '_screen_pos', return_value=(10, 20)), \
mock.patch.object(di, 'get_cursor', return_value=(90, 80)):
self.assertTrue(auto.mouse_click_blank((1, 2), times=2, move_back=True))
drv.click.assert_called_once_with(10, 20, times=2)
drv.move_to.assert_called_once_with(90, 80)
def test_all_task_and_reinitialization_reinstall_after_init(self):
auto, handler_type = vendor_auto()
scheme = SimpleNamespace(init_game=auto.init_input)
scheme.script_task = lambda: (scheme.init_game(), auto.mouse_click_blank())
original = scheme.init_game
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
with mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1'), \
mock.patch.dict(sys.modules, {'module.automation.input_handlers.input':
SimpleNamespace(Input=handler_type)}), \
mock.patch.object(di, 'DriverInput', return_value=drv), \
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
with ap.driver_click_tasks(scheme, auto, mock.Mock(),
SimpleNamespace(simulator=False), log=lambda _: None):
scheme.script_task()
first = auto.input_handler
scheme.script_task()
self.assertIsNot(auto.input_handler, first)
self.assertIsInstance(auto.input_handler, ap.DriverClickProxy)
self.assertEqual(drv.click.call_count, 2)
self.assertIs(scheme.init_game, original)
def test_actual_task_entry_enables_driver_for_all_and_daily(self):
from lc_mcp import aalc_task
for task, problems in [('all', []), ('daily', []), ('all', ['invalid config'])]:
with self.subTest(task=task, problems=problems):
auto, handler_type = vendor_auto()
auto.clear_img_cache = mock.Mock()
auto.click_element = mock.Mock(return_value=False)
cfg = SimpleNamespace(simulator=False)
scheme = SimpleNamespace(init_game=auto.init_input)
scheme.script_task = lambda: (scheme.init_game(), auto.mouse_click(10, 20))
scheme.Daily_task_wrapper = lambda **kw: lambda: auto.mouse_click(10, 20)
scheme.to_get_reward = scheme.Buy_enkephalin = scheme.Mirror_task = mock.Mock()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
modules = {
'module.automation': SimpleNamespace(auto=auto),
'module.automation.input_handlers.input': SimpleNamespace(Input=handler_type),
'module.config': SimpleNamespace(cfg=cfg),
'module.game_and_screen': SimpleNamespace(screen=mock.Mock()),
'tasks.base': SimpleNamespace(script_task_scheme=scheme),
'tasks.base.retry_monitor': SimpleNamespace(retry_monitor=mock.Mock()),
'tasks.battle': SimpleNamespace(battle=mock.Mock()),
'utils.path_manager': SimpleNamespace(path_manager=mock.Mock()),
}
with mock.patch.dict(sys.modules, modules), \
mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1', LCP_RESTORE_FILE=''), \
mock.patch.object(aalc_task, 'bootstrap'), \
mock.patch.object(aalc_task, 'install_exact_team_match'), \
mock.patch.object(aalc_task, 'install_robust_set_foreground'), \
mock.patch.object(aalc_task, 'WindowGuard'), \
mock.patch.object(aalc_task.killswitch, 'install') as install_hotkey, \
mock.patch.object(aalc_task, 'log'), \
mock.patch.object(aalc_task.preflight, 'collect', return_value={}), \
mock.patch.object(aalc_task.preflight, 'desktop_size', return_value=(1920, 1080)), \
mock.patch.object(aalc_task.preflight, 'check', return_value=problems), \
mock.patch.object(di, 'DriverInput', return_value=drv), \
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
self.assertEqual(aalc_task.run(task, {}), 3 if problems else 0)
install_hotkey.return_value.stop.assert_called_once()
if problems:
drv.click.assert_not_called()
else:
drv.click.assert_called_once_with(10, 20, times=1)
install_hotkey.call_args.kwargs['on_stop']()
drv.emergency_stop.assert_called_once()
def test_disabled_and_simulator_leave_initialization_unchanged(self):
for enabled, simulator in [('0', False), ('1', True)]:
with self.subTest(enabled=enabled, simulator=simulator):
scheme = SimpleNamespace(init_game=mock.Mock())
original = scheme.init_game
with mock.patch.dict(os.environ, LCP_DRIVER_INPUT=enabled):
with ap.driver_click_tasks(scheme, mock.Mock(), mock.Mock(),
SimpleNamespace(simulator=simulator)):
self.assertIs(scheme.init_game, original)
class DriverFailureTest(unittest.TestCase):
def test_emergency_stop_releases_press_and_blocks_subsequent_clicks(self):
drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock()
with mock.patch.object(drv, 'move_to', return_value=True), \
mock.patch.object(di.time, 'sleep', side_effect=lambda _: drv.emergency_stop()):
self.assertFalse(drv.click(10, 20, times=3))
drv._dll.mouse_down.assert_called_once_with(1)
drv._dll.mouse_up.assert_called_with(1)
self.assertFalse(drv.ready)
self.assertFalse(drv.click(30, 40))
self.assertFalse(drv.move_relative(20, 30))
self.assertFalse(drv.down())
drv._dll.moveR.assert_not_called()
self.assertEqual(drv._pressed, set())
def test_release_even_if_sleep_is_interrupted(self):
drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock()
with mock.patch.object(drv, 'move_to', return_value=True), \
mock.patch.object(di.time, 'sleep', side_effect=InterruptedError):
with self.assertRaises(InterruptedError):
drv.click(1, 2)
drv._dll.mouse_up.assert_called_once_with(1)
def test_release_even_if_coordinate_lookup_fails(self):
drv = mock.Mock()
proxy = ap.DriverClickProxy(mock.Mock(), drv, mock.Mock())
with mock.patch.object(proxy, '_screen_pos', side_effect=OSError('closed')):
with self.assertRaises(OSError):
proxy.mouse_up(1, 2)
drv.up.assert_called_once_with(1)
def test_no_physical_click_if_game_cannot_get_foreground(self):
drv = mock.Mock()
handle = SimpleNamespace(hwnd=123, isMinimized=False, setForeground=mock.Mock())
proxy = ap.DriverClickProxy(mock.Mock(), drv, SimpleNamespace(handle=handle), log=lambda _: None)
with mock.patch.object(di, 'is_console_session', return_value=True), \
mock.patch.object(di, 'foreground_window', return_value=999):
self.assertFalse(proxy.mouse_click(1, 2))
drv.click.assert_not_called()
handle.setForeground.assert_called_once()
def test_failed_windows_reads_do_not_become_zero_coordinates(self):
api = mock.Mock()
api.user32.ClientToScreen.return_value = 0
api.user32.GetCursorPos.return_value = 0
api.user32.SystemParametersInfoA.return_value = 0
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
for fn, args in [(di.client_to_screen, (123, 1, 2)), (di.get_cursor, ()),
(di.acceleration_on, ())]:
with self.subTest(function=fn.__name__), self.assertRaises(OSError):
fn(*args)
def test_failed_environment_query_refuses_installation(self):
drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock()
with mock.patch.object(di, 'is_console_session', side_effect=OSError('session query failed')):
ok, reason = drv.preflight()
self.assertFalse(ok)
self.assertIn('session query failed', reason)
def test_dll_without_mouse_exports_is_rejected(self):
drv = di.DriverInput()
with mock.patch.object(di.os.path, 'exists', return_value=True), \
mock.patch.object(di.ctypes, 'CDLL', return_value=SimpleNamespace(device_open=lambda: 1)):
self.assertFalse(drv.open())
self.assertFalse(drv.ready)
def test_console_session_ids_are_compared(self):
api = mock.Mock()
def query(pid, sid):
sid._obj.value = 2
return 1
api.kernel32.ProcessIdToSessionId.side_effect = query
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
for console, expected in [(2, True), (3, False), (0xFFFFFFFF, False)]:
api.kernel32.WTSGetActiveConsoleSessionId.return_value = console
self.assertEqual(di.is_console_session(), expected)
class ForegroundFallbackTest(unittest.TestCase):
def test_none_on_success_still_detaches_after_success_or_failure(self):
for failed in (False, True):
with self.subTest(failed=failed):
handle = SimpleNamespace(hwnd=123, setForeground=mock.Mock(side_effect=OSError))
gui = mock.Mock()
gui.GetForegroundWindow.return_value = 456
gui.SetForegroundWindow.side_effect = OSError if failed else None
process = mock.Mock()
process.GetWindowThreadProcessId.return_value = (11, 22)
process.AttachThreadInput.return_value = None
api = SimpleNamespace(GetCurrentThreadId=lambda: 33)
with mock.patch.dict(sys.modules, win32api=api, win32gui=gui, win32process=process):
ap.install_robust_set_foreground(SimpleNamespace(handle=handle), log=lambda _: None)
handle.setForeground()
self.assertEqual(process.AttachThreadInput.call_args_list,
[mock.call(33, 11, True), mock.call(33, 11, False)])
if __name__ == '__main__':
unittest.main()