复核驱动输入与窗口补丁,修复接管互斥和异常清理
This commit is contained in:
@@ -107,12 +107,51 @@ class BackgroundRestoreTest(unittest.TestCase):
|
|||||||
engine.screen = mock.Mock()
|
engine.screen = mock.Mock()
|
||||||
engine.auto.input_handler.pos_offset.return_value = (100, 200)
|
engine.auto.input_handler.pos_offset.return_value = (100, 200)
|
||||||
engine._prepare_input = mock.Mock()
|
engine._prepare_input = mock.Mock()
|
||||||
with mock.patch('pyautogui.moveTo'), mock.patch('pyautogui.mouseDown'), \
|
with mock.patch.dict(sys.modules, pyautogui=mock.Mock()), \
|
||||||
mock.patch('pyautogui.mouseUp'), \
|
|
||||||
mock.patch('lc_mcp.aalc_engine.time.sleep'):
|
mock.patch('lc_mcp.aalc_engine.time.sleep'):
|
||||||
engine.click(100, 200)
|
engine.click(100, 200)
|
||||||
engine.screen.handle.set_window_transparent.assert_not_called()
|
engine.screen.handle.set_window_transparent.assert_not_called()
|
||||||
|
|
||||||
|
def test_window_cleanup_covers_setup_release_and_restore_failures(self):
|
||||||
|
constants = SimpleNamespace(WM_MOUSEMOVE=512, WM_LBUTTONDOWN=513, WM_LBUTTONUP=514)
|
||||||
|
for action in ('click', 'drag'):
|
||||||
|
for stage in ('move_window', 'activate', 'move_message', 'pre_press_sleep',
|
||||||
|
'release', 'restore'):
|
||||||
|
with self.subTest(action=action, stage=stage):
|
||||||
|
engine = AalcEngine.__new__(AalcEngine)
|
||||||
|
engine.cfg = SimpleNamespace(simulator=False, win_input_type='window_move')
|
||||||
|
engine.auto, engine.screen = mock.Mock(), mock.Mock()
|
||||||
|
engine.auto.input_handler._set_window_pos.return_value = (20, 30)
|
||||||
|
engine._grab = mock.Mock(return_value=SimpleNamespace(width=800, height=600))
|
||||||
|
engine._background_mouse = mock.Mock()
|
||||||
|
engine._restore_background_position = mock.Mock()
|
||||||
|
failure = RuntimeError(stage)
|
||||||
|
if stage == 'move_window':
|
||||||
|
engine.auto.input_handler._set_window_pos.side_effect = failure
|
||||||
|
elif stage == 'activate':
|
||||||
|
engine.auto.input_handler.set_active.side_effect = failure
|
||||||
|
elif stage == 'restore':
|
||||||
|
engine._restore_background_position.side_effect = failure
|
||||||
|
elif stage in ('move_message', 'release'):
|
||||||
|
message = 512 if stage == 'move_message' else 514
|
||||||
|
def send(kind, *args, **kwargs):
|
||||||
|
if kind == message:
|
||||||
|
raise failure
|
||||||
|
engine._background_mouse.side_effect = send
|
||||||
|
with mock.patch.dict(sys.modules, win32con=constants), \
|
||||||
|
mock.patch('lc_mcp.aalc_engine.time.sleep') as sleep:
|
||||||
|
if stage == 'pre_press_sleep':
|
||||||
|
sleep.side_effect = failure
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
if action == 'click':
|
||||||
|
engine.click(100, 200)
|
||||||
|
else:
|
||||||
|
engine.drag(100, 100, 100, 300)
|
||||||
|
self.assertEqual(engine.screen.handle.set_window_transparent.call_args_list,
|
||||||
|
[mock.call(True), mock.call(False)])
|
||||||
|
if stage != 'move_window':
|
||||||
|
engine._restore_background_position.assert_called_once_with((20, 30))
|
||||||
|
|
||||||
def test_restore_uses_noactivate_and_preserves_foreground(self):
|
def test_restore_uses_noactivate_and_preserves_foreground(self):
|
||||||
gui = mock.Mock()
|
gui = mock.Mock()
|
||||||
gui.GetForegroundWindow.return_value = 123
|
gui.GetForegroundWindow.return_value = 123
|
||||||
|
|||||||
@@ -703,6 +703,53 @@ class RenderCheckTest(QuietLogMixin, unittest.TestCase):
|
|||||||
self.assertFalse(cm.render_ok())
|
self.assertFalse(cm.render_ok())
|
||||||
|
|
||||||
|
|
||||||
|
class CaptureApiTest(QuietLogMixin, unittest.TestCase):
|
||||||
|
def test_window_capture_uses_printwindow_and_releases_gdi_objects(self):
|
||||||
|
import ctypes
|
||||||
|
for outcome in (1, 0, OSError('capture failed')):
|
||||||
|
with self.subTest(outcome=outcome):
|
||||||
|
api, gui, ui = mock.Mock(), mock.Mock(), mock.Mock()
|
||||||
|
gui.GetClientRect.return_value = (0, 0, 1280, 720)
|
||||||
|
gui.IsIconic.return_value = False
|
||||||
|
source = ui.CreateDCFromHandle.return_value
|
||||||
|
target = source.CreateCompatibleDC.return_value
|
||||||
|
bitmap = ui.CreateBitmap.return_value
|
||||||
|
previous = target.SelectObject.return_value
|
||||||
|
if isinstance(outcome, Exception):
|
||||||
|
api.user32.PrintWindow.side_effect = outcome
|
||||||
|
else:
|
||||||
|
api.user32.PrintWindow.return_value = outcome
|
||||||
|
with mock.patch.dict(sys.modules, win32gui=gui, win32ui=ui), \
|
||||||
|
mock.patch.object(ctypes, 'windll', api, create=True):
|
||||||
|
self.assertEqual(cm.window_blit_ok(123), outcome == 1)
|
||||||
|
api.user32.PrintWindow.assert_called_once_with(123, target.GetSafeHdc(), 3)
|
||||||
|
target.BitBlt.assert_not_called()
|
||||||
|
bitmap.CreateCompatibleBitmap.assert_called_once_with(source, 1280, 720)
|
||||||
|
self.assertEqual(target.SelectObject.call_args_list,
|
||||||
|
[mock.call(bitmap), mock.call(previous)])
|
||||||
|
target.DeleteDC.assert_called_once()
|
||||||
|
gui.DeleteObject.assert_called_once_with(bitmap.GetHandle())
|
||||||
|
source.DeleteDC.assert_not_called()
|
||||||
|
gui.ReleaseDC.assert_called_once_with(123, gui.GetWindowDC())
|
||||||
|
|
||||||
|
def test_missing_dc_and_minimized_window_cannot_pass_capture(self):
|
||||||
|
gui = mock.Mock()
|
||||||
|
gui.IsIconic.return_value = True
|
||||||
|
with mock.patch.dict(sys.modules, win32gui=gui):
|
||||||
|
self.assertFalse(cm.window_blit_ok(123))
|
||||||
|
gui.GetWindowDC.assert_not_called()
|
||||||
|
self.assertFalse(cm._blit_ok(0))
|
||||||
|
|
||||||
|
def test_screen_fallback_uses_bitblt(self):
|
||||||
|
gui, ui = mock.Mock(), mock.Mock()
|
||||||
|
source = ui.CreateDCFromHandle.return_value
|
||||||
|
target = source.CreateCompatibleDC.return_value
|
||||||
|
with mock.patch.dict(sys.modules, win32gui=gui, win32ui=ui):
|
||||||
|
self.assertTrue(cm.screen_blit_ok())
|
||||||
|
target.BitBlt.assert_called_once_with((0, 0), (64, 64), source, (0, 0), 0x00CC0020)
|
||||||
|
gui.ReleaseDC.assert_called_once_with(0, gui.GetDC())
|
||||||
|
|
||||||
|
|
||||||
class SessionTableTest(QuietLogMixin, unittest.TestCase):
|
class SessionTableTest(QuietLogMixin, unittest.TestCase):
|
||||||
"""解析 `query session` —— 用来区分"截不到图"到底是哪种情况。
|
"""解析 `query session` —— 用来区分"截不到图"到底是哪种情况。
|
||||||
|
|
||||||
|
|||||||
+252
-8
@@ -5,14 +5,18 @@
|
|||||||
而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。
|
而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。
|
||||||
|
|
||||||
背景(2026-10-22 实测):
|
背景(2026-10-22 实测):
|
||||||
* 在 RDP 独立会话里, 罗技驱动 moveR 完全不生效(22 次采样光标纹丝不动),
|
* RDP 独立会话不能靠前台窗口判定, 必须核对进程与 console 会话 ID。
|
||||||
切到物理 console 会话后立刻正常 —— GetForegroundWindow()==0 是判据。
|
|
||||||
* 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素),
|
* 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素),
|
||||||
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
|
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
|
||||||
"""
|
"""
|
||||||
import sys
|
import sys
|
||||||
|
import os
|
||||||
|
import ast
|
||||||
|
import inspect
|
||||||
|
import threading
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
@@ -23,11 +27,12 @@ from lc_mcp import aalc_patches as ap # noqa: E402
|
|||||||
class PreflightTest(unittest.TestCase):
|
class PreflightTest(unittest.TestCase):
|
||||||
"""能不能用, 必须说得清楚; 不能用时一条都不能含糊。"""
|
"""能不能用, 必须说得清楚; 不能用时一条都不能含糊。"""
|
||||||
|
|
||||||
def _drv(self, dll_ok=True, fg=True, accel=False):
|
def _drv(self, dll_ok=True, fg=True, accel=False, console=True):
|
||||||
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
|
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
|
||||||
d._dll = mock.Mock()
|
d._dll = mock.Mock()
|
||||||
d._open = dll_ok
|
d._open = dll_ok
|
||||||
with mock.patch.object(di, 'has_foreground', lambda: fg), \
|
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):
|
mock.patch.object(di, 'acceleration_on', lambda: accel):
|
||||||
return d.preflight()
|
return d.preflight()
|
||||||
|
|
||||||
@@ -46,7 +51,11 @@ class PreflightTest(unittest.TestCase):
|
|||||||
ok, why = self._drv(fg=False)
|
ok, why = self._drv(fg=False)
|
||||||
self.assertFalse(ok)
|
self.assertFalse(ok)
|
||||||
self.assertIn('前台窗口', why)
|
self.assertIn('前台窗口', why)
|
||||||
self.assertIn('RDP', 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):
|
def test_refuses_when_acceleration_is_on(self):
|
||||||
ok, why = self._drv(accel=True)
|
ok, why = self._drv(accel=True)
|
||||||
@@ -141,7 +150,7 @@ class InstallTest(unittest.TestCase):
|
|||||||
"""接管 AALC 的点击: 条件不满足时**一个都不许改**。"""
|
"""接管 AALC 的点击: 条件不满足时**一个都不许改**。"""
|
||||||
|
|
||||||
def _auto(self):
|
def _auto(self):
|
||||||
auto = mock.Mock()
|
auto = SimpleNamespace()
|
||||||
auto.input_handler = mock.Mock()
|
auto.input_handler = mock.Mock()
|
||||||
auto.mouse_click = auto.input_handler.mouse_click
|
auto.mouse_click = auto.input_handler.mouse_click
|
||||||
return auto
|
return auto
|
||||||
@@ -178,16 +187,251 @@ class InstallTest(unittest.TestCase):
|
|||||||
class ClientToScreenTest(unittest.TestCase):
|
class ClientToScreenTest(unittest.TestCase):
|
||||||
|
|
||||||
def test_uses_client_to_screen(self):
|
def test_uses_client_to_screen(self):
|
||||||
pt = mock.Mock(x=0, y=0)
|
|
||||||
|
|
||||||
def fake(hwnd, byref_pt):
|
def fake(hwnd, byref_pt):
|
||||||
ptr = byref_pt._obj
|
ptr = byref_pt._obj
|
||||||
ptr.x, ptr.y = ptr.x + 100, ptr.y + 50
|
ptr.x, ptr.y = ptr.x + 100, ptr.y + 50
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
with mock.patch.object(di.ctypes.windll.user32, 'ClientToScreen', fake):
|
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))
|
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 in ('all', 'daily'):
|
||||||
|
with self.subTest(task=task):
|
||||||
|
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, '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=[]), \
|
||||||
|
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, {}), 0)
|
||||||
|
drv.click.assert_called_once_with(10, 20, times=1)
|
||||||
|
|
||||||
|
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_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__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user