196 lines
7.9 KiB
Python
196 lines
7.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""急停热键。
|
|
|
|
背景(2026-10-22, 用户提问"你执行脚本的时候我鼠标没法动,我怎么停止呢"):
|
|
|
|
驱动级点击是闭环定位 —— 手一动, 下一次点击前会读到新位置、算出偏差、再把你推回
|
|
目标点。所以任务跑起来时鼠标是"拔河"状态, 用户没法用鼠标去点停止按钮。键盘不受
|
|
影响, 所以急停必须走键盘。
|
|
|
|
AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_interface.py)
|
|
里注册, lc_mcp 走命令行子进程, 那条路径上没有热键监听。这是本模块存在的原因。
|
|
"""
|
|
import os
|
|
import sys
|
|
import threading
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest import mock
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
from lc_mcp import killswitch # noqa: E402
|
|
|
|
|
|
class KeySpecTest(unittest.TestCase):
|
|
|
|
def test_wraps_plain_name(self):
|
|
self.assertEqual(killswitch._key_spec('f12'), '<f12>')
|
|
|
|
def test_keeps_already_wrapped(self):
|
|
self.assertEqual(killswitch._key_spec('<f11>'), '<f11>')
|
|
|
|
def test_lowercases_and_trims(self):
|
|
self.assertEqual(killswitch._key_spec(' F12 '), '<f12>')
|
|
|
|
def test_empty_falls_back_to_default(self):
|
|
self.assertEqual(killswitch._key_spec(''), '<f12>')
|
|
self.assertEqual(killswitch._key_spec(None), '<f12>')
|
|
self.assertEqual(killswitch._key_spec(' '), '<f12>')
|
|
|
|
|
|
class InstallTest(unittest.TestCase):
|
|
"""装不上不能把任务带崩,但必须说清楚怎么应急。"""
|
|
|
|
def test_reports_when_pynput_is_missing(self):
|
|
lines = []
|
|
with mock.patch.dict(sys.modules, {'pynput': None}):
|
|
got = killswitch.install(log=lines.append, key='f12')
|
|
self.assertIsNone(got)
|
|
joined = '\n'.join(lines)
|
|
self.assertIn('急停热键不可用', joined)
|
|
self.assertIn('Ctrl+Alt+Del', joined, '必须给出应急手段')
|
|
|
|
def test_registers_the_configured_key(self):
|
|
listener = mock.Mock()
|
|
listener.daemon = False
|
|
fake_keyboard = mock.Mock()
|
|
fake_keyboard.GlobalHotKeys.return_value = listener
|
|
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
|
|
'pynput.keyboard': fake_keyboard}):
|
|
got = killswitch.install(log=lambda m: None, key='f11')
|
|
self.assertIs(got, listener)
|
|
fake_keyboard.GlobalHotKeys.assert_called_once()
|
|
self.assertIn('<f11>', fake_keyboard.GlobalHotKeys.call_args[0][0])
|
|
listener.start.assert_called_once()
|
|
self.assertTrue(listener.daemon)
|
|
|
|
def test_env_var_overrides_default_key(self):
|
|
listener = mock.Mock()
|
|
fake_keyboard = mock.Mock()
|
|
fake_keyboard.GlobalHotKeys.return_value = listener
|
|
with mock.patch.dict(os.environ, {'LCP_KILL_KEY': 'pause'}), \
|
|
mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
|
|
'pynput.keyboard': fake_keyboard}):
|
|
killswitch.install(log=lambda m: None)
|
|
self.assertIn('<pause>', fake_keyboard.GlobalHotKeys.call_args[0][0])
|
|
|
|
|
|
class ActivateTest(unittest.TestCase):
|
|
def _grab_handler(self, log=lambda _: None, on_stop=None):
|
|
listener = mock.Mock()
|
|
keyboard = mock.Mock()
|
|
keyboard.GlobalHotKeys.return_value = listener
|
|
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=keyboard)}):
|
|
killswitch.install(log=log, on_stop=on_stop)
|
|
return next(iter(keyboard.GlobalHotKeys.call_args.args[0].values())), listener
|
|
|
|
def fire(self, handler, listener):
|
|
handler()
|
|
listener._lc_state['worker'].join(2)
|
|
self.assertFalse(listener._lc_state['worker'].is_alive())
|
|
|
|
def test_exits_with_user_abort_code_and_only_fires_once(self):
|
|
handler, listener = self._grab_handler()
|
|
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
|
self.fire(handler, listener)
|
|
handler()
|
|
fake_exit.assert_called_once_with(killswitch.EXIT_CODE)
|
|
|
|
def test_broken_log_cannot_disable_the_hotkey(self):
|
|
log = mock.Mock()
|
|
handler, listener = self._grab_handler(log=log)
|
|
log.reset_mock()
|
|
log.side_effect = OSError('closed log')
|
|
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
|
self.fire(handler, listener)
|
|
fake_exit.assert_called_once_with(130)
|
|
log.assert_not_called()
|
|
|
|
def test_releases_input_before_exiting_even_when_cleanup_raises(self):
|
|
calls = []
|
|
def cleanup():
|
|
calls.append('release')
|
|
raise OSError('driver disconnected')
|
|
handler, listener = self._grab_handler(on_stop=cleanup)
|
|
# 不让测试线程输出预期的异常 traceback。
|
|
with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: calls.append(code)), \
|
|
mock.patch.object(threading, 'excepthook'):
|
|
self.fire(handler, listener)
|
|
self.assertEqual(calls, ['release', 130])
|
|
|
|
def test_hung_cleanup_cannot_block_exit_deadline(self):
|
|
release, exited = threading.Event(), threading.Event()
|
|
handler, listener = self._grab_handler(on_stop=release.wait)
|
|
with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: exited.set()):
|
|
handler()
|
|
try:
|
|
self.assertTrue(exited.wait(2), '清理卡住也必须触发强退')
|
|
finally:
|
|
release.set()
|
|
listener._lc_state['worker'].join(2)
|
|
|
|
def test_startup_message_explains_game_is_kept(self):
|
|
lines = []
|
|
self._grab_handler(log=lines.append)
|
|
self.assertIn('游戏窗口保留', '\n'.join(lines))
|
|
|
|
def test_real_emergency_exit_is_reported_as_stopped(self):
|
|
from lc_mcp.tasks import TaskRunner
|
|
child = """
|
|
import json, os, sys, time
|
|
from types import SimpleNamespace
|
|
from lc_mcp import killswitch
|
|
from lc_mcp.aalc_task import RESTORE_ENV
|
|
class Listener:
|
|
def __init__(self, bindings): self.activate = next(iter(bindings.values()))
|
|
def start(self): pass
|
|
sys.modules['pynput'] = SimpleNamespace(keyboard=SimpleNamespace(GlobalHotKeys=Listener))
|
|
listener = killswitch.install(log=lambda msg: None)
|
|
with open(os.environ[RESTORE_ENV], 'w') as f: json.dump({'set_mirror_count': 1}, f)
|
|
listener.activate()
|
|
time.sleep(10)
|
|
"""
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
runner = TaskRunner(tmp, argv_factory=lambda t, p: [sys.executable, '-c', child])
|
|
self.assertTrue(runner.start('mirror', {'count': 2})['ok'])
|
|
self.addCleanup(runner.proc.kill)
|
|
runner.proc.wait(timeout=5)
|
|
status = runner.status()
|
|
self.assertEqual((status['state'], status['exit_code']), ('stopped', 130))
|
|
self.assertTrue(status['pending_restore'], '强退保留配置恢复文件, 下次启动前由服务处理')
|
|
|
|
|
|
class StopTest(unittest.TestCase):
|
|
|
|
def test_stop_is_safe_on_none(self):
|
|
killswitch.stop(None) # 不该抛
|
|
|
|
def test_stop_calls_listener(self):
|
|
listener = mock.Mock()
|
|
killswitch.stop(listener)
|
|
listener.stop.assert_called_once()
|
|
|
|
def test_listening_stops_on_return_and_exception(self):
|
|
for failure in (False, True):
|
|
listener = mock.Mock()
|
|
with self.subTest(failure=failure), \
|
|
mock.patch.object(killswitch, 'install', return_value=listener):
|
|
try:
|
|
with killswitch.listening():
|
|
if failure:
|
|
raise RuntimeError('task failed')
|
|
except RuntimeError:
|
|
pass
|
|
listener.stop.assert_called_once()
|
|
|
|
def test_stop_swallows_listener_errors(self):
|
|
listener = mock.Mock()
|
|
listener.stop.side_effect = RuntimeError('boom')
|
|
killswitch.stop(listener) # 不该抛
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|