unittest.py 17 KB

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