test_filelock.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import os
  2. import time
  3. import logging
  4. import multiprocessing
  5. import tempfile
  6. import threading
  7. import library.python.filelock
  8. def _acquire_lock(lock_path, out_file_path):
  9. with library.python.filelock.FileLock(lock_path):
  10. with open(out_file_path, "a") as out:
  11. out.write("{}:{}\n".format(os.getpid(), time.time()))
  12. time.sleep(2)
  13. def test_filelock():
  14. temp_dir = tempfile.mkdtemp()
  15. lock_path = os.path.join(temp_dir, "file.lock")
  16. out_file_path = os.path.join(temp_dir, "out.txt")
  17. process_count = 5
  18. processes = []
  19. for i in range(process_count):
  20. process = multiprocessing.Process(target=_acquire_lock, args=(lock_path, out_file_path))
  21. process.start()
  22. processes.append(process)
  23. for process in processes:
  24. process.join()
  25. pids = []
  26. times = []
  27. with open(out_file_path) as out:
  28. content = out.read()
  29. logging.info("Times:\n%s", content)
  30. for line in content.strip().split("\n"):
  31. pid, time_val = line.split(":")
  32. pids.append(pid)
  33. times.append(float(time_val))
  34. assert len(set(pids)) == process_count
  35. time1 = times.pop()
  36. while times:
  37. time2 = times.pop()
  38. assert int(time1) - int(time2) >= 2
  39. time1 = time2
  40. def test_filelock_init_acquired():
  41. temp_dir = tempfile.mkdtemp()
  42. lock_path = os.path.join(temp_dir, "file.lock")
  43. with library.python.filelock.FileLock(lock_path):
  44. sublock = library.python.filelock.FileLock(lock_path)
  45. del sublock
  46. def test_concurrent_lock():
  47. filename = 'con.lock'
  48. def lock():
  49. l = library.python.filelock.FileLock(filename)
  50. time.sleep(1)
  51. l.acquire()
  52. l.release()
  53. try:
  54. os.unlink(filename)
  55. except OSError:
  56. pass
  57. threads = []
  58. for i in range(100):
  59. t = threading.Thread(target=lock)
  60. t.daemon = True
  61. threads.append(t)
  62. for t in threads:
  63. t.start()
  64. for t in threads:
  65. t.join()