1
0

test_linearizer.py 1.9 KB

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