Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_lockfile.py 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import time
  2. import os
  3. from django.test import TestCase
  4. from ..lockfile import FileLock, FileLocked
  5. def setup_fake_lock(lock_file_name):
  6. pid = os.getpid()
  7. lockfile = '%s.lock' % pid
  8. try:
  9. os.remove(lock_file_name)
  10. except OSError:
  11. pass
  12. os.symlink(lockfile, lock_file_name)
  13. class LockTest(TestCase):
  14. def test_process_killed_force_unlock(self):
  15. pid = os.getpid()
  16. lockfile = '%s.lock' % pid
  17. setup_fake_lock('test.lock')
  18. with open(lockfile, 'w+') as f:
  19. f.write('9999999')
  20. assert os.path.exists(lockfile)
  21. with FileLock('test'):
  22. assert True
  23. def test_force_unlock_in_same_process(self):
  24. pid = os.getpid()
  25. lockfile = '%s.lock' % pid
  26. os.symlink(lockfile, 'test.lock')
  27. with open(lockfile, 'w+') as f:
  28. f.write(str(os.getpid()))
  29. with FileLock('test', force=True):
  30. assert True
  31. def test_exception_after_timeout(self):
  32. pid = os.getpid()
  33. lockfile = '%s.lock' % pid
  34. setup_fake_lock('test.lock')
  35. with open(lockfile, 'w+') as f:
  36. f.write(str(os.getpid()))
  37. try:
  38. with FileLock('test', timeout=1):
  39. assert False
  40. except FileLocked:
  41. assert True
  42. def test_force_after_timeout(self):
  43. pid = os.getpid()
  44. lockfile = '%s.lock' % pid
  45. setup_fake_lock('test.lock')
  46. with open(lockfile, 'w+') as f:
  47. f.write(str(os.getpid()))
  48. timeout = 1
  49. start = time.time()
  50. with FileLock('test', timeout=timeout, force=True):
  51. assert True
  52. end = time.time()
  53. assert end - start > timeout
  54. def test_get_lock_pid(self):
  55. """Ensure get_lock_pid() works properly"""
  56. with FileLock('test', timeout=1, force=True) as lock:
  57. self.assertEqual(lock.get_lock_pid(), int(os.getpid()))