合并前复核:补齐急停释放、整轮中止和计划任务时限
This commit is contained in:
@@ -164,6 +164,35 @@ class RunAalcTest(unittest.TestCase):
|
|||||||
self.assertIn('preflight', info)
|
self.assertIn('preflight', info)
|
||||||
self.assertEqual(self.tools(mcp), ['run_task'])
|
self.assertEqual(self.tools(mcp), ['run_task'])
|
||||||
|
|
||||||
|
def test_user_stop_never_retries(self):
|
||||||
|
for status in ({'state': 'stopped', 'exit_code': 130},
|
||||||
|
{'state': 'stopped'}, {'state': 'failed', 'exit_code': 130}):
|
||||||
|
mcp = FakeMcp([status], [DONE])
|
||||||
|
with self.subTest(status=status), self.assertRaises(auto_cycle.UserAborted):
|
||||||
|
self.run_aalc(mcp)
|
||||||
|
self.assertEqual(self.tools(mcp), ['run_task'])
|
||||||
|
|
||||||
|
def test_mirror_emergency_stop_ends_cycle_before_upgrade_or_navigation(self):
|
||||||
|
mcp = FakeMcp([DONE], [{'state': 'stopped', 'exit_code': 130}])
|
||||||
|
poll = auto_cycle.poll_task
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
with mock.patch.object(auto_cycle, 'probe', mcp.probe), \
|
||||||
|
mock.patch.object(auto_cycle, 'poll_task',
|
||||||
|
side_effect=lambda t, s, **kw: poll(t, s, sleep=lambda _: None)), \
|
||||||
|
mock.patch.object(auto_cycle, 'lunacy_guard', return_value=(True, 'ok')), \
|
||||||
|
mock.patch.object(auto_cycle, 'ensure_team1', return_value=True), \
|
||||||
|
mock.patch.object(auto_cycle, 'goto_identities') as navigate, \
|
||||||
|
mock.patch.object(auto_cycle, 'run') as upgrade, \
|
||||||
|
mock.patch('builtins.print'):
|
||||||
|
code = auto_cycle.main(['--mirror', '1', '--report-dir', tmp])
|
||||||
|
report = json.loads(next(Path(tmp).glob('cycle_*.json')).read_text(encoding='utf-8'))
|
||||||
|
self.assertEqual(code, 130)
|
||||||
|
self.assertFalse(report['ok'])
|
||||||
|
self.assertIn('用户停止', report['result'])
|
||||||
|
navigate.assert_not_called()
|
||||||
|
upgrade.assert_not_called()
|
||||||
|
self.assertEqual(self.tools(mcp), ['run_task', 'run_task'])
|
||||||
|
|
||||||
def test_exit_zero_with_errors_is_failure(self):
|
def test_exit_zero_with_errors_is_failure(self):
|
||||||
mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])])
|
mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])])
|
||||||
ok, info = self.run_aalc(mcp)
|
ok, info = self.run_aalc(mcp)
|
||||||
|
|||||||
@@ -300,8 +300,8 @@ class DriverWiringTest(unittest.TestCase):
|
|||||||
|
|
||||||
def test_actual_task_entry_enables_driver_for_all_and_daily(self):
|
def test_actual_task_entry_enables_driver_for_all_and_daily(self):
|
||||||
from lc_mcp import aalc_task
|
from lc_mcp import aalc_task
|
||||||
for task in ('all', 'daily'):
|
for task, problems in [('all', []), ('daily', []), ('all', ['invalid config'])]:
|
||||||
with self.subTest(task=task):
|
with self.subTest(task=task, problems=problems):
|
||||||
auto, handler_type = vendor_auto()
|
auto, handler_type = vendor_auto()
|
||||||
auto.clear_img_cache = mock.Mock()
|
auto.clear_img_cache = mock.Mock()
|
||||||
auto.click_element = mock.Mock(return_value=False)
|
auto.click_element = mock.Mock(return_value=False)
|
||||||
@@ -328,14 +328,21 @@ class DriverWiringTest(unittest.TestCase):
|
|||||||
mock.patch.object(aalc_task, 'install_exact_team_match'), \
|
mock.patch.object(aalc_task, 'install_exact_team_match'), \
|
||||||
mock.patch.object(aalc_task, 'install_robust_set_foreground'), \
|
mock.patch.object(aalc_task, 'install_robust_set_foreground'), \
|
||||||
mock.patch.object(aalc_task, 'WindowGuard'), \
|
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, 'log'), \
|
||||||
mock.patch.object(aalc_task.preflight, 'collect', return_value={}), \
|
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, 'desktop_size', return_value=(1920, 1080)), \
|
||||||
mock.patch.object(aalc_task.preflight, 'check', return_value=[]), \
|
mock.patch.object(aalc_task.preflight, 'check', return_value=problems), \
|
||||||
mock.patch.object(di, 'DriverInput', return_value=drv), \
|
mock.patch.object(di, 'DriverInput', return_value=drv), \
|
||||||
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
|
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
|
||||||
self.assertEqual(aalc_task.run(task, {}), 0)
|
self.assertEqual(aalc_task.run(task, {}), 3 if problems else 0)
|
||||||
drv.click.assert_called_once_with(10, 20, times=1)
|
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):
|
def test_disabled_and_simulator_leave_initialization_unchanged(self):
|
||||||
for enabled, simulator in [('0', False), ('1', True)]:
|
for enabled, simulator in [('0', False), ('1', True)]:
|
||||||
@@ -349,6 +356,21 @@ class DriverWiringTest(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class DriverFailureTest(unittest.TestCase):
|
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):
|
def test_release_even_if_sleep_is_interrupted(self):
|
||||||
drv = di.DriverInput()
|
drv = di.DriverInput()
|
||||||
drv._open, drv._dll = True, mock.Mock()
|
drv._open, drv._dll = True, mock.Mock()
|
||||||
|
|||||||
+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