合并前复核:补齐急停释放、整轮中止和计划任务时限
This commit is contained in:
+90
-25
@@ -12,6 +12,9 @@ AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_
|
|||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import threading
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
@@ -34,6 +37,7 @@ class KeySpecTest(unittest.TestCase):
|
|||||||
def test_empty_falls_back_to_default(self):
|
def test_empty_falls_back_to_default(self):
|
||||||
self.assertEqual(killswitch._key_spec(''), '<f12>')
|
self.assertEqual(killswitch._key_spec(''), '<f12>')
|
||||||
self.assertEqual(killswitch._key_spec(None), '<f12>')
|
self.assertEqual(killswitch._key_spec(None), '<f12>')
|
||||||
|
self.assertEqual(killswitch._key_spec(' '), '<f12>')
|
||||||
|
|
||||||
|
|
||||||
class InstallTest(unittest.TestCase):
|
class InstallTest(unittest.TestCase):
|
||||||
@@ -74,40 +78,88 @@ class InstallTest(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class ActivateTest(unittest.TestCase):
|
class ActivateTest(unittest.TestCase):
|
||||||
"""按下热键必须真的退出进程,而且只退一次。"""
|
def _grab_handler(self, log=lambda _: None, on_stop=None):
|
||||||
|
|
||||||
def _grab_handler(self):
|
|
||||||
listener = mock.Mock()
|
listener = mock.Mock()
|
||||||
fake_keyboard = mock.Mock()
|
keyboard = mock.Mock()
|
||||||
fake_keyboard.GlobalHotKeys.return_value = listener
|
keyboard.GlobalHotKeys.return_value = listener
|
||||||
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
|
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=keyboard)}):
|
||||||
'pynput.keyboard': fake_keyboard}):
|
killswitch.install(log=log, on_stop=on_stop)
|
||||||
killswitch.install(log=lambda m: None)
|
return next(iter(keyboard.GlobalHotKeys.call_args.args[0].values())), listener
|
||||||
bindings = fake_keyboard.GlobalHotKeys.call_args[0][0]
|
|
||||||
return list(bindings.values())[0], listener
|
|
||||||
|
|
||||||
def test_exits_with_user_abort_code(self):
|
def fire(self, handler, listener):
|
||||||
handler, _ = self._grab_handler()
|
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:
|
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
||||||
|
self.fire(handler, listener)
|
||||||
handler()
|
handler()
|
||||||
fake_exit.assert_called_once_with(killswitch.EXIT_CODE)
|
fake_exit.assert_called_once_with(killswitch.EXIT_CODE)
|
||||||
|
|
||||||
def test_only_fires_once(self):
|
def test_broken_log_cannot_disable_the_hotkey(self):
|
||||||
handler, _ = self._grab_handler()
|
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:
|
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
||||||
handler()
|
self.fire(handler, listener)
|
||||||
handler()
|
fake_exit.assert_called_once_with(130)
|
||||||
handler()
|
log.assert_not_called()
|
||||||
self.assertEqual(fake_exit.call_count, 1, '重复按下不该重复退出')
|
|
||||||
|
|
||||||
def test_logs_that_game_stays_alive(self):
|
def test_releases_input_before_exiting_even_when_cleanup_raises(self):
|
||||||
handler, _ = self._grab_handler()
|
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 = []
|
lines = []
|
||||||
with mock.patch.object(killswitch.os, '_exit'):
|
self._grab_handler(log=lines.append)
|
||||||
handler.__closure__ # 确认是闭包
|
self.assertIn('游戏窗口保留', '\n'.join(lines))
|
||||||
killswitch.install(log=lines.append)
|
|
||||||
# 用新的 logger 重新装一次才拿得到日志,这里只验证消息文案存在
|
def test_real_emergency_exit_is_reported_as_stopped(self):
|
||||||
self.assertTrue(callable(handler))
|
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):
|
class StopTest(unittest.TestCase):
|
||||||
@@ -120,6 +172,19 @@ class StopTest(unittest.TestCase):
|
|||||||
killswitch.stop(listener)
|
killswitch.stop(listener)
|
||||||
listener.stop.assert_called_once()
|
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):
|
def test_stop_swallows_listener_errors(self):
|
||||||
listener = mock.Mock()
|
listener = mock.Mock()
|
||||||
listener.stop.side_effect = RuntimeError('boom')
|
listener.stop.side_effect = RuntimeError('boom')
|
||||||
|
|||||||
Reference in New Issue
Block a user