test_rwlock.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Copyright 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from twisted.internet import defer
  15. from synapse.util.async_helpers import ReadWriteLock
  16. from tests import unittest
  17. class ReadWriteLockTestCase(unittest.TestCase):
  18. def _assert_called_before_not_after(self, lst, first_false):
  19. for i, d in enumerate(lst[:first_false]):
  20. self.assertTrue(d.called, msg="%d was unexpectedly false" % i)
  21. for i, d in enumerate(lst[first_false:]):
  22. self.assertFalse(
  23. d.called, msg="%d was unexpectedly true" % (i + first_false)
  24. )
  25. def test_rwlock(self):
  26. rwlock = ReadWriteLock()
  27. key = object()
  28. ds = [
  29. rwlock.read(key), # 0
  30. rwlock.read(key), # 1
  31. rwlock.write(key), # 2
  32. rwlock.write(key), # 3
  33. rwlock.read(key), # 4
  34. rwlock.read(key), # 5
  35. rwlock.write(key), # 6
  36. ]
  37. ds = [defer.ensureDeferred(d) for d in ds]
  38. self._assert_called_before_not_after(ds, 2)
  39. with ds[0].result:
  40. self._assert_called_before_not_after(ds, 2)
  41. self._assert_called_before_not_after(ds, 2)
  42. with ds[1].result:
  43. self._assert_called_before_not_after(ds, 2)
  44. self._assert_called_before_not_after(ds, 3)
  45. with ds[2].result:
  46. self._assert_called_before_not_after(ds, 3)
  47. self._assert_called_before_not_after(ds, 4)
  48. with ds[3].result:
  49. self._assert_called_before_not_after(ds, 4)
  50. self._assert_called_before_not_after(ds, 6)
  51. with ds[5].result:
  52. self._assert_called_before_not_after(ds, 6)
  53. self._assert_called_before_not_after(ds, 6)
  54. with ds[4].result:
  55. self._assert_called_before_not_after(ds, 6)
  56. self._assert_called_before_not_after(ds, 7)
  57. with ds[6].result:
  58. pass
  59. d = defer.ensureDeferred(rwlock.write(key))
  60. self.assertTrue(d.called)
  61. with d.result:
  62. pass
  63. d = defer.ensureDeferred(rwlock.read(key))
  64. self.assertTrue(d.called)
  65. with d.result:
  66. pass