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()