1
0

unittest.py 19 KB

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