unittest.py 9.6 KB

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