unittest.py 9.1 KB

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