test_linearizer.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 import async, logcontext
  16. from tests import unittest
  17. from twisted.internet import defer
  18. from synapse.util.async import Linearizer
  19. class LinearizerTestCase(unittest.TestCase):
  20. @defer.inlineCallbacks
  21. def test_linearizer(self):
  22. linearizer = Linearizer()
  23. key = object()
  24. d1 = linearizer.queue(key)
  25. cm1 = yield d1
  26. d2 = linearizer.queue(key)
  27. self.assertFalse(d2.called)
  28. with cm1:
  29. self.assertFalse(d2.called)
  30. with (yield d2):
  31. pass
  32. def test_lots_of_queued_things(self):
  33. # we have one slow thing, and lots of fast things queued up behind it.
  34. # it should *not* explode the stack.
  35. linearizer = Linearizer()
  36. @defer.inlineCallbacks
  37. def func(i, sleep=False):
  38. with logcontext.LoggingContext("func(%s)" % i) as lc:
  39. with (yield linearizer.queue("")):
  40. self.assertEqual(
  41. logcontext.LoggingContext.current_context(), lc)
  42. if sleep:
  43. yield async.sleep(0)
  44. self.assertEqual(
  45. logcontext.LoggingContext.current_context(), lc)
  46. func(0, sleep=True)
  47. for i in xrange(1, 100):
  48. func(i)
  49. return func(1000)