普通镜牢转交 AALC,核对镜牢实际完成局数,合成与任务互斥

Browse Source
转交与互斥(原未提交改动,合入选队分支后提交):
- MCP 初始化说明和工具描述引导常规日常/领奖/普通镜牢走
  task_status -> run_task -> 轮询;jev_mirror_agent 默认转交 AALC,
  明确的速通配置、决策模型或未完成速通局仍走逐步模式。
- 新增 ~/lc_mcp/game.lock:run_task 子进程与模块合成脚本互斥,
  合成脚本另查 task_status,状态不明时不接管游戏。
- all 任务的 HDR 提示无 GUI 时直接确认并记录;预检按窗口位置
  决定是否计标题栏,set_windows=false 跳过;levelup card/weakest
  同步失败返回非零。急停提示改为 End 键。

镜牢结果(对接文档指出的缺口):
- 预检拒绝空队列和没有适用当前难度队伍的配置:AALC 会一局不打
  就以 0 退出。可用判定与 Mirror_task 的固定用途规则一致。
- 监听 mirror_signal 统计实际完成局数;少于应打局数记 [ERROR]
  并以退出码 4 结束,task_status 为 failed。
- mirror 指定 count 时临时关闭 infinite_dungeons(否则次数变成
  9999),原值写入恢复文件,结束或强杀后写回。

验证:Linux / Python 3.12 全套 507 项通过;git diff --check 通过。
用上游真实 Mirror_task 回放了无可用队伍和正常完成两种情况;
Windows 实机仍需回归。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-11-14 03:27:03 +00:00
co-authored by Claude Opus 5.5
parent 1aa823ea2e
commit 5fdb9fd221
17 changed files with 904 additions and 46 deletions
+154
View File
@@ -0,0 +1,154 @@
"""Ordinary mirror requests delegate to AALC without entering the click loop."""
import contextlib
import io
import json
import os
from pathlib import Path
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
import jev_mirror_agent as agent
from mcp_session import SessionTimeout
from run_state import save_json
class AutomationDispatchTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.home = Path(folder.name)
for patch in (mock.patch.object(agent, 'RUNTIME_HOME', self.home),
mock.patch.object(agent, 'STOP_FILE', self.home / 'JEV_STOP'),
mock.patch.dict(os.environ, {'LC_FIXED_FALLBACK': '0'})):
patch.start()
self.addCleanup(patch.stop)
def workflow(self, **overrides):
args = dict(workflow='auto', config=None, decision_engine=None, new_run=False, resume=False)
args.update(overrides)
return agent.execution_workflow(SimpleNamespace(**args))
def test_ordinary_request_defaults_to_aalc(self):
self.assertEqual(self.workflow(), 'aalc')
def test_special_requirements_preserve_speedrun(self):
for args in ({'config': 'jev.json'}, {'decision_engine': 'executor'}, {'resume': True},
{'workflow': 'speedrun'}):
with self.subTest(args=args):
self.assertEqual(self.workflow(**args), 'speedrun')
save_json(self.home / 'mirror_current_run.json', {'status': 'requires_decision'})
self.assertEqual(self.workflow(), 'speedrun')
self.assertEqual(self.workflow(new_run=True), 'aalc')
def delegate(self, current, started=None, **kwargs):
bridge = mock.Mock()
bridge.call.side_effect = [current, started or {'ok': True, 'log': 'new.log', 'task': 'mirror'}]
with mock.patch.object(agent, 'Bridge', return_value=bridge):
result = agent.delegate_mirror(**kwargs)
bridge.close.assert_called_once()
return result, bridge
def test_launches_only_mirror_and_returns_monitoring_contract(self):
result, bridge = self.delegate({'ok': True, 'state': 'idle'})
self.assertEqual(result['state'], 'delegated')
self.assertEqual(result['next_call']['tool'], 'task_status')
self.assertEqual(bridge.call.call_args_list, [mock.call('task_status', {'lines': 30}),
mock.call('run_task', {'task': 'mirror', 'count': 1})])
run = json.loads((self.home / 'mirror_current_run.json').read_text())
self.assertFalse(run['dungeon_completed'])
self.assertFalse(run['final_reward_claimed'])
self.assertEqual(self.workflow(resume=True), 'aalc')
def test_running_mirror_is_monitored_without_duplicate_start(self):
result, bridge = self.delegate({'ok': True, 'state': 'running', 'task': 'mirror'})
self.assertEqual(result['state'], 'monitoring')
self.assertEqual(bridge.call.call_count, 1)
def test_other_running_task_is_not_stopped_or_replaced(self):
result, bridge = self.delegate({'ok': True, 'state': 'running', 'task': 'daily'})
self.assertEqual(result['state'], 'busy')
self.assertEqual(bridge.call.call_count, 1)
def test_user_stop_never_restarts_without_new_request(self):
for current in ({'ok': True, 'state': 'stopped', 'task': 'mirror'},
{'ok': True, 'state': 'failed', 'exit_code': 130}):
with self.subTest(current=current):
result, bridge = self.delegate(current)
self.assertEqual(result['state'], 'stopped')
self.assertEqual(bridge.call.call_count, 1)
result, bridge = self.delegate({'ok': True, 'state': 'stopped'}, new_run=True)
self.assertEqual(result['state'], 'delegated')
def test_unknown_or_failed_status_never_triggers_blind_retry(self):
for current in ({}, {'ok': False, 'error': 'offline'}, {'ok': True, 'state': 'unexpected'},
{'ok': True, 'state': 'failed'},
{'ok': True, 'state': 'succeeded', 'errors': ['battle failed']},
{'ok': True, 'state': 'succeeded', 'pending_restore': ['x.restore.json']}):
with self.subTest(current=current):
result, bridge = self.delegate(current)
self.assertEqual(result['state'], 'requires_analysis')
self.assertEqual(bridge.call.call_count, 1)
def test_resume_checks_errors_without_launching_another_run(self):
current = {'ok': True, 'state': 'succeeded', 'task': 'mirror', 'errors': ['battle failed']}
result, bridge = self.delegate(current, resume=True)
self.assertEqual(result['state'], 'requires_analysis')
self.assertEqual(bridge.call.call_count, 1)
def test_resume_does_not_accept_a_different_task_as_its_result(self):
save_json(self.home / 'mirror_current_run.json', {
'workflow': 'aalc', 'status': 'delegated', 'task_log': 'original.log'})
result, bridge = self.delegate({'ok': True, 'state': 'succeeded', 'task': 'mirror',
'log': 'another.log'}, resume=True)
self.assertEqual(result['reason'], 'task_changed')
self.assertEqual(bridge.call.call_count, 1)
def test_unfinished_speedrun_blocks_unrequested_workflow_switch(self):
save_json(self.home / 'mirror_current_run.json', {'status': 'requires_decision'})
with mock.patch.object(agent, 'Bridge') as factory:
result = agent.delegate_mirror()
self.assertEqual(result['reason'], 'unfinished_speedrun')
factory.assert_not_called()
def test_stop_marker_prevents_even_connecting(self):
agent.STOP_FILE.touch()
with mock.patch.object(agent, 'Bridge') as factory:
self.assertEqual(agent.delegate_mirror()['state'], 'stopped')
factory.assert_not_called()
def test_timeout_after_start_is_reported_without_retry_or_clicks(self):
bridge = mock.Mock()
error = SessionTimeout('reply lost')
error.tool = 'run_task'
bridge.call.side_effect = [{'ok': True, 'state': 'idle'}, error]
with mock.patch.object(agent, 'Bridge', return_value=bridge):
result = agent.delegate_mirror()
self.assertEqual(result['state'], 'requires_analysis')
self.assertTrue(result['outcome_unknown'])
self.assertEqual(result['pending_tool'], 'run_task')
self.assertEqual(bridge.call.call_count, 2)
bridge.close.assert_called_once()
def test_plain_cli_takes_aalc_path_without_model_or_ocr(self):
bridge = mock.Mock()
bridge.call.side_effect = [{'ok': True, 'state': 'idle'}, {'ok': True, 'log': 'mirror.log'}]
release = mock.Mock()
with mock.patch.object(sys, 'argv', ['agent']), \
mock.patch.object(agent, 'Bridge', return_value=bridge), \
mock.patch.object(agent, 'acquire_single_instance', return_value=release), \
mock.patch.object(agent, 'DecisionRouter') as router, \
contextlib.redirect_stdout(io.StringIO()):
agent.main()
router.assert_not_called()
release.assert_called_once()
result = json.loads((self.home / 'aalc_mirror_status.json').read_text())
self.assertEqual(result['state'], 'delegated')
self.assertEqual([call.args[0] for call in bridge.call.call_args_list], ['task_status', 'run_task'])
if __name__ == '__main__':
unittest.main()
+66 -1
View File
@@ -14,6 +14,7 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
import convert_modules as cm # noqa: E402 import convert_modules as cm # noqa: E402
from lc_mcp import game_lock
class QuietLogMixin: class QuietLogMixin:
@@ -28,6 +29,62 @@ class QuietLogMixin:
patcher = mock.patch.object(cm, 'log', lambda m: None) patcher = mock.patch.object(cm, 'log', lambda m: None)
patcher.start() patcher.start()
self.addCleanup(patcher.stop) self.addCleanup(patcher.stop)
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
patcher = mock.patch.object(game_lock, 'default_lock_path',
return_value=os.path.join(tmp.name, 'game.lock'))
patcher.start()
self.addCleanup(patcher.stop)
patcher = mock.patch.object(cm, 'probe', return_value={'ok': True, 'state': 'idle'})
patcher.start()
self.addCleanup(patcher.stop)
class GameOwnershipTest(QuietLogMixin, unittest.TestCase):
def test_running_task_is_not_navigated_or_closed(self):
from lc_mcp.fake_engine import FakeEngine
from lc_mcp.protocol import Server
from lc_mcp.tasks import TaskRunner
with tempfile.TemporaryDirectory() as tmp:
runner = TaskRunner(tmp, argv_factory=lambda *a: [
sys.executable, '-c', 'import time; time.sleep(30)'])
server = Server(FakeEngine(), runner)
runner.start('daily', {}) # Emulate an older process without the shared lock.
try:
with mock.patch.object(cm, 'probe', side_effect=server.call_tool), \
mock.patch.object(cm, 'ensure_server', return_value=True), \
mock.patch.object(cm, 'ensure_display') as display, \
mock.patch.object(cm, 'launch_game') as launch, \
mock.patch.object(cm, 'close_game') as close:
self.assertEqual(cm.main(['--report-dir', tmp]), 1)
display.assert_not_called()
launch.assert_not_called()
close.assert_not_called()
self.assertTrue(runner.running())
self.assertEqual(server.engine.actions, [])
finally:
runner.stop()
def test_unknown_status_does_not_touch_the_game(self):
for status in ({}, {'ok': False}, {'ok': True, 'state': 'unknown'}):
with self.subTest(status=status), tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(cm, 'probe', return_value=status), \
mock.patch.object(cm, 'ensure_server', return_value=True), \
mock.patch.object(cm, 'ensure_display') as display, \
mock.patch.object(cm, 'close_game') as close:
self.assertEqual(cm.main(['--report-dir', tmp]), 1)
display.assert_not_called()
close.assert_not_called()
def test_existing_owner_prevents_even_service_startup(self):
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(cm, 'ensure_server') as server, \
mock.patch.object(cm, 'close_game') as close, \
game_lock.exclusive_game():
self.assertEqual(cm.main(['--report-dir', tmp]), 1)
server.assert_not_called()
close.assert_not_called()
class ScreenDetectTest(QuietLogMixin, unittest.TestCase): class ScreenDetectTest(QuietLogMixin, unittest.TestCase):
@@ -603,6 +660,14 @@ class CliRoutingTest(QuietLogMixin, unittest.TestCase):
done = [] done = []
tmp = tempfile.mkdtemp() tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True) self.addCleanup(shutil.rmtree, tmp, True)
def close_owned_game():
# Ownership must cover shutdown too, so a new task cannot start here.
with self.assertRaises(game_lock.GameBusyError):
with game_lock.exclusive_game():
pass
closed.append(1)
with mock.patch.object(cm, 'read_enkephalin', lambda: 4), \ with mock.patch.object(cm, 'read_enkephalin', lambda: 4), \
mock.patch.object(cm, 'read_lunacy', lambda **k: 9699), \ mock.patch.object(cm, 'read_lunacy', lambda **k: 9699), \
mock.patch.object(cm, 'ensure_server', lambda *a: True), \ mock.patch.object(cm, 'ensure_server', lambda *a: True), \
@@ -611,7 +676,7 @@ class CliRoutingTest(QuietLogMixin, unittest.TestCase):
mock.patch.object(cm, 'wait_main_menu', lambda *a: True), \ mock.patch.object(cm, 'wait_main_menu', lambda *a: True), \
mock.patch.object(cm, 'ensure_window_size', lambda *a: (1600, 900)), \ mock.patch.object(cm, 'ensure_window_size', lambda *a: (1600, 900)), \
mock.patch.object(cm, 'close_panel', lambda: True), \ mock.patch.object(cm, 'close_panel', lambda: True), \
mock.patch.object(cm, 'close_game', lambda: closed.append(1)), \ mock.patch.object(cm, 'close_game', close_owned_game), \
mock.patch.object(cm.time, 'sleep', lambda s: None): mock.patch.object(cm.time, 'sleep', lambda s: None):
code = cm.main(argv + ['--report-dir', tmp]) code = cm.main(argv + ['--report-dir', tmp])
done.append(os.listdir(tmp)) done.append(os.listdir(tmp))
+6
View File
@@ -10,6 +10,7 @@
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。 关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
""" """
import sys import sys
import contextlib
import os import os
import ast import ast
import inspect import inspect
@@ -326,6 +327,10 @@ class DriverWiringTest(unittest.TestCase):
with mock.patch.dict(sys.modules, modules), \ with mock.patch.dict(sys.modules, modules), \
mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1', LCP_RESTORE_FILE=''), \ mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1', LCP_RESTORE_FILE=''), \
mock.patch.object(aalc_task, 'bootstrap'), \ 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_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'), \
@@ -338,6 +343,7 @@ class DriverWiringTest(unittest.TestCase):
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, {}), 3 if problems else 0) self.assertEqual(aalc_task.run(task, {}), 3 if problems else 0)
install_hotkey.return_value.stop.assert_called_once() install_hotkey.return_value.stop.assert_called_once()
self.assertEqual(hdr_warning.call_count, int(task == 'all' and not problems))
if problems: if problems:
drv.click.assert_not_called() drv.click.assert_not_called()
else: else:
+67
View File
@@ -0,0 +1,67 @@
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from lc_mcp import aalc_task, game_lock
class GameLockTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.path = os.path.join(tmp.name, 'game.lock')
def test_exception_releases_lock_without_deleting_file(self):
with self.assertRaisesRegex(RuntimeError, 'failed'):
with game_lock.exclusive_game(self.path):
raise RuntimeError('failed')
self.assertTrue(os.path.exists(self.path))
with game_lock.exclusive_game(self.path):
with self.assertRaises(game_lock.GameBusyError):
with game_lock.exclusive_game(self.path):
self.fail('second owner acquired the game')
def test_process_lock_is_released_after_hard_exit(self):
ready = self.path + '.ready'
code = '''
import os, sys, time
from lc_mcp.game_lock import exclusive_game
with exclusive_game(sys.argv[1]):
with open(sys.argv[2], 'w') as marker:
marker.write('ready')
time.sleep(30)
'''
with subprocess.Popen([sys.executable, '-c', code, self.path, ready],
cwd=Path(__file__).resolve().parents[1],
stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
try:
deadline = time.monotonic() + 5
while not os.path.exists(ready) and proc.poll() is None and time.monotonic() < deadline:
time.sleep(.01)
self.assertTrue(os.path.exists(ready), 'child did not acquire the lock')
with self.assertRaises(game_lock.GameBusyError):
with game_lock.exclusive_game(self.path):
self.fail('parent acquired a live child lock')
finally:
proc.kill()
proc.communicate(timeout=5)
with game_lock.exclusive_game(self.path):
pass
def test_task_refuses_converter_lock_before_bootstrap(self):
with mock.patch.object(game_lock, 'default_lock_path', return_value=self.path), \
mock.patch.object(aalc_task, 'bootstrap') as bootstrap, \
mock.patch.object(aalc_task, 'log'):
with game_lock.exclusive_game():
self.assertEqual(aalc_task.run('daily', {}), aalc_task.PREFLIGHT_EXIT)
bootstrap.assert_not_called()
if __name__ == '__main__':
unittest.main()
+21 -7
View File
@@ -18,7 +18,7 @@ sys.path.insert(0, REPO)
from lc_mcp import server as srv_mod # noqa: E402 from lc_mcp import server as srv_mod # noqa: E402
from lc_mcp.engine import find_hits # noqa: E402 from lc_mcp.engine import find_hits # noqa: E402
from lc_mcp.fake_engine import FakeEngine # noqa: E402 from lc_mcp.fake_engine import FakeEngine # noqa: E402
from lc_mcp.protocol import Server, TOOLS # noqa: E402 from lc_mcp.protocol import AUTOMATION_INSTRUCTIONS, Server, TOOLS # noqa: E402
from lc_mcp.tasks import TaskRunner # noqa: E402 from lc_mcp.tasks import TaskRunner # noqa: E402
START = {'text': '开始', 'x': 100, 'y': 200, 'w': 40, 'h': 20} START = {'text': '开始', 'x': 100, 'y': 200, 'w': 40, 'h': 20}
@@ -67,6 +67,7 @@ class ProtocolTest(unittest.TestCase):
def test_initialize_and_list(self): def test_initialize_and_list(self):
r = self.s.handle({'jsonrpc': '2.0', 'id': 7, 'method': 'initialize', 'params': {}}) r = self.s.handle({'jsonrpc': '2.0', 'id': 7, 'method': 'initialize', 'params': {}})
self.assertEqual(r['id'], 7) self.assertEqual(r['id'], 7)
self.assertEqual(r['result']['instructions'], AUTOMATION_INSTRUCTIONS)
names = [t['name'] for t in self.s.handle({'jsonrpc': '2.0', 'id': 8, 'method': 'tools/list'})['result']['tools']] names = [t['name'] for t in self.s.handle({'jsonrpc': '2.0', 'id': 8, 'method': 'tools/list'})['result']['tools']]
self.assertEqual(names, [t['name'] for t in TOOLS]) self.assertEqual(names, [t['name'] for t in TOOLS])
self.assertIsNone(self.s.handle({'jsonrpc': '2.0', 'method': 'notifications/initialized'})) self.assertIsNone(self.s.handle({'jsonrpc': '2.0', 'method': 'notifications/initialized'}))
@@ -213,7 +214,7 @@ class AalcTaskArgsTest(unittest.TestCase):
class Cfg: class Cfg:
def __init__(self): def __init__(self):
self.values, self.saved, self.flushes = {'set_mirror_count': 1}, {}, 0 self.values, self.saved, self.flushes = {'set_mirror_count': 1, 'infinite_dungeons': True}, {}, 0
def get_value(self, key): def get_value(self, key):
return self.values[key] return self.values[key]
@@ -228,20 +229,33 @@ class AalcTaskArgsTest(unittest.TestCase):
self.flushes += 1 self.flushes += 1
cfg = Cfg() cfg = Cfg()
with tempfile.TemporaryDirectory() as d: before = {'set_mirror_count': 1, 'infinite_dungeons': True}
lines = []
with tempfile.TemporaryDirectory() as d, mock.patch.object(aalc_task, 'log', lines.append):
path = os.path.join(d, 'x.restore.json') path = os.path.join(d, 'x.restore.json')
originals = aalc_task.apply_overrides(cfg, 'mirror', {'count': 5}, path) originals = aalc_task.apply_overrides(cfg, 'mirror', {'count': 5}, path)
self.assertEqual(cfg.values['set_mirror_count'], 5) # 指定次数时无限刷牢必须关掉, 否则 AALC 把次数改成 9999
self.assertEqual(cfg.values, {'set_mirror_count': 5, 'infinite_dungeons': False})
self.assertIn('无限刷牢', '\n'.join(lines))
with open(path, encoding='utf-8') as f: with open(path, encoding='utf-8') as f:
self.assertEqual(json.load(f), {'set_mirror_count': 1}) self.assertEqual(json.load(f), before)
self.assertEqual(originals, {'set_mirror_count': 1}) self.assertEqual(originals, before)
# 任务进程被强杀后, TaskRunner 用 --restore 读文件写回 # 任务进程被强杀后, TaskRunner 用 --restore 读文件写回
aalc_task.restore_file(path, cfg) aalc_task.restore_file(path, cfg)
self.assertEqual((cfg.saved, cfg.flushes), ({'set_mirror_count': 1}, 1)) self.assertEqual((cfg.saved, cfg.flushes), (before, 1))
self.assertFalse(os.path.exists(path)) self.assertFalse(os.path.exists(path))
self.assertEqual(aalc_task.apply_overrides(cfg, 'reward', {}, path), {}) self.assertEqual(aalc_task.apply_overrides(cfg, 'reward', {}, path), {})
self.assertFalse(os.path.exists(path)) # 没有覆盖就不留恢复文件 self.assertFalse(os.path.exists(path)) # 没有覆盖就不留恢复文件
def test_mirror_without_count_keeps_configured_infinite_mode(self):
from lc_mcp import aalc_task
cfg = mock.Mock()
cfg.get_value.side_effect = {'set_EXP_count': 3}.get
self.assertEqual(aalc_task.apply_overrides(cfg, 'mirror', {}), {})
cfg.unsaved_set_value.assert_not_called()
self.assertEqual(aalc_task.apply_overrides(cfg, 'daily', {'exp': 1}), {'set_EXP_count': 3})
cfg.unsaved_set_value.assert_called_once_with('set_EXP_count', 1)
class TaskRestoreTest(unittest.TestCase): class TaskRestoreTest(unittest.TestCase):
"""run_task 的临时次数会随 AALC 中途存盘写进 config.yaml; 强杀后必须写回原值。""" """run_task 的临时次数会随 AALC 中途存盘写进 config.yaml; 强杀后必须写回原值。"""
+31
View File
@@ -80,6 +80,37 @@ class ProgressResultTest(unittest.TestCase):
self.assertEqual(self.run_progress(level=30), (0, 1)) self.assertEqual(self.run_progress(level=30), (0, 1))
class CardResultTest(unittest.TestCase):
def run_command(self, command, upgrade=True, sync=True, uptie=True):
argv = ['levelup.py'] + command + (['--uptie'] if uptie else [])
with mock.patch.object(sys, 'argv', argv), \
mock.patch.object(levelup, 'state', return_value={
'items': [{'text': 'Level Up IDENTITIES Facades'}]}), \
mock.patch.object(levelup, 'scan_grid', return_value=[
(0, 0, 335, 260, 20, True, 'identity')]), \
mock.patch.object(levelup, 'dismiss_modal'), \
mock.patch.object(levelup, 'long_press'), \
mock.patch.object(levelup, 'click'), \
mock.patch.object(levelup, 'do_level_up', return_value=(upgrade, '升级结果')), \
mock.patch.object(levelup, 'do_uptie', return_value=(sync, '同步结果')) as synchronize, \
mock.patch.object(levelup.time, 'sleep'), \
mock.patch('builtins.print'):
code = levelup.main()
return code, synchronize.call_count
def test_failed_uptie_fails_both_cli_commands(self):
for command in (['card', '0', '0'], ['weakest']):
with self.subTest(command=command):
self.assertEqual(self.run_command(command, sync=False), (1, 1))
def test_both_operations_must_succeed(self):
self.assertEqual(self.run_command(['card', '0', '0']), (0, 1))
self.assertEqual(self.run_command(['card', '0', '0'], upgrade=False), (1, 1))
def test_upgrade_without_uptie_keeps_its_result(self):
self.assertEqual(self.run_command(['card', '0', '0'], uptie=False), (0, 0))
class Screens: class Screens:
"""按顺序返回预设画面的假 state(), 记录点击。""" """按顺序返回预设画面的假 state(), 记录点击。"""
+187 -1
View File
@@ -1,6 +1,10 @@
import ast
import os import os
import sys import sys
import threading
import unittest import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -34,6 +38,28 @@ class PreflightTest(unittest.TestCase):
def test_missing_team_in_queue(self): def test_missing_team_in_queue(self):
problems = preflight.check(values(teams_active_queue=[2]), 'mirror', env={}) problems = preflight.check(values(teams_active_queue=[2]), 'mirror', env={})
self.assertIn('队伍 2', problems[0]) self.assertIn('队伍 2', problems[0])
self.assertIn('没有可用队伍', problems[-1])
def test_empty_queue_is_rejected_because_aalc_would_exit_zero(self):
problems = preflight.check(values(teams_active_queue=[]), 'mirror', env={})
self.assertEqual(len(problems), 1)
self.assertIn('没有可用队伍', problems[0])
self.assertEqual(preflight.check(values(teams_active_queue=[]), 'daily', env={}), [])
self.assertEqual(preflight.check(values(teams_active_queue=[], mirror=False), 'all', env={}), [])
def test_fixed_team_use_must_match_current_difficulty(self):
order = [1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0]
hard_only = {'sinner_order': order, 'fixed_team_use': True, 'fixed_team_use_select': 0}
normal_only = dict(hard_only, fixed_team_use_select=1)
for team, hard, ok in [(hard_only, False, False), (hard_only, True, True),
(normal_only, False, True), (normal_only, True, False),
(dict(hard_only, fixed_team_use=False), False, True)]:
with self.subTest(team=team, hard=hard):
problems = preflight.check(values(teams={'1': team}, hard_mirror=hard), 'mirror', env={})
self.assertEqual(problems == [], ok, problems)
# 只要队列里有一支适用当前难度, AALC 就会轮转到它
v = values(teams_active_queue=[1, 2], teams={'1': hard_only, '2': normal_only})
self.assertEqual(preflight.check(v, 'mirror', env={}), [])
def test_lunacy_spending_is_rejected_unless_explicit(self): def test_lunacy_spending_is_rejected_unless_explicit(self):
v = values(set_lunacy_to_enkephalin=2) v = values(set_lunacy_to_enkephalin=2)
@@ -56,15 +82,175 @@ class PreflightTest(unittest.TestCase):
class Cfg: class Cfg:
data = {'simulator': False, 'mirror': True, 'set_win_size': 720, data = {'simulator': False, 'mirror': True, 'set_win_size': 720,
'set_lunacy_to_enkephalin': None, 'teams_active_queue': [1], 'teams': {1: Team()}} 'set_windows': False, 'set_win_position': 'center',
'set_lunacy_to_enkephalin': None, 'hard_mirror': 1,
'teams_active_queue': [1], 'teams': {1: Team()}}
def get_value(self, key): def get_value(self, key):
return self.data[key] return self.data[key]
v = preflight.collect(Cfg()) v = preflight.collect(Cfg())
self.assertEqual(v['teams'], {'1': {'sinner_order': [1]}}) self.assertEqual(v['teams'], {'1': {'sinner_order': [1]}})
self.assertIs(v['hard_mirror'], True)
self.assertEqual(v['set_lunacy_to_enkephalin'], 0) self.assertEqual(v['set_lunacy_to_enkephalin'], 0)
self.assertFalse(v['set_windows'])
self.assertEqual(v['set_win_position'], 'center')
def test_user_managed_window_skips_configured_size_check(self):
self.assertEqual(preflight.check(values(set_windows=False, set_win_size=2160),
'daily', desktop=(1920, 1080), env={}), [])
def test_borderless_window_can_fill_the_desktop(self):
for position in ('center', 'left_top', 'right_top', 'left_bottom', 'right_bottom'):
with self.subTest(position=position):
v = values(set_windows=True, set_win_size=1080, set_win_position=position)
self.assertEqual(preflight.check(v, 'daily', desktop=(1920, 1080), env={}), [])
self.assertTrue(preflight.check(v, 'daily', desktop=(1600, 900), env={}))
class HeadlessHdrTest(unittest.TestCase):
def test_upstream_prompt_is_acknowledged_without_an_event_loop(self):
# Run the pinned upstream detector; Event.wait would block without a receiver.
path = Path(__file__).resolve().parents[1] / 'vendor/aalc/tasks/base/script_task_scheme.py'
tree = ast.parse(path.read_text(encoding='utf-8'))
node = next(n for n in tree.body if isinstance(n, ast.FunctionDef)
and n.name == '_warn_if_game_monitor_hdr_enabled')
direct = object()
class Signal:
callback = None
def connect(self, callback, mode):
self.callback = callback if mode is direct else None
def disconnect(self, callback):
self.callback = None
def emit(self, event):
if self.callback:
self.callback(event)
signal = Signal()
events = []
def event_factory():
event = threading.Event()
events.append(event)
return event
ns = dict(cfg=SimpleNamespace(simulator=False, get_value=lambda *a: True),
screen=SimpleNamespace(handle=SimpleNamespace(hwnd=1)),
win32api=SimpleNamespace(MonitorFromWindow=lambda *a: 1),
win32con=SimpleNamespace(MONITOR_DEFAULTTONEAREST=2),
get_monitor_hdr_info=lambda *a: SimpleNamespace(hdr_enabled=True),
Event=event_factory, mediator=SimpleNamespace(hdr_warning=signal), log=mock.Mock())
exec(compile(ast.Module(body=[node], type_ignores=[]), str(path), 'exec'), ns)
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=direct)))
messages = []
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}):
with aalc_patches.headless_hdr_warning(SimpleNamespace(**ns), log=messages.append):
worker = threading.Thread(target=ns[node.name], daemon=True)
worker.start()
worker.join(1)
try:
self.assertFalse(worker.is_alive(), 'HDR prompt blocked the task')
self.assertTrue(events[0].is_set())
self.assertIn('HDR', messages[0])
finally:
for event in events:
event.set()
worker.join(1)
self.assertIsNone(signal.callback)
def test_exception_disconnects_the_receiver(self):
signal = mock.Mock()
scheme = SimpleNamespace(mediator=SimpleNamespace(hdr_warning=signal))
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=1)))
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}):
with self.assertRaisesRegex(RuntimeError, 'task failed'):
with aalc_patches.headless_hdr_warning(scheme):
raise RuntimeError('task failed')
signal.disconnect.assert_called_once_with(signal.connect.call_args.args[0])
class MirrorCompletionTest(unittest.TestCase):
"""AALC 退出码 0 不代表打完镜牢; 用上游真实 Mirror_task 核对完成局数。"""
class Signal:
def __init__(self):
self.callbacks = []
def connect(self, callback, mode):
self.callbacks.append(callback)
def disconnect(self, callback):
self.callbacks.remove(callback)
def emit(self, *args):
for callback in list(self.callbacks):
callback(*args)
def run_upstream_mirror(self, queue, team, count=1):
path = Path(__file__).resolve().parents[1] / 'vendor/aalc/tasks/base/script_task_scheme.py'
tree = ast.parse(path.read_text(encoding='utf-8'))
node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'Mirror_task')
signal = self.Signal()
mediator = SimpleNamespace(mirror_signal=signal, mirror_bar_kill_signal=mock.Mock())
state = {'teams_active_queue': list(queue),
'teams_be_select': [num in queue for num in (1,)]}
cfg = SimpleNamespace(
set_mirror_count=count, infinite_dungeons=False, save_rewards=False, hard_mirror=False,
auto_hard_mirror=False, re_claim_rewards=False, teams_active_queue=state['teams_active_queue'],
config=SimpleNamespace(teams={'1': team}), get_value=state.get,
normalize_and_sync_team_state=lambda persist=True: None, rotate_team_queue=mock.Mock())
ns = dict(cfg=cfg, mediator=mediator, log=mock.Mock(), to_get_reward=mock.Mock(),
onetime_mir_process=mock.Mock(return_value=True))
exec(compile(ast.Module(body=[node], type_ignores=[]), str(path), 'exec'), ns)
scheme = SimpleNamespace(mediator=mediator, Mirror_task=ns['Mirror_task'])
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=1)))
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}), \
aalc_patches.mirror_progress(scheme) as progress:
scheme.Mirror_task()
self.assertEqual(signal.callbacks, [], 'receiver must be disconnected')
return progress, ns['onetime_mir_process']
def test_unusable_team_returns_normally_but_is_reported_incomplete(self):
from lc_mcp import aalc_task
hard_only = SimpleNamespace(fixed_team_use=True, fixed_team_use_select=0)
progress, play = self.run_upstream_mirror([1], hard_only)
play.assert_not_called()
self.assertEqual((progress.finished, progress.total), (0, 1))
lines = []
with mock.patch.object(aalc_task, 'log', lines.append):
self.assertEqual(aalc_task.mirror_result('mirror', progress), aalc_task.INCOMPLETE_EXIT)
self.assertTrue(any(line.startswith('[ERROR]') and '0/1' in line for line in lines))
def test_completed_run_is_success(self):
from lc_mcp import aalc_task
progress, play = self.run_upstream_mirror([1], SimpleNamespace(fixed_team_use=False))
play.assert_called_once()
self.assertEqual((progress.finished, progress.total), (1, 1))
with mock.patch.object(aalc_task, 'log'):
self.assertEqual(aalc_task.mirror_result('mirror', progress), 0)
def test_missing_progress_only_fails_explicit_mirror_task(self):
from lc_mcp import aalc_task
with mock.patch.object(aalc_task, 'log'):
self.assertEqual(aalc_task.mirror_result('all', aalc_patches.MirrorProgress()), 0)
self.assertEqual(aalc_task.mirror_result('daily', aalc_patches.MirrorProgress()), 0)
self.assertEqual(aalc_task.mirror_result('mirror', aalc_patches.MirrorProgress()),
aalc_task.INCOMPLETE_EXIT)
def test_receiver_is_disconnected_on_exception(self):
signal = mock.Mock()
scheme = SimpleNamespace(mediator=SimpleNamespace(mirror_signal=signal))
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=1)))
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}):
with self.assertRaisesRegex(RuntimeError, 'task failed'):
with aalc_patches.mirror_progress(scheme):
raise RuntimeError('task failed')
signal.disconnect.assert_called_once_with(signal.connect.call_args.args[0])
class ExactTeamMatchTest(unittest.TestCase): class ExactTeamMatchTest(unittest.TestCase):