unittest.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 gc
  17. import hashlib
  18. import hmac
  19. import logging
  20. from mock import Mock
  21. from canonicaljson import json
  22. import twisted
  23. import twisted.logger
  24. from twisted.internet.defer import Deferred
  25. from twisted.trial import unittest
  26. from synapse.http.server import JsonResource
  27. from synapse.http.site import SynapseRequest
  28. from synapse.server import HomeServer
  29. from synapse.types import UserID, create_requester
  30. from synapse.util.logcontext import LoggingContext, LoggingContextFilter
  31. from tests.server import get_clock, make_request, render, setup_test_homeserver
  32. from tests.utils import default_config, setupdb
  33. setupdb()
  34. # Set up putting Synapse's logs into Trial's.
  35. rootLogger = logging.getLogger()
  36. log_format = (
  37. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s"
  38. )
  39. class ToTwistedHandler(logging.Handler):
  40. tx_log = twisted.logger.Logger()
  41. def emit(self, record):
  42. log_entry = self.format(record)
  43. log_level = record.levelname.lower().replace('warning', 'warn')
  44. self.tx_log.emit(
  45. twisted.logger.LogLevel.levelWithName(log_level),
  46. log_entry.replace("{", r"(").replace("}", r")"),
  47. )
  48. handler = ToTwistedHandler()
  49. formatter = logging.Formatter(log_format)
  50. handler.setFormatter(formatter)
  51. handler.addFilter(LoggingContextFilter(request=""))
  52. rootLogger.addHandler(handler)
  53. def around(target):
  54. """A CLOS-style 'around' modifier, which wraps the original method of the
  55. given instance with another piece of code.
  56. @around(self)
  57. def method_name(orig, *args, **kwargs):
  58. return orig(*args, **kwargs)
  59. """
  60. def _around(code):
  61. name = code.__name__
  62. orig = getattr(target, name)
  63. def new(*args, **kwargs):
  64. return code(orig, *args, **kwargs)
  65. setattr(target, name, new)
  66. return _around
  67. class TestCase(unittest.TestCase):
  68. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  69. attributes on both itself and its individual test methods, to override the
  70. root logger's logging level while that test (case|method) runs."""
  71. def __init__(self, methodName, *args, **kwargs):
  72. super(TestCase, self).__init__(methodName, *args, **kwargs)
  73. method = getattr(self, methodName)
  74. level = getattr(method, "loglevel", getattr(self, "loglevel", logging.ERROR))
  75. @around(self)
  76. def setUp(orig):
  77. # enable debugging of delayed calls - this means that we get a
  78. # traceback when a unit test exits leaving things on the reactor.
  79. twisted.internet.base.DelayedCall.debug = True
  80. # if we're not starting in the sentinel logcontext, then to be honest
  81. # all future bets are off.
  82. if LoggingContext.current_context() is not LoggingContext.sentinel:
  83. self.fail(
  84. "Test starting with non-sentinel logging context %s" % (
  85. LoggingContext.current_context(),
  86. )
  87. )
  88. old_level = logging.getLogger().level
  89. if old_level != level:
  90. @around(self)
  91. def tearDown(orig):
  92. ret = orig()
  93. logging.getLogger().setLevel(old_level)
  94. return ret
  95. logging.getLogger().setLevel(level)
  96. return orig()
  97. @around(self)
  98. def tearDown(orig):
  99. ret = orig()
  100. # force a GC to workaround problems with deferreds leaking logcontexts when
  101. # they are GCed (see the logcontext docs)
  102. gc.collect()
  103. LoggingContext.set_current_context(LoggingContext.sentinel)
  104. return ret
  105. def assertObjectHasAttributes(self, attrs, obj):
  106. """Asserts that the given object has each of the attributes given, and
  107. that the value of each matches according to assertEquals."""
  108. for (key, value) in attrs.items():
  109. if not hasattr(obj, key):
  110. raise AssertionError("Expected obj to have a '.%s'" % key)
  111. try:
  112. self.assertEquals(attrs[key], getattr(obj, key))
  113. except AssertionError as e:
  114. raise (type(e))(e.message + " for '.%s'" % key)
  115. def assert_dict(self, required, actual):
  116. """Does a partial assert of a dict.
  117. Args:
  118. required (dict): The keys and value which MUST be in 'actual'.
  119. actual (dict): The test result. Extra keys will not be checked.
  120. """
  121. for key in required:
  122. self.assertEquals(
  123. required[key], actual[key], msg="%s mismatch. %s" % (key, actual)
  124. )
  125. def DEBUG(target):
  126. """A decorator to set the .loglevel attribute to logging.DEBUG.
  127. Can apply to either a TestCase or an individual test method."""
  128. target.loglevel = logging.DEBUG
  129. return target
  130. def INFO(target):
  131. """A decorator to set the .loglevel attribute to logging.INFO.
  132. Can apply to either a TestCase or an individual test method."""
  133. target.loglevel = logging.INFO
  134. return target
  135. class HomeserverTestCase(TestCase):
  136. """
  137. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  138. Attributes:
  139. servlets (list[function]): List of servlet registration function.
  140. user_id (str): The user ID to assume if auth is hijacked.
  141. hijack_auth (bool): Whether to hijack auth to return the user specified
  142. in user_id.
  143. """
  144. servlets = []
  145. hijack_auth = True
  146. def setUp(self):
  147. """
  148. Set up the TestCase by calling the homeserver constructor, optionally
  149. hijacking the authentication system to return a fixed user, and then
  150. calling the prepare function.
  151. """
  152. self.reactor, self.clock = get_clock()
  153. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  154. self.hs = self.make_homeserver(self.reactor, self.clock)
  155. if self.hs is None:
  156. raise Exception("No homeserver returned from make_homeserver.")
  157. if not isinstance(self.hs, HomeServer):
  158. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  159. # Register the resources
  160. self.resource = JsonResource(self.hs)
  161. for servlet in self.servlets:
  162. servlet(self.hs, self.resource)
  163. from tests.rest.client.v1.utils import RestHelper
  164. self.helper = RestHelper(self.hs, self.resource, getattr(self, "user_id", None))
  165. if hasattr(self, "user_id"):
  166. if self.hijack_auth:
  167. def get_user_by_access_token(token=None, allow_guest=False):
  168. return {
  169. "user": UserID.from_string(self.helper.auth_user_id),
  170. "token_id": 1,
  171. "is_guest": False,
  172. }
  173. def get_user_by_req(request, allow_guest=False, rights="access"):
  174. return create_requester(
  175. UserID.from_string(self.helper.auth_user_id), 1, False, None
  176. )
  177. self.hs.get_auth().get_user_by_req = get_user_by_req
  178. self.hs.get_auth().get_user_by_access_token = get_user_by_access_token
  179. self.hs.get_auth().get_access_token_from_request = Mock(
  180. return_value="1234"
  181. )
  182. if hasattr(self, "prepare"):
  183. self.prepare(self.reactor, self.clock, self.hs)
  184. def make_homeserver(self, reactor, clock):
  185. """
  186. Make and return a homeserver.
  187. Args:
  188. reactor: A Twisted Reactor, or something that pretends to be one.
  189. clock (synapse.util.Clock): The Clock, associated with the reactor.
  190. Returns:
  191. A homeserver (synapse.server.HomeServer) suitable for testing.
  192. Function to be overridden in subclasses.
  193. """
  194. hs = self.setup_test_homeserver()
  195. return hs
  196. def default_config(self, name="test"):
  197. """
  198. Get a default HomeServer config object.
  199. Args:
  200. name (str): The homeserver name/domain.
  201. """
  202. return default_config(name)
  203. def prepare(self, reactor, clock, homeserver):
  204. """
  205. Prepare for the test. This involves things like mocking out parts of
  206. the homeserver, or building test data common across the whole test
  207. suite.
  208. Args:
  209. reactor: A Twisted Reactor, or something that pretends to be one.
  210. clock (synapse.util.Clock): The Clock, associated with the reactor.
  211. homeserver (synapse.server.HomeServer): The HomeServer to test
  212. against.
  213. Function to optionally be overridden in subclasses.
  214. """
  215. def make_request(
  216. self,
  217. method,
  218. path,
  219. content=b"",
  220. access_token=None,
  221. request=SynapseRequest,
  222. shorthand=True,
  223. ):
  224. """
  225. Create a SynapseRequest at the path using the method and containing the
  226. given content.
  227. Args:
  228. method (bytes/unicode): The HTTP request method ("verb").
  229. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  230. escaped UTF-8 & spaces and such).
  231. content (bytes or dict): The body of the request. JSON-encoded, if
  232. a dict.
  233. shorthand: Whether to try and be helpful and prefix the given URL
  234. with the usual REST API path, if it doesn't contain it.
  235. Returns:
  236. A synapse.http.site.SynapseRequest.
  237. """
  238. if isinstance(content, dict):
  239. content = json.dumps(content).encode('utf8')
  240. return make_request(
  241. self.reactor, method, path, content, access_token, request, shorthand
  242. )
  243. def render(self, request):
  244. """
  245. Render a request against the resources registered by the test class's
  246. servlets.
  247. Args:
  248. request (synapse.http.site.SynapseRequest): The request to render.
  249. """
  250. render(request, self.resource, self.reactor)
  251. def setup_test_homeserver(self, *args, **kwargs):
  252. """
  253. Set up the test homeserver, meant to be called by the overridable
  254. make_homeserver. It automatically passes through the test class's
  255. clock & reactor.
  256. Args:
  257. See tests.utils.setup_test_homeserver.
  258. Returns:
  259. synapse.server.HomeServer
  260. """
  261. kwargs = dict(kwargs)
  262. kwargs.update(self._hs_args)
  263. return setup_test_homeserver(self.addCleanup, *args, **kwargs)
  264. def pump(self, by=0.0):
  265. """
  266. Pump the reactor enough that Deferreds will fire.
  267. """
  268. self.reactor.pump([by] * 100)
  269. def get_success(self, d):
  270. if not isinstance(d, Deferred):
  271. return d
  272. self.pump()
  273. return self.successResultOf(d)
  274. def register_user(self, username, password, admin=False):
  275. """
  276. Register a user. Requires the Admin API be registered.
  277. Args:
  278. username (bytes/unicode): The user part of the new user.
  279. password (bytes/unicode): The password of the new user.
  280. admin (bool): Whether the user should be created as an admin
  281. or not.
  282. Returns:
  283. The MXID of the new user (unicode).
  284. """
  285. self.hs.config.registration_shared_secret = u"shared"
  286. # Create the user
  287. request, channel = self.make_request("GET", "/_matrix/client/r0/admin/register")
  288. self.render(request)
  289. nonce = channel.json_body["nonce"]
  290. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  291. nonce_str = b"\x00".join([username.encode('utf8'), password.encode('utf8')])
  292. if admin:
  293. nonce_str += b"\x00admin"
  294. else:
  295. nonce_str += b"\x00notadmin"
  296. want_mac.update(nonce.encode('ascii') + b"\x00" + nonce_str)
  297. want_mac = want_mac.hexdigest()
  298. body = json.dumps(
  299. {
  300. "nonce": nonce,
  301. "username": username,
  302. "password": password,
  303. "admin": admin,
  304. "mac": want_mac,
  305. }
  306. )
  307. request, channel = self.make_request(
  308. "POST", "/_matrix/client/r0/admin/register", body.encode('utf8')
  309. )
  310. self.render(request)
  311. self.assertEqual(channel.code, 200)
  312. user_id = channel.json_body["user_id"]
  313. return user_id
  314. def login(self, username, password, device_id=None):
  315. """
  316. Log in a user, and get an access token. Requires the Login API be
  317. registered.
  318. """
  319. body = {"type": "m.login.password", "user": username, "password": password}
  320. if device_id:
  321. body["device_id"] = device_id
  322. request, channel = self.make_request(
  323. "POST", "/_matrix/client/r0/login", json.dumps(body).encode('utf8')
  324. )
  325. self.render(request)
  326. self.assertEqual(channel.code, 200)
  327. access_token = channel.json_body["access_token"]
  328. return access_token