test_lock.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from twisted.internet import defer
  16. from tests import unittest
  17. from synapse.util.lockutils import LockManager
  18. class LockManagerTestCase(unittest.TestCase):
  19. def setUp(self):
  20. self.lock_manager = LockManager()
  21. @defer.inlineCallbacks
  22. def test_one_lock(self):
  23. key = "test"
  24. deferred_lock1 = self.lock_manager.lock(key)
  25. self.assertTrue(deferred_lock1.called)
  26. lock1 = yield deferred_lock1
  27. self.assertFalse(lock1.released)
  28. lock1.release()
  29. self.assertTrue(lock1.released)
  30. @defer.inlineCallbacks
  31. def test_concurrent_locks(self):
  32. key = "test"
  33. deferred_lock1 = self.lock_manager.lock(key)
  34. deferred_lock2 = self.lock_manager.lock(key)
  35. self.assertTrue(deferred_lock1.called)
  36. self.assertFalse(deferred_lock2.called)
  37. lock1 = yield deferred_lock1
  38. self.assertFalse(lock1.released)
  39. self.assertFalse(deferred_lock2.called)
  40. lock1.release()
  41. self.assertTrue(lock1.released)
  42. self.assertTrue(deferred_lock2.called)
  43. lock2 = yield deferred_lock2
  44. lock2.release()
  45. @defer.inlineCallbacks
  46. def test_sequential_locks(self):
  47. key = "test"
  48. deferred_lock1 = self.lock_manager.lock(key)
  49. self.assertTrue(deferred_lock1.called)
  50. lock1 = yield deferred_lock1
  51. self.assertFalse(lock1.released)
  52. lock1.release()
  53. self.assertTrue(lock1.released)
  54. deferred_lock2 = self.lock_manager.lock(key)
  55. self.assertTrue(deferred_lock2.called)
  56. lock2 = yield deferred_lock2
  57. self.assertFalse(lock2.released)
  58. lock2.release()
  59. self.assertTrue(lock2.released)
  60. @defer.inlineCallbacks
  61. def test_with_statement(self):
  62. key = "test"
  63. with (yield self.lock_manager.lock(key)) as lock:
  64. self.assertFalse(lock.released)
  65. self.assertTrue(lock.released)
  66. @defer.inlineCallbacks
  67. def test_two_with_statement(self):
  68. key = "test"
  69. with (yield self.lock_manager.lock(key)):
  70. pass
  71. with (yield self.lock_manager.lock(key)):
  72. pass