52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
import os
|
|
import tempfile
|
|
import unittest
|
|
|
|
from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
|
|
|
|
class TestSingleInstanceLock(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp_dir = tempfile.mkdtemp(prefix="test_lock_")
|
|
self.pid_path = os.path.join(self.temp_dir, "test.pid")
|
|
|
|
def tearDown(self):
|
|
import shutil
|
|
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
|
|
|
def test_lock_acquire_and_release(self):
|
|
lock1 = SingleInstanceLock(pid_path=self.pid_path)
|
|
self.assertTrue(lock1.acquire())
|
|
self.assertTrue(os.path.isfile(self.pid_path))
|
|
|
|
with open(self.pid_path, "r") as f:
|
|
pid = int(f.read().strip())
|
|
self.assertEqual(pid, os.getpid())
|
|
|
|
# Second lock attempt must fail
|
|
lock2 = SingleInstanceLock(pid_path=self.pid_path)
|
|
with self.assertRaises(LockAcquisitionError):
|
|
lock2.acquire()
|
|
|
|
# Release first lock
|
|
lock1.release()
|
|
|
|
# Now lock2 should succeed
|
|
self.assertTrue(lock2.acquire())
|
|
lock2.release()
|
|
|
|
def test_lock_context_manager(self):
|
|
with SingleInstanceLock(pid_path=self.pid_path):
|
|
self.assertTrue(os.path.isfile(self.pid_path))
|
|
# Nested lock should fail
|
|
lock2 = SingleInstanceLock(pid_path=self.pid_path)
|
|
with self.assertRaises(LockAcquisitionError):
|
|
lock2.acquire()
|
|
|
|
# After context exit, lock file is unlinked or released
|
|
lock3 = SingleInstanceLock(pid_path=self.pid_path)
|
|
self.assertTrue(lock3.acquire())
|
|
lock3.release()
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|