unittest.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from mock import Mock
  18. from canonicaljson import json
  19. import twisted
  20. import twisted.logger
  21. from twisted.internet.defer import Deferred
  22. from twisted.trial import unittest
  23. from synapse.http.server import JsonResource
  24. from synapse.http.site import SynapseRequest
  25. from synapse.server import HomeServer
  26. from synapse.types import UserID, create_requester
  27. from synapse.util.logcontext import LoggingContextFilter
  28. from tests.server import get_clock, make_request, render, setup_test_homeserver
  29. # Set up putting Synapse's logs into Trial's.
  30. rootLogger = logging.getLogger()
  31. log_format = (
  32. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s"
  33. )
  34. class ToTwistedHandler(logging.Handler):
  35. tx_log = twisted.logger.Logger()
  36. def emit(self, record):
  37. log_entry = self.format(record)
  38. log_level = record.levelname.lower().replace('warning', 'warn')
  39. self.tx_log.emit(
  40. twisted.logger.LogLevel.levelWithName(log_level),
  41. log_entry.replace("{", r"(").replace("}", r")"),
  42. )
  43. handler = ToTwistedHandler()
  44. formatter = logging.Formatter(log_format)
  45. handler.setFormatter(formatter)
  46. handler.addFilter(LoggingContextFilter(request=""))
  47. rootLogger.addHandler(handler)
  48. def around(target):
  49. """A CLOS-style 'around' modifier, which wraps the original method of the
  50. given instance with another piece of code.
  51. @around(self)
  52. def method_name(orig, *args, **kwargs):
  53. return orig(*args, **kwargs)
  54. """
  55. def _around(code):
  56. name = code.__name__
  57. orig = getattr(target, name)
  58. def new(*args, **kwargs):
  59. return code(orig, *args, **kwargs)
  60. setattr(target, name, new)
  61. return _around
  62. class TestCase(unittest.TestCase):
  63. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  64. attributes on both itself and its individual test methods, to override the
  65. root logger's logging level while that test (case|method) runs."""
  66. def __init__(self, methodName, *args, **kwargs):
  67. super(TestCase, self).__init__(methodName, *args, **kwargs)
  68. method = getattr(self, methodName)
  69. level = getattr(method, "loglevel", getattr(self, "loglevel", logging.ERROR))
  70. @around(self)
  71. def setUp(orig):
  72. # enable debugging of delayed calls - this means that we get a
  73. # traceback when a unit test exits leaving things on the reactor.
  74. twisted.internet.base.DelayedCall.debug = True
  75. old_level = logging.getLogger().level
  76. if old_level != level:
  77. @around(self)
  78. def tearDown(orig):
  79. ret = orig()
  80. logging.getLogger().setLevel(old_level)
  81. return ret
  82. logging.getLogger().setLevel(level)
  83. return orig()
  84. def assertObjectHasAttributes(self, attrs, obj):
  85. """Asserts that the given object has each of the attributes given, and
  86. that the value of each matches according to assertEquals."""
  87. for (key, value) in attrs.items():
  88. if not hasattr(obj, key):
  89. raise AssertionError("Expected obj to have a '.%s'" % key)
  90. try:
  91. self.assertEquals(attrs[key], getattr(obj, key))
  92. except AssertionError as e:
  93. raise (type(e))(str(e) + " for '.%s'" % key)
  94. def assert_dict(self, required, actual):
  95. """Does a partial assert of a dict.
  96. Args:
  97. required (dict): The keys and value which MUST be in 'actual'.
  98. actual (dict): The test result. Extra keys will not be checked.
  99. """
  100. for key in required:
  101. self.assertEquals(
  102. required[key], actual[key], msg="%s mismatch. %s" % (key, actual)
  103. )
  104. def DEBUG(target):
  105. """A decorator to set the .loglevel attribute to logging.DEBUG.
  106. Can apply to either a TestCase or an individual test method."""
  107. target.loglevel = logging.DEBUG
  108. return target
  109. class HomeserverTestCase(TestCase):
  110. """
  111. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  112. Attributes:
  113. servlets (list[function]): List of servlet registration function.
  114. user_id (str): The user ID to assume if auth is hijacked.
  115. hijack_auth (bool): Whether to hijack auth to return the user specified
  116. in user_id.
  117. """
  118. servlets = []
  119. hijack_auth = True
  120. def setUp(self):
  121. """
  122. Set up the TestCase by calling the homeserver constructor, optionally
  123. hijacking the authentication system to return a fixed user, and then
  124. calling the prepare function.
  125. """
  126. self.reactor, self.clock = get_clock()
  127. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  128. self.hs = self.make_homeserver(self.reactor, self.clock)
  129. if self.hs is None:
  130. raise Exception("No homeserver returned from make_homeserver.")
  131. if not isinstance(self.hs, HomeServer):
  132. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  133. # Register the resources
  134. self.resource = JsonResource(self.hs)
  135. for servlet in self.servlets:
  136. servlet(self.hs, self.resource)
  137. if hasattr(self, "user_id"):
  138. from tests.rest.client.v1.utils import RestHelper
  139. self.helper = RestHelper(self.hs, self.resource, self.user_id)
  140. if self.hijack_auth:
  141. def get_user_by_access_token(token=None, allow_guest=False):
  142. return {
  143. "user": UserID.from_string(self.helper.auth_user_id),
  144. "token_id": 1,
  145. "is_guest": False,
  146. }
  147. def get_user_by_req(request, allow_guest=False, rights="access"):
  148. return create_requester(
  149. UserID.from_string(self.helper.auth_user_id), 1, False, None
  150. )
  151. self.hs.get_auth().get_user_by_req = get_user_by_req
  152. self.hs.get_auth().get_user_by_access_token = get_user_by_access_token
  153. self.hs.get_auth().get_access_token_from_request = Mock(
  154. return_value="1234"
  155. )
  156. if hasattr(self, "prepare"):
  157. self.prepare(self.reactor, self.clock, self.hs)
  158. def make_homeserver(self, reactor, clock):
  159. """
  160. Make and return a homeserver.
  161. Args:
  162. reactor: A Twisted Reactor, or something that pretends to be one.
  163. clock (synapse.util.Clock): The Clock, associated with the reactor.
  164. Returns:
  165. A homeserver (synapse.server.HomeServer) suitable for testing.
  166. Function to be overridden in subclasses.
  167. """
  168. hs = self.setup_test_homeserver()
  169. return hs
  170. def prepare(self, reactor, clock, homeserver):
  171. """
  172. Prepare for the test. This involves things like mocking out parts of
  173. the homeserver, or building test data common across the whole test
  174. suite.
  175. Args:
  176. reactor: A Twisted Reactor, or something that pretends to be one.
  177. clock (synapse.util.Clock): The Clock, associated with the reactor.
  178. homeserver (synapse.server.HomeServer): The HomeServer to test
  179. against.
  180. Function to optionally be overridden in subclasses.
  181. """
  182. def make_request(
  183. self, method, path, content=b"", access_token=None, request=SynapseRequest
  184. ):
  185. """
  186. Create a SynapseRequest at the path using the method and containing the
  187. given content.
  188. Args:
  189. method (bytes/unicode): The HTTP request method ("verb").
  190. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  191. escaped UTF-8 & spaces and such).
  192. content (bytes or dict): The body of the request. JSON-encoded, if
  193. a dict.
  194. Returns:
  195. A synapse.http.site.SynapseRequest.
  196. """
  197. if isinstance(content, dict):
  198. content = json.dumps(content).encode('utf8')
  199. return make_request(method, path, content, access_token, request)
  200. def render(self, request):
  201. """
  202. Render a request against the resources registered by the test class's
  203. servlets.
  204. Args:
  205. request (synapse.http.site.SynapseRequest): The request to render.
  206. """
  207. render(request, self.resource, self.reactor)
  208. def setup_test_homeserver(self, *args, **kwargs):
  209. """
  210. Set up the test homeserver, meant to be called by the overridable
  211. make_homeserver. It automatically passes through the test class's
  212. clock & reactor.
  213. Args:
  214. See tests.utils.setup_test_homeserver.
  215. Returns:
  216. synapse.server.HomeServer
  217. """
  218. kwargs = dict(kwargs)
  219. kwargs.update(self._hs_args)
  220. return setup_test_homeserver(self.addCleanup, *args, **kwargs)
  221. def pump(self, by=0.0):
  222. """
  223. Pump the reactor enough that Deferreds will fire.
  224. """
  225. self.reactor.pump([by] * 100)
  226. def get_success(self, d):
  227. if not isinstance(d, Deferred):
  228. return d
  229. self.pump()
  230. return self.successResultOf(d)