test_limiter.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 tests import unittest
  16. from twisted.internet import defer
  17. from synapse.util.async import Limiter
  18. class LimiterTestCase(unittest.TestCase):
  19. @defer.inlineCallbacks
  20. def test_limiter(self):
  21. limiter = Limiter(3)
  22. key = object()
  23. d1 = limiter.queue(key)
  24. cm1 = yield d1
  25. d2 = limiter.queue(key)
  26. cm2 = yield d2
  27. d3 = limiter.queue(key)
  28. cm3 = yield d3
  29. d4 = limiter.queue(key)
  30. self.assertFalse(d4.called)
  31. d5 = limiter.queue(key)
  32. self.assertFalse(d5.called)
  33. with cm1:
  34. self.assertFalse(d4.called)
  35. self.assertFalse(d5.called)
  36. self.assertTrue(d4.called)
  37. self.assertFalse(d5.called)
  38. with cm3:
  39. self.assertFalse(d5.called)
  40. self.assertTrue(d5.called)
  41. with cm2:
  42. pass
  43. with (yield d4):
  44. pass
  45. with (yield d5):
  46. pass
  47. d6 = limiter.queue(key)
  48. with (yield d6):
  49. pass