- driver_input: 只在"原地连点"(与上次点击相差<=4px)时先挪开 10px 再点, 强制产生 MOUSEMOVE; 按下 60→100ms, 到位等待 50→80ms (LCP_DRIVER_PRESS_MS / SETTLE_MS / WIGGLE 可调) - aalc_patches: 「获得E.G.O饰品」弹窗第 3 次起绕过驱动代理改软件点击(pyautogui), 第 8 次发回车, 20 次才中止; 新增 data/team_names.json 覆盖体系默认队名 (LCP_TEAM_NAMES=0 关闭) - docs: 2026-11-15 实测(6 连刷 6/6、键盘 4/4 进入、卡包按体系、镜像迷宫+震颤), ISSUES 状态更新 + I-14 前台被抢 单测: 709 passed。
640 lines
31 KiB
Python
640 lines
31 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""驱动级输入接管。
|
|
|
|
⛔ 这个模块的每一条"拒绝"都比"接管"更重要: 接管错了会让任务点错地方,
|
|
而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。
|
|
|
|
背景(2026-10-22 实测):
|
|
* RDP 独立会话不能靠前台窗口判定, 必须核对进程与 console 会话 ID。
|
|
* 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素),
|
|
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
|
|
"""
|
|
import sys
|
|
import contextlib
|
|
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):
|
|
# 这里只测定位逻辑, 前台校验另有 ForegroundCheckTest
|
|
self.assertTrue(d.click(500, 400, require_foreground=False))
|
|
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, require_foreground=False))
|
|
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, 'exclusive_game'), \
|
|
mock.patch.object(aalc_task, 'headless_hdr_warning') as hdr_warning, \
|
|
mock.patch.object(aalc_task, 'mirror_progress',
|
|
lambda scheme: contextlib.nullcontext(ap.MirrorProgress())), \
|
|
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()
|
|
self.assertEqual(hdr_warning.call_count, int(task == 'all' and not problems))
|
|
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, 'click_point_is_on_foreground', lambda *a, **k: (True, 'ok')), \
|
|
mock.patch.object(di.time, 'sleep', side_effect=lambda _: drv.emergency_stop()):
|
|
# settle=0: 第一次 sleep 是按下后的按住时长, 急停发生在按住期间
|
|
self.assertFalse(drv.click(10, 20, times=3, settle=0))
|
|
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))
|
|
# 急停前的"抖动"移动(见 DriverInput.click 注释 4)允许存在, 急停之后不能再有输入
|
|
moves = drv._dll.moveR.call_count
|
|
self.assertFalse(drv.move_relative(20, 30))
|
|
self.assertFalse(drv.down())
|
|
self.assertEqual(drv._dll.moveR.call_count, moves)
|
|
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, 'click_point_is_on_foreground',
|
|
lambda *a, **k: (True, '')), \
|
|
mock.patch.object(di.time, 'sleep', side_effect=InterruptedError):
|
|
with self.assertRaises(InterruptedError):
|
|
# settle=0 让第一个 sleep 出现在按下之后, 测的才是 try/finally
|
|
drv.click(1, 2, require_foreground=False, settle=0)
|
|
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)])
|
|
|
|
|
|
|
|
def win_api(**functions):
|
|
"""按 API 名替换 driver_input._api 返回的函数。"""
|
|
return mock.patch.object(di, '_api', side_effect=lambda library, name, result, args: functions[name])
|
|
|
|
|
|
def window_rect(left, top, right, bottom):
|
|
def get_window_rect(hwnd, ptr):
|
|
r = ptr._obj
|
|
r.left, r.top, r.right, r.bottom = left, top, right, bottom
|
|
return 1
|
|
return get_window_rect
|
|
|
|
|
|
class ForegroundCheckTest(unittest.TestCase):
|
|
"""位置对却点不上 —— 头号原因是前台不是游戏。
|
|
|
|
2026-10-23 实测: 窗口位置和坐标换算都正确, 但前台是浏览器, 点击全部落到
|
|
浏览器里, 而旧版 click() 照样返回 True。这组测试守住"必须拒绝"这一条。
|
|
"""
|
|
|
|
def _drv(self):
|
|
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
|
|
d._dll = mock.Mock()
|
|
d._open = True
|
|
return d
|
|
|
|
def test_rejects_when_no_foreground_window(self):
|
|
with mock.patch.object(di, 'foreground_window', return_value=None):
|
|
ok, why = di.click_point_is_on_foreground(100, 100)
|
|
self.assertFalse(ok)
|
|
self.assertIn('前台窗口', why)
|
|
|
|
def test_rejects_when_point_outside_foreground_window(self):
|
|
with mock.patch.object(di, 'foreground_window', return_value=12345), \
|
|
win_api(GetWindowRect=window_rect(0, 0, 50, 50)):
|
|
ok, why = di.click_point_is_on_foreground(999, 999)
|
|
self.assertFalse(ok)
|
|
self.assertIn('不在前台窗口内', why)
|
|
|
|
def test_accepts_when_point_inside_foreground_window(self):
|
|
with mock.patch.object(di, 'foreground_window', return_value=12345), \
|
|
win_api(GetWindowRect=window_rect(0, 0, 1920, 1080)):
|
|
ok, why = di.click_point_is_on_foreground(500, 500)
|
|
self.assertTrue(ok)
|
|
self.assertEqual(why, 'ok')
|
|
|
|
def test_click_refuses_when_check_fails(self):
|
|
"""校验不过 -> 一个按键都不许发。"""
|
|
pos = {'v': (500, 400)}
|
|
d = self._drv()
|
|
d._dll.moveR.side_effect = lambda dx, dy, _: None
|
|
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
|
mock.patch.object(di.time, 'sleep', lambda s: None), \
|
|
mock.patch.object(di, 'click_point_is_on_foreground',
|
|
lambda *a, **k: (False, '')):
|
|
self.assertFalse(d.click(500, 400))
|
|
d._dll.mouse_down.assert_not_called()
|
|
d._dll.mouse_up.assert_not_called()
|
|
|
|
def test_click_proceeds_when_check_passes(self):
|
|
pos = {'v': (500, 400)}
|
|
d = self._drv()
|
|
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
|
mock.patch.object(di.time, 'sleep', lambda s: None), \
|
|
mock.patch.object(di, 'click_point_is_on_foreground',
|
|
lambda *a, **k: (True, '')):
|
|
self.assertTrue(d.click(500, 400))
|
|
d._dll.mouse_down.assert_called_once_with(1)
|
|
d._dll.mouse_up.assert_called_once_with(1)
|
|
|
|
def test_press_duration_is_passed_through(self):
|
|
"""按下时长必须真的用上 —— 30ms 在掉帧时会漏点。"""
|
|
pos = {'v': (500, 400)}
|
|
d = self._drv()
|
|
slept = []
|
|
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
|
mock.patch.object(di.time, 'sleep', lambda s: slept.append(s)), \
|
|
mock.patch.object(di, 'click_point_is_on_foreground',
|
|
lambda *a, **k: (True, '')):
|
|
d.click(500, 400, press_ms=120, settle=0)
|
|
self.assertIn(0.12, slept, '按下时长没生效')
|
|
|
|
def test_settle_delay_happens_before_press(self):
|
|
"""定位成功到按下之间要有间隔, 否则游戏把这次点击算在旧位置。"""
|
|
pos = {'v': (500, 400)}
|
|
d = self._drv()
|
|
order = []
|
|
d._dll.mouse_down.side_effect = lambda b: order.append('down')
|
|
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
|
mock.patch.object(di, 'click_point_is_on_foreground',
|
|
lambda *a, **k: (True, '')), \
|
|
mock.patch.object(di.time, 'sleep',
|
|
lambda s: order.append('sleep%.2f' % s)):
|
|
d.click(500, 400, settle=0.08)
|
|
self.assertIn('down', order)
|
|
self.assertTrue(any(x.startswith('sleep') for x in order[:order.index('down')]),
|
|
'按下之前必须有 sleep')
|
|
|
|
class HwndForegroundCheckTest(unittest.TestCase):
|
|
"""句柄级前台校验。
|
|
|
|
⛔ 为什么不能只比矩形(2026-10-23 实测): 把浏览器切到前台, 点游戏里同一个
|
|
坐标, 只判断"点在不在前台窗口矩形内"的话**照样通过** —— 因为那个屏幕坐标
|
|
同时也落在浏览器窗口的矩形里。窗口重叠时几何判断毫无意义。
|
|
|
|
给了 hwnd 就必须要求前台窗口就是它。
|
|
"""
|
|
|
|
def test_accepts_when_foreground_is_the_target(self):
|
|
with mock.patch.object(di, 'foreground_window', return_value=999):
|
|
ok, why = di.click_point_is_on_foreground(100, 100, 999)
|
|
self.assertTrue(ok)
|
|
self.assertEqual(why, 'ok')
|
|
|
|
def test_accepts_child_window_of_target(self):
|
|
"""游戏可能有子窗口拿到焦点, 也算在目标窗口上。"""
|
|
is_child = mock.Mock(return_value=True)
|
|
with mock.patch.object(di, 'foreground_window', return_value=1000), \
|
|
win_api(IsChild=is_child):
|
|
ok, _ = di.click_point_is_on_foreground(100, 100, 999)
|
|
is_child.assert_called_once_with(999, 1000)
|
|
self.assertTrue(ok)
|
|
|
|
def test_rejects_when_foreground_is_another_window(self):
|
|
titles = {1000: 'Browser', 999: 'LimbusCompany'}
|
|
with mock.patch.object(di, 'foreground_window', return_value=1000), \
|
|
win_api(IsChild=mock.Mock(return_value=False)), \
|
|
mock.patch.object(di, 'window_title', side_effect=titles.get):
|
|
ok, why = di.click_point_is_on_foreground(100, 100, 999)
|
|
self.assertFalse(ok)
|
|
self.assertIn('前台不是目标窗口', why)
|
|
self.assertIn('Browser', why)
|
|
|
|
def test_bind_window_is_used_by_click(self):
|
|
"""绑定窗口后, click() 必须走句柄级校验。"""
|
|
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
|
|
d._dll = mock.Mock()
|
|
d._open = True
|
|
d.bind_window(4242)
|
|
self.assertEqual(d.hwnd, 4242)
|
|
seen = {}
|
|
|
|
def fake_check(sx, sy, hwnd=None):
|
|
seen['hwnd'] = hwnd
|
|
return False, '前台不是目标窗口'
|
|
|
|
with mock.patch.object(di, 'get_cursor', lambda: (10, 10)), \
|
|
mock.patch.object(di, 'click_point_is_on_foreground', fake_check), \
|
|
mock.patch.object(di.time, 'sleep', lambda s: None):
|
|
self.assertFalse(d.click(10, 10))
|
|
self.assertEqual(seen['hwnd'], 4242, 'click 没把绑定的句柄传下去')
|
|
d._dll.mouse_down.assert_not_called()
|
|
|
|
def test_proxy_rebinds_current_window_before_each_click(self):
|
|
"""游戏重启后句柄会变; 代理复用时若仍拿安装时的旧句柄, 前台校验会拒绝所有点击。"""
|
|
drv = di.DriverInput(dll_path='X.dll', log=lambda m: None).bind_window(111)
|
|
handle = SimpleNamespace(hwnd=222, 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=222), \
|
|
mock.patch.object(di, 'client_to_screen', return_value=(5, 6)):
|
|
self.assertEqual(proxy._screen_pos(1, 2), (5, 6))
|
|
self.assertEqual(drv.hwnd, 222)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|