unittest.py 9.3 KB

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