import os import tempfile import unittest from pathlib import Path from linux_updater.core.lock import InstanceLock class TestInstanceLock(unittest.TestCase): def setUp(self): self.tmp = tempfile.NamedTemporaryFile(delete=False) self.tmp.close() self.lock_path = Path(self.tmp.name) if self.lock_path.exists(): self.lock_path.unlink() def tearDown(self): if self.lock_path.exists(): self.lock_path.unlink() def test_acquire_and_release(self): lock = InstanceLock(lock_path=self.lock_path) self.assertTrue(lock.acquire()) self.assertTrue(self.lock_path.exists()) self.assertEqual(lock.get_holder_pid(), os.getpid()) lock.release() self.assertFalse(lock.acquired) self.assertFalse(self.lock_path.exists()) def test_second_instance_blocked(self): lock1 = InstanceLock(lock_path=self.lock_path) self.assertTrue(lock1.acquire()) lock2 = InstanceLock(lock_path=self.lock_path) self.assertFalse(lock2.acquire()) self.assertEqual(lock2.get_holder_pid(), os.getpid()) lock1.release() # Now lock2 can acquire self.assertTrue(lock2.acquire()) lock2.release() def test_context_manager(self): with InstanceLock(lock_path=self.lock_path) as lock: self.assertTrue(lock.acquired) self.assertEqual(lock.get_holder_pid(), os.getpid()) # Second lock fails inside context manager lock2 = InstanceLock(lock_path=self.lock_path) self.assertFalse(lock2.acquire()) # Released after exit self.assertFalse(self.lock_path.exists()) if __name__ == "__main__": unittest.main()