test_rwlock.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 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 synapse.util.async_helpers import ReadWriteLock
  17. from tests import unittest
  18. class ReadWriteLockTestCase(unittest.TestCase):
  19. def _assert_called_before_not_after(self, lst, first_false):
  20. for i, d in enumerate(lst[:first_false]):
  21. self.assertTrue(d.called, msg="%d was unexpectedly false" % i)
  22. for i, d in enumerate(lst[first_false:]):
  23. self.assertFalse(
  24. d.called, msg="%d was unexpectedly true" % (i + first_false)
  25. )
  26. def test_rwlock(self):
  27. rwlock = ReadWriteLock()
  28. key = object()
  29. ds = [
  30. rwlock.read(key), # 0
  31. rwlock.read(key), # 1
  32. rwlock.write(key), # 2
  33. rwlock.write(key), # 3
  34. rwlock.read(key), # 4
  35. rwlock.read(key), # 5
  36. rwlock.write(key), # 6
  37. ]
  38. ds = [defer.ensureDeferred(d) for d in ds]
  39. self._assert_called_before_not_after(ds, 2)
  40. with ds[0].result:
  41. self._assert_called_before_not_after(ds, 2)
  42. self._assert_called_before_not_after(ds, 2)
  43. with ds[1].result:
  44. self._assert_called_before_not_after(ds, 2)
  45. self._assert_called_before_not_after(ds, 3)
  46. with ds[2].result:
  47. self._assert_called_before_not_after(ds, 3)
  48. self._assert_called_before_not_after(ds, 4)
  49. with ds[3].result:
  50. self._assert_called_before_not_after(ds, 4)
  51. self._assert_called_before_not_after(ds, 6)
  52. with ds[5].result:
  53. self._assert_called_before_not_after(ds, 6)
  54. self._assert_called_before_not_after(ds, 6)
  55. with ds[4].result:
  56. self._assert_called_before_not_after(ds, 6)
  57. self._assert_called_before_not_after(ds, 7)
  58. with ds[6].result:
  59. pass
  60. d = defer.ensureDeferred(rwlock.write(key))
  61. self.assertTrue(d.called)
  62. with d.result:
  63. pass
  64. d = defer.ensureDeferred(rwlock.read(key))
  65. self.assertTrue(d.called)
  66. with d.result:
  67. pass