test_rwlock.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 synapse.util.async 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. self._assert_called_before_not_after(ds, 2)
  38. with ds[0].result:
  39. self._assert_called_before_not_after(ds, 2)
  40. self._assert_called_before_not_after(ds, 2)
  41. with ds[1].result:
  42. self._assert_called_before_not_after(ds, 2)
  43. self._assert_called_before_not_after(ds, 3)
  44. with ds[2].result:
  45. self._assert_called_before_not_after(ds, 3)
  46. self._assert_called_before_not_after(ds, 4)
  47. with ds[3].result:
  48. self._assert_called_before_not_after(ds, 4)
  49. self._assert_called_before_not_after(ds, 6)
  50. with ds[5].result:
  51. self._assert_called_before_not_after(ds, 6)
  52. self._assert_called_before_not_after(ds, 6)
  53. with ds[4].result:
  54. self._assert_called_before_not_after(ds, 6)
  55. self._assert_called_before_not_after(ds, 7)
  56. with ds[6].result:
  57. pass
  58. d = rwlock.write(key)
  59. self.assertTrue(d.called)
  60. with d.result:
  61. pass
  62. d = rwlock.read(key)
  63. self.assertTrue(d.called)
  64. with d.result:
  65. pass