test_descriptors.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. import logging
  16. import mock
  17. from synapse.api.errors import SynapseError
  18. from synapse.util import async
  19. from synapse.util import logcontext
  20. from twisted.internet import defer
  21. from synapse.util.caches import descriptors
  22. from tests import unittest
  23. logger = logging.getLogger(__name__)
  24. class DescriptorTestCase(unittest.TestCase):
  25. @defer.inlineCallbacks
  26. def test_cache(self):
  27. class Cls(object):
  28. def __init__(self):
  29. self.mock = mock.Mock()
  30. @descriptors.cached()
  31. def fn(self, arg1, arg2):
  32. return self.mock(arg1, arg2)
  33. obj = Cls()
  34. obj.mock.return_value = 'fish'
  35. r = yield obj.fn(1, 2)
  36. self.assertEqual(r, 'fish')
  37. obj.mock.assert_called_once_with(1, 2)
  38. obj.mock.reset_mock()
  39. # a call with different params should call the mock again
  40. obj.mock.return_value = 'chips'
  41. r = yield obj.fn(1, 3)
  42. self.assertEqual(r, 'chips')
  43. obj.mock.assert_called_once_with(1, 3)
  44. obj.mock.reset_mock()
  45. # the two values should now be cached
  46. r = yield obj.fn(1, 2)
  47. self.assertEqual(r, 'fish')
  48. r = yield obj.fn(1, 3)
  49. self.assertEqual(r, 'chips')
  50. obj.mock.assert_not_called()
  51. @defer.inlineCallbacks
  52. def test_cache_num_args(self):
  53. """Only the first num_args arguments should matter to the cache"""
  54. class Cls(object):
  55. def __init__(self):
  56. self.mock = mock.Mock()
  57. @descriptors.cached(num_args=1)
  58. def fn(self, arg1, arg2):
  59. return self.mock(arg1, arg2)
  60. obj = Cls()
  61. obj.mock.return_value = 'fish'
  62. r = yield obj.fn(1, 2)
  63. self.assertEqual(r, 'fish')
  64. obj.mock.assert_called_once_with(1, 2)
  65. obj.mock.reset_mock()
  66. # a call with different params should call the mock again
  67. obj.mock.return_value = 'chips'
  68. r = yield obj.fn(2, 3)
  69. self.assertEqual(r, 'chips')
  70. obj.mock.assert_called_once_with(2, 3)
  71. obj.mock.reset_mock()
  72. # the two values should now be cached; we should be able to vary
  73. # the second argument and still get the cached result.
  74. r = yield obj.fn(1, 4)
  75. self.assertEqual(r, 'fish')
  76. r = yield obj.fn(2, 5)
  77. self.assertEqual(r, 'chips')
  78. obj.mock.assert_not_called()
  79. def test_cache_logcontexts(self):
  80. """Check that logcontexts are set and restored correctly when
  81. using the cache."""
  82. complete_lookup = defer.Deferred()
  83. class Cls(object):
  84. @descriptors.cached()
  85. def fn(self, arg1):
  86. @defer.inlineCallbacks
  87. def inner_fn():
  88. with logcontext.PreserveLoggingContext():
  89. yield complete_lookup
  90. defer.returnValue(1)
  91. return inner_fn()
  92. @defer.inlineCallbacks
  93. def do_lookup():
  94. with logcontext.LoggingContext() as c1:
  95. c1.name = "c1"
  96. r = yield obj.fn(1)
  97. self.assertEqual(logcontext.LoggingContext.current_context(),
  98. c1)
  99. defer.returnValue(r)
  100. def check_result(r):
  101. self.assertEqual(r, 1)
  102. obj = Cls()
  103. # set off a deferred which will do a cache lookup
  104. d1 = do_lookup()
  105. self.assertEqual(logcontext.LoggingContext.current_context(),
  106. logcontext.LoggingContext.sentinel)
  107. d1.addCallback(check_result)
  108. # and another
  109. d2 = do_lookup()
  110. self.assertEqual(logcontext.LoggingContext.current_context(),
  111. logcontext.LoggingContext.sentinel)
  112. d2.addCallback(check_result)
  113. # let the lookup complete
  114. complete_lookup.callback(None)
  115. return defer.gatherResults([d1, d2])
  116. def test_cache_logcontexts_with_exception(self):
  117. """Check that the cache sets and restores logcontexts correctly when
  118. the lookup function throws an exception"""
  119. class Cls(object):
  120. @descriptors.cached()
  121. def fn(self, arg1):
  122. @defer.inlineCallbacks
  123. def inner_fn():
  124. yield async.run_on_reactor()
  125. raise SynapseError(400, "blah")
  126. return inner_fn()
  127. @defer.inlineCallbacks
  128. def do_lookup():
  129. with logcontext.LoggingContext() as c1:
  130. c1.name = "c1"
  131. try:
  132. yield obj.fn(1)
  133. self.fail("No exception thrown")
  134. except SynapseError:
  135. pass
  136. self.assertEqual(logcontext.LoggingContext.current_context(),
  137. c1)
  138. obj = Cls()
  139. # set off a deferred which will do a cache lookup
  140. d1 = do_lookup()
  141. self.assertEqual(logcontext.LoggingContext.current_context(),
  142. logcontext.LoggingContext.sentinel)
  143. return d1
  144. @defer.inlineCallbacks
  145. def test_cache_default_args(self):
  146. class Cls(object):
  147. def __init__(self):
  148. self.mock = mock.Mock()
  149. @descriptors.cached()
  150. def fn(self, arg1, arg2=2, arg3=3):
  151. return self.mock(arg1, arg2, arg3)
  152. obj = Cls()
  153. obj.mock.return_value = 'fish'
  154. r = yield obj.fn(1, 2, 3)
  155. self.assertEqual(r, 'fish')
  156. obj.mock.assert_called_once_with(1, 2, 3)
  157. obj.mock.reset_mock()
  158. # a call with same params shouldn't call the mock again
  159. r = yield obj.fn(1, 2)
  160. self.assertEqual(r, 'fish')
  161. obj.mock.assert_not_called()
  162. obj.mock.reset_mock()
  163. # a call with different params should call the mock again
  164. obj.mock.return_value = 'chips'
  165. r = yield obj.fn(2, 3)
  166. self.assertEqual(r, 'chips')
  167. obj.mock.assert_called_once_with(2, 3, 3)
  168. obj.mock.reset_mock()
  169. # the two values should now be cached
  170. r = yield obj.fn(1, 2)
  171. self.assertEqual(r, 'fish')
  172. r = yield obj.fn(2, 3)
  173. self.assertEqual(r, 'chips')
  174. obj.mock.assert_not_called()