unittest.py 13 KB

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