Fix MCP cancellation, mirror run state, and battle boundaries
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
"""Controller lifecycle and battle regressions using mocked MCP only."""
|
||||
import contextlib
|
||||
import ctypes
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
import battle_batch
|
||||
import jev_mirror_agent as agent
|
||||
from mcp_session import SessionCancelled, SessionTimeout
|
||||
from run_state import save_json
|
||||
|
||||
|
||||
class BattleBatchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.folder.cleanup)
|
||||
self.stop = Path(self.folder.name) / 'JEV_STOP'
|
||||
|
||||
def run_helper(self, client):
|
||||
session = mock.MagicMock()
|
||||
session.__enter__.return_value = client
|
||||
output = io.StringIO()
|
||||
with mock.patch.object(battle_batch, 'Session', return_value=session), \
|
||||
mock.patch.object(battle_batch, 'STOP_FILE', self.stop), \
|
||||
mock.patch.object(sys, 'argv', ['battle_batch.py', '--seconds', '1', '--battle-confirmed']), \
|
||||
mock.patch.object(battle_batch.time, 'sleep'), contextlib.redirect_stdout(output):
|
||||
battle_batch.main()
|
||||
return json.loads(output.getvalue())
|
||||
|
||||
def test_terminal_screens_never_receive_more_keys(self):
|
||||
for text in ('进行判定', '选择遭遇战奖励卡', '参加战斗的全体罪人已经死亡。'):
|
||||
with self.subTest(text=text):
|
||||
client = mock.Mock()
|
||||
client.call.return_value = {'ok': True, 'items': [{'text': text}]}
|
||||
result = self.run_helper(client)
|
||||
self.assertEqual(result['pairs'], 0)
|
||||
self.assertEqual(client.call.call_args_list, [mock.call('get_state')])
|
||||
|
||||
def test_stop_after_p_prevents_enter(self):
|
||||
client = mock.Mock()
|
||||
def call(tool, args=None):
|
||||
if tool == 'get_state':
|
||||
return {'ok': True, 'items': [{'text': 'WAVE 1'}]}
|
||||
self.stop.touch()
|
||||
return {'ok': True}
|
||||
client.call.side_effect = call
|
||||
result = self.run_helper(client)
|
||||
self.assertTrue(result['stopped'])
|
||||
self.assertFalse(result['outcome_unknown'])
|
||||
self.assertEqual(client.call.call_args_list, [mock.call('get_state'), mock.call('keypress', {'key': 'p'})])
|
||||
|
||||
def test_judgement_after_one_batch_ends_without_a_second_batch(self):
|
||||
client = mock.Mock()
|
||||
frames = iter(['WAVE 1', '选择一位罪人来进行判定'])
|
||||
client.call.side_effect = lambda tool, args=None: (
|
||||
{'ok': True, 'items': [{'text': next(frames)}]} if tool == 'get_state' else {'ok': True})
|
||||
result = self.run_helper(client)
|
||||
self.assertEqual(result['pairs'], 2)
|
||||
self.assertEqual(sum(call.args[0] == 'keypress' for call in client.call.call_args_list), 4)
|
||||
|
||||
|
||||
class AgentRuntimeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.folder.cleanup)
|
||||
self.home = Path(self.folder.name)
|
||||
self.config = self.home / 'config.json'
|
||||
self.config.write_text('{}')
|
||||
self.kernel = mock.Mock()
|
||||
self.kernel.CreateMutexW.return_value = 12345
|
||||
self.kernel.GetLastError.return_value = 0
|
||||
|
||||
def run_agent(self, bridge, extra_args=(), constructor_error=None):
|
||||
output = io.StringIO()
|
||||
environment = dict(os.environ, LC_FIXED_FALLBACK='1')
|
||||
environment.pop('OPENCODE_API_KEY', None)
|
||||
with mock.patch.object(agent, 'RUNTIME_HOME', self.home), \
|
||||
mock.patch.object(agent, 'STOP_FILE', self.home / 'JEV_STOP'), \
|
||||
mock.patch.object(agent, 'Bridge', return_value=bridge, side_effect=constructor_error) as factory, \
|
||||
mock.patch.object(ctypes, 'windll', mock.Mock(kernel32=self.kernel), create=True), \
|
||||
mock.patch.object(sys, 'argv', ['jev_mirror_agent.py', str(self.config), '--steps', '1', *extra_args]), \
|
||||
mock.patch.dict(os.environ, environment, clear=True), \
|
||||
mock.patch.object(agent.time, 'sleep'), \
|
||||
mock.patch.object(agent, 'button_enabled', return_value=False), \
|
||||
contextlib.redirect_stdout(output):
|
||||
agent.main()
|
||||
status = json.loads((self.home / 'jev_mirror_status.json').read_text())
|
||||
return status, factory
|
||||
|
||||
def test_old_claim_context_does_not_complete_new_run_at_lobby(self):
|
||||
save_json(self.home / 'jev_shop_context.json', {'floor': 5, 'claim_requested': True})
|
||||
save_json(self.home / 'mirror_current_run.json', {
|
||||
'start_utc': '2026-10-02T00:00:00+00:00', 'status': 'running',
|
||||
'dungeon_completed': False, 'final_reward_claimed': False})
|
||||
bridge = mock.Mock()
|
||||
bridge.call.return_value = {'ok': True, 'items': [
|
||||
{'text': text, 'score': 1} for text in ('探索状态', '进入', '名与蛛之镜')]}
|
||||
status, _ = self.run_agent(bridge)
|
||||
run = json.loads((self.home / 'mirror_current_run.json').read_text())
|
||||
self.assertEqual(status['state'], 'stopped')
|
||||
self.assertFalse(run['dungeon_completed'])
|
||||
self.assertFalse(run['final_reward_claimed'])
|
||||
bridge.close.assert_called_once()
|
||||
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
|
||||
|
||||
def test_bridge_initialization_failure_records_error_and_releases_mutex(self):
|
||||
status, _ = self.run_agent(mock.Mock(), constructor_error=SessionTimeout('initialization hung'))
|
||||
self.assertEqual(status['state'], 'requires_analysis')
|
||||
self.assertTrue(status['outcome_unknown'])
|
||||
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
|
||||
|
||||
def test_stop_file_prevents_bridge_startup(self):
|
||||
(self.home / 'JEV_STOP').touch()
|
||||
status, factory = self.run_agent(mock.Mock())
|
||||
self.assertEqual(status['state'], 'stopped')
|
||||
factory.assert_not_called()
|
||||
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
|
||||
|
||||
def test_pending_request_cancellation_marks_run_stopped_and_logs_uncertainty(self):
|
||||
bridge = mock.Mock()
|
||||
bridge.call.side_effect = SessionCancelled('cancelled pending get_state', True)
|
||||
status, _ = self.run_agent(bridge)
|
||||
self.assertEqual(status['state'], 'stopped')
|
||||
self.assertTrue(status['outcome_unknown'])
|
||||
run = json.loads((self.home / 'mirror_current_run.json').read_text())
|
||||
self.assertEqual(run['status'], 'stopped')
|
||||
rows = (self.home / 'jev_mirror_log.jsonl').read_text().splitlines()
|
||||
self.assertEqual(json.loads(rows[-1])['state'], 'stopped')
|
||||
bridge.close.assert_called_once()
|
||||
|
||||
def test_expired_budget_prevents_execute_from_sending_any_key(self):
|
||||
bridge = mock.Mock()
|
||||
with mock.patch.object(agent, 'STOP_FILE') as stop:
|
||||
stop.exists.return_value = False
|
||||
result = agent.execute(bridge, {'tool': 'keypress', 'args': {'key': 'enter'}}, deadline=0)
|
||||
self.assertTrue(result['stopped'])
|
||||
bridge.call.assert_not_called()
|
||||
|
||||
def test_close_error_still_releases_controller_mutex(self):
|
||||
bridge = mock.Mock()
|
||||
bridge.call.return_value = {'ok': True, 'items': []}
|
||||
bridge.close.side_effect = RuntimeError('close failed')
|
||||
with self.assertRaisesRegex(RuntimeError, 'close failed'):
|
||||
self.run_agent(bridge)
|
||||
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,6 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""不需要 Windows/AALC 的测试: python -m unittest discover -s tests"""
|
||||
import json
|
||||
import io
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -84,6 +85,55 @@ class ProtocolTest(unittest.TestCase):
|
||||
self.assertIn('bad arguments', r['error'])
|
||||
self.assertFalse(call(self.s, 'click')['ok'])
|
||||
|
||||
def test_invalid_request_shapes_do_not_escape_or_send_input(self):
|
||||
for params in (['invalid'], 'invalid', 1, True, None):
|
||||
response = self.s.handle({'jsonrpc': '2.0', 'id': 7, 'method': 'tools/call', 'params': params})
|
||||
self.assertEqual(response['error']['code'], -32602)
|
||||
for arguments in ([], 'invalid', 1, True, None):
|
||||
response = self.s.handle({'jsonrpc': '2.0', 'id': 8, 'method': 'tools/call',
|
||||
'params': {'name': 'click', 'arguments': arguments}})
|
||||
self.assertEqual(response['error']['code'], -32602)
|
||||
self.assertEqual(self.engine.actions, [])
|
||||
|
||||
def test_notifications_never_reply_or_perform_request_only_actions(self):
|
||||
message = {'jsonrpc': '2.0', 'method': 'tools/call',
|
||||
'params': {'name': 'click', 'arguments': {'x': 1, 'y': 2}}}
|
||||
self.assertIsNone(self.s.handle(message))
|
||||
self.assertEqual(self.engine.actions, [])
|
||||
self.assertIsNotNone(self.s.handle(dict(message, id=None)))
|
||||
|
||||
def test_malformed_messages_allow_following_valid_request(self):
|
||||
messages = ['null', '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":[1]}',
|
||||
'{"jsonrpc":"2.0","id":2,"method":"ping"}']
|
||||
stdin, stdout = io.StringIO('\n'.join(messages) + '\n'), io.StringIO()
|
||||
srv_mod.serve_lines(self.s, stdin.readline, stdout.write)
|
||||
responses = [json.loads(line) for line in stdout.getvalue().splitlines()]
|
||||
self.assertEqual([r.get('error', {}).get('code') for r in responses[:2]], [-32600, -32602])
|
||||
self.assertEqual(responses[2], {'jsonrpc': '2.0', 'id': 2, 'result': {}})
|
||||
|
||||
def test_invalid_envelope_returns_request_error(self):
|
||||
for updates in ({'jsonrpc': '1.0'}, {'method': []}, {'id': True}, {'id': []}):
|
||||
message = dict({'jsonrpc': '2.0', 'id': 9, 'method': 'ping'}, **updates)
|
||||
self.assertEqual(self.s.handle(message)['error']['code'], -32600)
|
||||
|
||||
def test_task_start_cannot_race_an_input_already_in_progress(self):
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.engine.click = lambda *args: (entered.set(), release.wait(3))
|
||||
worker = threading.Thread(target=lambda: call(self.s, 'click', x=1, y=2))
|
||||
worker.start()
|
||||
try:
|
||||
self.assertTrue(entered.wait(2))
|
||||
started = time.monotonic()
|
||||
response = call(self.s, 'run_task', task='mirror')
|
||||
self.assertFalse(response['ok'])
|
||||
self.assertIsNone(self.tasks.proc)
|
||||
self.assertLess(time.monotonic() - started, 1)
|
||||
self.assertEqual(call(self.s, 'task_status')['state'], 'idle')
|
||||
self.assertTrue(call(self.s, 'stop_task')['ok'])
|
||||
finally:
|
||||
release.set()
|
||||
worker.join(3)
|
||||
|
||||
def test_drag_duration_and_rejected_arguments(self):
|
||||
r = call(self.s, 'drag', from_x=200, from_y=300, to_x=200, to_y=600, duration=1.5)
|
||||
self.assertTrue(r['ok'])
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Real pipe regressions with a dummy worker; never connects to a game service."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
from mcp_session import Session, SessionCancelled, SessionTimeout
|
||||
|
||||
WORKER = '''import json,os,sys,time
|
||||
mode=os.environ['WORKER_MODE']
|
||||
for line in sys.stdin:
|
||||
message=json.loads(line)
|
||||
with open(os.environ['WORKER_LOG'],'a',encoding='utf-8') as log:
|
||||
log.write(json.dumps(message)+'\\n')
|
||||
mid=message.get('id')
|
||||
if mode=='initialize-failure':
|
||||
sys.exit(1)
|
||||
if mid is None:
|
||||
continue
|
||||
if message['method']=='initialize':
|
||||
if mode=='stderr-burst':
|
||||
sys.stderr.write('diagnostic\\n'*50000)
|
||||
sys.stderr.flush()
|
||||
result={}
|
||||
elif mode=='silent':
|
||||
continue
|
||||
elif mode=='malformed':
|
||||
print('invalid json',flush=True)
|
||||
continue
|
||||
else:
|
||||
result={'content':[{'type':'text','text':json.dumps({'ok':True,'text':'中文'})}]}
|
||||
print(json.dumps({'jsonrpc':'2.0','id':mid,'result':result}),flush=True)
|
||||
if mode=='no-read':
|
||||
time.sleep(60)
|
||||
'''
|
||||
|
||||
|
||||
class SessionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.folder.cleanup)
|
||||
self.log = Path(self.folder.name) / 'requests.jsonl'
|
||||
self.children = []
|
||||
|
||||
def worker(self, mode, **options):
|
||||
real_popen = subprocess.Popen
|
||||
def launch(*args, **kwargs):
|
||||
kwargs['env'] = dict(kwargs['env'], WORKER_MODE=mode, WORKER_LOG=str(self.log))
|
||||
child = real_popen([sys.executable, '-u', '-c', WORKER], **kwargs)
|
||||
self.children.append(child)
|
||||
return child
|
||||
with mock.patch('mcp_session.subprocess.Popen', side_effect=launch):
|
||||
return Session(**options)
|
||||
|
||||
def test_silent_response_times_out_without_retry_and_closes_child(self):
|
||||
client = self.worker('silent', timeout=.5)
|
||||
self.addCleanup(client.close)
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(SessionTimeout) as caught:
|
||||
client.call('click', {'x': 1, 'y': 2})
|
||||
self.assertTrue(caught.exception.outcome_unknown)
|
||||
self.assertEqual(caught.exception.tool, 'click')
|
||||
self.assertLess(time.monotonic() - started, 3)
|
||||
self.assertIsNotNone(client.process.poll())
|
||||
rows = [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
self.assertEqual(sum(row['method'] == 'tools/call' for row in rows), 1)
|
||||
with self.assertRaises(ConnectionError):
|
||||
client.call('get_state')
|
||||
|
||||
def test_stop_interrupts_pending_response(self):
|
||||
cancelled = threading.Event()
|
||||
client = self.worker('silent', timeout=5, cancelled=cancelled.is_set)
|
||||
self.addCleanup(client.close)
|
||||
timer = threading.Timer(.2, cancelled.set)
|
||||
timer.start()
|
||||
self.addCleanup(timer.cancel)
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(SessionCancelled) as caught:
|
||||
client.call('keypress', {'key': 'enter'})
|
||||
self.assertTrue(caught.exception.outcome_unknown)
|
||||
self.assertLess(time.monotonic() - started, 3)
|
||||
self.assertIsNotNone(client.process.poll())
|
||||
|
||||
def test_stderr_burst_does_not_block_handshake_and_chinese_response(self):
|
||||
with self.worker('stderr-burst', timeout=5) as client:
|
||||
self.assertEqual(client.call('get_state')['text'], '中文')
|
||||
self.assertLessEqual(len(client.stderr_tail), 20)
|
||||
|
||||
def test_initialization_failure_closes_every_pipe(self):
|
||||
with self.assertRaises(ConnectionError):
|
||||
self.worker('initialize-failure', timeout=2)
|
||||
child = self.children[0]
|
||||
self.assertIsNotNone(child.poll())
|
||||
self.assertTrue(all(stream.closed for stream in (child.stdin, child.stdout, child.stderr)))
|
||||
|
||||
def test_invalid_response_closes_session(self):
|
||||
client = self.worker('malformed', timeout=2)
|
||||
self.addCleanup(client.close)
|
||||
with self.assertRaises(ConnectionError):
|
||||
client.call('get_state')
|
||||
self.assertIsNotNone(client.process.poll())
|
||||
|
||||
def test_blocked_stdin_write_is_also_bounded(self):
|
||||
client = self.worker('no-read', timeout=.5)
|
||||
self.addCleanup(client.close)
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(SessionTimeout):
|
||||
client.call('type_text', {'text': 'x' * 500000})
|
||||
self.assertLess(time.monotonic() - started, 3)
|
||||
self.assertIsNotNone(client.process.poll())
|
||||
self.assertFalse(any(thread.is_alive() for thread in client._threads))
|
||||
|
||||
def test_long_wait_tool_has_a_response_budget_beyond_its_polling_timeout(self):
|
||||
client = Session.__new__(Session)
|
||||
client.timeout = 30
|
||||
client.request = mock.Mock(return_value={'content': [{'text': '{"ok":true}'}]})
|
||||
client.call('wait_for_text', {'text': '开始', 'timeout': 300})
|
||||
self.assertEqual(client.request.call_args.args[2], 305)
|
||||
|
||||
def test_session_uses_real_bridge_against_isolated_fake_server(self):
|
||||
from lc_mcp.fake_engine import FakeEngine
|
||||
from lc_mcp.protocol import Server
|
||||
from lc_mcp.server import make_tcp
|
||||
from lc_mcp.tasks import TaskRunner
|
||||
home = Path(self.folder.name)
|
||||
runtime = home / 'lc_mcp'
|
||||
runtime.mkdir()
|
||||
(runtime / 'token').write_text('test-only-token')
|
||||
engine = FakeEngine()
|
||||
tcp = make_tcp(Server(engine, TaskRunner(str(home / 'runs'))), '127.0.0.1', 0, 'test-only-token')
|
||||
serving = threading.Thread(target=tcp.serve_forever, daemon=True)
|
||||
serving.start()
|
||||
try:
|
||||
with mock.patch.dict(os.environ, {'LCP_PORT': str(tcp.server_address[1]),
|
||||
'HOME': str(home), 'USERPROFILE': str(home)}):
|
||||
with Session(timeout=5) as client:
|
||||
self.assertTrue(client.call('get_state')['ok'])
|
||||
self.assertTrue(client.call('drag', {'from_x': 1, 'from_y': 2,
|
||||
'to_x': 3, 'to_y': 4})['ok'])
|
||||
self.assertTrue(client.call('type_text', {'text': '中文'})['ok'])
|
||||
self.assertEqual(engine.actions[-1], ('type', '中文'))
|
||||
finally:
|
||||
tcp.shutdown()
|
||||
tcp.server_close()
|
||||
serving.join(2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,111 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
from run_state import prepare_run, save_json, record_claim, claim_is_current, complete_run
|
||||
|
||||
|
||||
class RunStateTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.folder.cleanup)
|
||||
self.home = Path(self.folder.name)
|
||||
self.run_path = self.home / 'mirror_current_run.json'
|
||||
self.context_path = self.home / 'jev_shop_context.json'
|
||||
|
||||
def test_completed_run_starts_with_fresh_floor_and_no_claim_or_upgrades(self):
|
||||
old_run, old_context = prepare_run(self.home)
|
||||
old_run['status'] = 'completed'
|
||||
old_context.update(floor=5, claim_requested=True, symbol_upgraded=True, battle_context=True)
|
||||
save_json(self.run_path, old_run)
|
||||
save_json(self.context_path, old_context)
|
||||
run, context = prepare_run(self.home)
|
||||
self.assertNotEqual(run['run_id'], old_run['run_id'])
|
||||
self.assertEqual(context, {'run_id': run['run_id'], 'floor': 1, 'refresh_used': 0})
|
||||
self.assertFalse(claim_is_current(run, context))
|
||||
|
||||
def test_resume_keeps_matching_run_and_verified_claim(self):
|
||||
old_run, context = prepare_run(self.home)
|
||||
context.update(floor=4, symbol_upgraded=True)
|
||||
record_claim(self.home, old_run, context, {'path': 'completion.png'})
|
||||
run, resumed = prepare_run(self.home, resume=True)
|
||||
self.assertEqual(run['run_id'], old_run['run_id'])
|
||||
self.assertEqual(run['start_utc'], old_run['start_utc'])
|
||||
self.assertEqual(resumed['floor'], 4)
|
||||
self.assertTrue(resumed['symbol_upgraded'])
|
||||
self.assertTrue(claim_is_current(run, resumed))
|
||||
|
||||
def test_explicit_new_run_discards_even_unfinished_state(self):
|
||||
old_run, _ = prepare_run(self.home)
|
||||
run, _ = prepare_run(self.home, new_run=True)
|
||||
self.assertNotEqual(run['run_id'], old_run['run_id'])
|
||||
|
||||
def test_resume_requires_an_unfinished_record(self):
|
||||
with self.assertRaises(ValueError):
|
||||
prepare_run(self.home, resume=True)
|
||||
run, _ = prepare_run(self.home)
|
||||
run['status'] = 'completed'
|
||||
save_json(self.run_path, run)
|
||||
with self.assertRaises(ValueError):
|
||||
prepare_run(self.home, resume=True)
|
||||
|
||||
def test_orphan_context_does_not_supply_completion_to_new_run(self):
|
||||
save_json(self.context_path, {'floor': 5, 'claim_requested': True})
|
||||
run, context = prepare_run(self.home)
|
||||
self.assertEqual(context['floor'], 1)
|
||||
self.assertFalse(claim_is_current(run, context))
|
||||
|
||||
def test_legacy_unfinished_run_preserves_upgrades_but_discards_unbound_claim(self):
|
||||
save_json(self.run_path, {'start_utc': '2026-10-02T18:13:22+08:00', 'status': 'user_takeover'})
|
||||
save_json(self.context_path, {'floor': 5, 'symbol_upgraded': True,
|
||||
'claim_requested': True, 'battle_context': True})
|
||||
run, context = prepare_run(self.home, resume=True)
|
||||
self.assertEqual(context['floor'], 5)
|
||||
self.assertTrue(context['symbol_upgraded'])
|
||||
self.assertNotIn('battle_context', context)
|
||||
self.assertFalse(claim_is_current(run, context))
|
||||
self.assertTrue(run['legacy_context_migrated'])
|
||||
|
||||
def test_mismatched_ids_fail_before_overwriting_the_context(self):
|
||||
prepare_run(self.home)
|
||||
save_json(self.context_path, {'run_id': 'another-run', 'floor': 5})
|
||||
before = self.context_path.read_bytes()
|
||||
with self.assertRaises(ValueError):
|
||||
prepare_run(self.home)
|
||||
self.assertEqual(self.context_path.read_bytes(), before)
|
||||
|
||||
def test_completion_requires_matching_claim_and_keeps_both_screens(self):
|
||||
run, context = prepare_run(self.home)
|
||||
with self.assertRaises(ValueError):
|
||||
complete_run(self.home, run, context, {'path': 'home.png'})
|
||||
record_claim(self.home, run, context, {'path': 'completion.png'})
|
||||
context['claim_run_id'] = 'another-run'
|
||||
with self.assertRaises(ValueError):
|
||||
complete_run(self.home, run, context, {'path': 'home.png'})
|
||||
context['claim_run_id'] = run['run_id']
|
||||
complete_run(self.home, run, context, {'path': 'home.png'})
|
||||
saved = json.loads(self.run_path.read_text())
|
||||
self.assertTrue(saved['dungeon_completed'])
|
||||
self.assertEqual(saved['claim_evidence']['path'], 'completion.png')
|
||||
self.assertEqual(saved['completion_evidence']['path'], 'home.png')
|
||||
|
||||
def test_atomic_snapshot_retains_old_data_if_serialization_fails(self):
|
||||
save_json(self.context_path, {'floor': 2})
|
||||
with self.assertRaises(TypeError):
|
||||
save_json(self.context_path, {'bad': {1, 2}})
|
||||
self.assertEqual(json.loads(self.context_path.read_text()), {'floor': 2})
|
||||
self.assertFalse(list(self.home.glob('*.tmp')))
|
||||
|
||||
def test_new_run_can_recover_from_corrupt_old_files(self):
|
||||
self.run_path.write_text('truncated')
|
||||
self.context_path.write_text('truncated')
|
||||
run, context = prepare_run(self.home, new_run=True)
|
||||
self.assertEqual(run['status'], 'running')
|
||||
self.assertEqual(context['floor'], 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user