unittest.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector
  4. # Copyright 2019 Matrix.org Federation C.I.C
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import gc
  18. import hashlib
  19. import hmac
  20. import inspect
  21. import logging
  22. import time
  23. from typing import Dict, Iterable, Optional, Tuple, Type, TypeVar, Union
  24. from mock import Mock, patch
  25. from canonicaljson import json
  26. from twisted.internet.defer import Deferred, ensureDeferred, succeed
  27. from twisted.python.failure import Failure
  28. from twisted.python.threadpool import ThreadPool
  29. from twisted.trial import unittest
  30. from twisted.web.resource import Resource
  31. from synapse.api.constants import EventTypes, Membership
  32. from synapse.config.homeserver import HomeServerConfig
  33. from synapse.config.ratelimiting import FederationRateLimitConfig
  34. from synapse.federation.transport import server as federation_server
  35. from synapse.http.server import JsonResource
  36. from synapse.http.site import SynapseRequest, SynapseSite
  37. from synapse.logging.context import (
  38. SENTINEL_CONTEXT,
  39. LoggingContext,
  40. current_context,
  41. set_current_context,
  42. )
  43. from synapse.server import HomeServer
  44. from synapse.types import UserID, create_requester
  45. from synapse.util.httpresourcetree import create_resource_tree
  46. from synapse.util.ratelimitutils import FederationRateLimiter
  47. from tests.server import FakeChannel, get_clock, make_request, setup_test_homeserver
  48. from tests.test_utils import event_injection, setup_awaitable_errors
  49. from tests.test_utils.logging_setup import setup_logging
  50. from tests.utils import default_config, setupdb
  51. setupdb()
  52. setup_logging()
  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. T = TypeVar("T")
  68. class TestCase(unittest.TestCase):
  69. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  70. attributes on both itself and its individual test methods, to override the
  71. root logger's logging level while that test (case|method) runs."""
  72. def __init__(self, methodName, *args, **kwargs):
  73. super().__init__(methodName, *args, **kwargs)
  74. method = getattr(self, methodName)
  75. level = getattr(method, "loglevel", getattr(self, "loglevel", None))
  76. @around(self)
  77. def setUp(orig):
  78. # if we're not starting in the sentinel logcontext, then to be honest
  79. # all future bets are off.
  80. if current_context():
  81. self.fail(
  82. "Test starting with non-sentinel logging context %s"
  83. % (current_context(),)
  84. )
  85. old_level = logging.getLogger().level
  86. if level is not None and old_level != level:
  87. @around(self)
  88. def tearDown(orig):
  89. ret = orig()
  90. logging.getLogger().setLevel(old_level)
  91. return ret
  92. logging.getLogger().setLevel(level)
  93. # Trial messes with the warnings configuration, thus this has to be
  94. # done in the context of an individual TestCase.
  95. self.addCleanup(setup_awaitable_errors())
  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. set_current_context(SENTINEL_CONTEXT)
  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. def logcontext_clean(target):
  136. """A decorator which marks the TestCase or method as 'logcontext_clean'
  137. ... ie, any logcontext errors should cause a test failure
  138. """
  139. def logcontext_error(msg):
  140. raise AssertionError("logcontext error: %s" % (msg))
  141. patcher = patch("synapse.logging.context.logcontext_error", new=logcontext_error)
  142. return patcher(target)
  143. class HomeserverTestCase(TestCase):
  144. """
  145. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  146. Defines a setUp method which creates a mock reactor, and instantiates a homeserver
  147. running on that reactor.
  148. There are various hooks for modifying the way that the homeserver is instantiated:
  149. * override make_homeserver, for example by making it pass different parameters into
  150. setup_test_homeserver.
  151. * override default_config, to return a modified configuration dictionary for use
  152. by setup_test_homeserver.
  153. * On a per-test basis, you can use the @override_config decorator to give a
  154. dictionary containing additional configuration settings to be added to the basic
  155. config dict.
  156. Attributes:
  157. servlets (list[function]): List of servlet registration function.
  158. user_id (str): The user ID to assume if auth is hijacked.
  159. hijack_auth (bool): Whether to hijack auth to return the user specified
  160. in user_id.
  161. """
  162. servlets = []
  163. hijack_auth = True
  164. needs_threadpool = False
  165. def __init__(self, methodName, *args, **kwargs):
  166. super().__init__(methodName, *args, **kwargs)
  167. # see if we have any additional config for this test
  168. method = getattr(self, methodName)
  169. self._extra_config = getattr(method, "_extra_config", None)
  170. def setUp(self):
  171. """
  172. Set up the TestCase by calling the homeserver constructor, optionally
  173. hijacking the authentication system to return a fixed user, and then
  174. calling the prepare function.
  175. """
  176. self.reactor, self.clock = get_clock()
  177. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  178. self.hs = self.make_homeserver(self.reactor, self.clock)
  179. if self.hs is None:
  180. raise Exception("No homeserver returned from make_homeserver.")
  181. if not isinstance(self.hs, HomeServer):
  182. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  183. # create the root resource, and a site to wrap it.
  184. self.resource = self.create_test_resource()
  185. self.site = SynapseSite(
  186. logger_name="synapse.access.http.fake",
  187. site_tag=self.hs.config.server.server_name,
  188. config=self.hs.config.server.listeners[0],
  189. resource=self.resource,
  190. server_version_string="1",
  191. )
  192. from tests.rest.client.v1.utils import RestHelper
  193. self.helper = RestHelper(self.hs, self.site, getattr(self, "user_id", None))
  194. if hasattr(self, "user_id"):
  195. if self.hijack_auth:
  196. # We need a valid token ID to satisfy foreign key constraints.
  197. token_id = self.get_success(
  198. self.hs.get_datastore().add_access_token_to_user(
  199. self.helper.auth_user_id, "some_fake_token", None, None,
  200. )
  201. )
  202. async def get_user_by_access_token(token=None, allow_guest=False):
  203. return {
  204. "user": UserID.from_string(self.helper.auth_user_id),
  205. "token_id": token_id,
  206. "is_guest": False,
  207. }
  208. async def get_user_by_req(request, allow_guest=False, rights="access"):
  209. return create_requester(
  210. UserID.from_string(self.helper.auth_user_id),
  211. token_id,
  212. False,
  213. False,
  214. None,
  215. )
  216. self.hs.get_auth().get_user_by_req = get_user_by_req
  217. self.hs.get_auth().get_user_by_access_token = get_user_by_access_token
  218. self.hs.get_auth().get_access_token_from_request = Mock(
  219. return_value="1234"
  220. )
  221. if self.needs_threadpool:
  222. self.reactor.threadpool = ThreadPool()
  223. self.addCleanup(self.reactor.threadpool.stop)
  224. self.reactor.threadpool.start()
  225. if hasattr(self, "prepare"):
  226. self.prepare(self.reactor, self.clock, self.hs)
  227. def wait_on_thread(self, deferred, timeout=10):
  228. """
  229. Wait until a Deferred is done, where it's waiting on a real thread.
  230. """
  231. start_time = time.time()
  232. while not deferred.called:
  233. if start_time + timeout < time.time():
  234. raise ValueError("Timed out waiting for threadpool")
  235. self.reactor.advance(0.01)
  236. time.sleep(0.01)
  237. def make_homeserver(self, reactor, clock):
  238. """
  239. Make and return a homeserver.
  240. Args:
  241. reactor: A Twisted Reactor, or something that pretends to be one.
  242. clock (synapse.util.Clock): The Clock, associated with the reactor.
  243. Returns:
  244. A homeserver (synapse.server.HomeServer) suitable for testing.
  245. Function to be overridden in subclasses.
  246. """
  247. hs = self.setup_test_homeserver()
  248. return hs
  249. def create_test_resource(self) -> Resource:
  250. """
  251. Create a the root resource for the test server.
  252. The default calls `self.create_resource_dict` and builds the resultant dict
  253. into a tree.
  254. """
  255. root_resource = Resource()
  256. create_resource_tree(self.create_resource_dict(), root_resource)
  257. return root_resource
  258. def create_resource_dict(self) -> Dict[str, Resource]:
  259. """Create a resource tree for the test server
  260. A resource tree is a mapping from path to twisted.web.resource.
  261. The default implementation creates a JsonResource and calls each function in
  262. `servlets` to register servlets against it.
  263. """
  264. servlet_resource = JsonResource(self.hs)
  265. for servlet in self.servlets:
  266. servlet(self.hs, servlet_resource)
  267. return {
  268. "/_matrix/client": servlet_resource,
  269. "/_synapse/admin": servlet_resource,
  270. }
  271. def default_config(self):
  272. """
  273. Get a default HomeServer config dict.
  274. """
  275. config = default_config("test")
  276. # apply any additional config which was specified via the override_config
  277. # decorator.
  278. if self._extra_config is not None:
  279. config.update(self._extra_config)
  280. return config
  281. def prepare(self, reactor, clock, homeserver):
  282. """
  283. Prepare for the test. This involves things like mocking out parts of
  284. the homeserver, or building test data common across the whole test
  285. suite.
  286. Args:
  287. reactor: A Twisted Reactor, or something that pretends to be one.
  288. clock (synapse.util.Clock): The Clock, associated with the reactor.
  289. homeserver (synapse.server.HomeServer): The HomeServer to test
  290. against.
  291. Function to optionally be overridden in subclasses.
  292. """
  293. def make_request(
  294. self,
  295. method: Union[bytes, str],
  296. path: Union[bytes, str],
  297. content: Union[bytes, dict] = b"",
  298. access_token: Optional[str] = None,
  299. request: Type[T] = SynapseRequest,
  300. shorthand: bool = True,
  301. federation_auth_origin: str = None,
  302. content_is_form: bool = False,
  303. await_result: bool = True,
  304. custom_headers: Optional[
  305. Iterable[Tuple[Union[bytes, str], Union[bytes, str]]]
  306. ] = None,
  307. ) -> FakeChannel:
  308. """
  309. Create a SynapseRequest at the path using the method and containing the
  310. given content.
  311. Args:
  312. method (bytes/unicode): The HTTP request method ("verb").
  313. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  314. escaped UTF-8 & spaces and such).
  315. content (bytes or dict): The body of the request. JSON-encoded, if
  316. a dict.
  317. shorthand: Whether to try and be helpful and prefix the given URL
  318. with the usual REST API path, if it doesn't contain it.
  319. federation_auth_origin (bytes|None): if set to not-None, we will add a fake
  320. Authorization header pretenting to be the given server name.
  321. content_is_form: Whether the content is URL encoded form data. Adds the
  322. 'Content-Type': 'application/x-www-form-urlencoded' header.
  323. await_result: whether to wait for the request to complete rendering. If
  324. true (the default), will pump the test reactor until the the renderer
  325. tells the channel the request is finished.
  326. custom_headers: (name, value) pairs to add as request headers
  327. Returns:
  328. The FakeChannel object which stores the result of the request.
  329. """
  330. return make_request(
  331. self.reactor,
  332. self.site,
  333. method,
  334. path,
  335. content,
  336. access_token,
  337. request,
  338. shorthand,
  339. federation_auth_origin,
  340. content_is_form,
  341. await_result,
  342. custom_headers,
  343. )
  344. def setup_test_homeserver(self, *args, **kwargs):
  345. """
  346. Set up the test homeserver, meant to be called by the overridable
  347. make_homeserver. It automatically passes through the test class's
  348. clock & reactor.
  349. Args:
  350. See tests.utils.setup_test_homeserver.
  351. Returns:
  352. synapse.server.HomeServer
  353. """
  354. kwargs = dict(kwargs)
  355. kwargs.update(self._hs_args)
  356. if "config" not in kwargs:
  357. config = self.default_config()
  358. else:
  359. config = kwargs["config"]
  360. # Parse the config from a config dict into a HomeServerConfig
  361. config_obj = HomeServerConfig()
  362. config_obj.parse_config_dict(config, "", "")
  363. kwargs["config"] = config_obj
  364. async def run_bg_updates():
  365. with LoggingContext("run_bg_updates", request="run_bg_updates-1"):
  366. while not await stor.db_pool.updates.has_completed_background_updates():
  367. await stor.db_pool.updates.do_next_background_update(1)
  368. hs = setup_test_homeserver(self.addCleanup, *args, **kwargs)
  369. stor = hs.get_datastore()
  370. # Run the database background updates, when running against "master".
  371. if hs.__class__.__name__ == "TestHomeServer":
  372. self.get_success(run_bg_updates())
  373. return hs
  374. def pump(self, by=0.0):
  375. """
  376. Pump the reactor enough that Deferreds will fire.
  377. """
  378. self.reactor.pump([by] * 100)
  379. def get_success(self, d, by=0.0):
  380. if inspect.isawaitable(d):
  381. d = ensureDeferred(d)
  382. if not isinstance(d, Deferred):
  383. return d
  384. self.pump(by=by)
  385. return self.successResultOf(d)
  386. def get_failure(self, d, exc):
  387. """
  388. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  389. """
  390. if inspect.isawaitable(d):
  391. d = ensureDeferred(d)
  392. if not isinstance(d, Deferred):
  393. return d
  394. self.pump()
  395. return self.failureResultOf(d, exc)
  396. def get_success_or_raise(self, d, by=0.0):
  397. """Drive deferred to completion and return result or raise exception
  398. on failure.
  399. """
  400. if inspect.isawaitable(d):
  401. deferred = ensureDeferred(d)
  402. if not isinstance(deferred, Deferred):
  403. return d
  404. results = [] # type: list
  405. deferred.addBoth(results.append)
  406. self.pump(by=by)
  407. if not results:
  408. self.fail(
  409. "Success result expected on {!r}, found no result instead".format(
  410. deferred
  411. )
  412. )
  413. result = results[0]
  414. if isinstance(result, Failure):
  415. result.raiseException()
  416. return result
  417. def register_user(
  418. self,
  419. username: str,
  420. password: str,
  421. admin: Optional[bool] = False,
  422. displayname: Optional[str] = None,
  423. ) -> str:
  424. """
  425. Register a user. Requires the Admin API be registered.
  426. Args:
  427. username: The user part of the new user.
  428. password: The password of the new user.
  429. admin: Whether the user should be created as an admin or not.
  430. displayname: The displayname of the new user.
  431. Returns:
  432. The MXID of the new user.
  433. """
  434. self.hs.config.registration_shared_secret = "shared"
  435. # Create the user
  436. channel = self.make_request("GET", "/_synapse/admin/v1/register")
  437. self.assertEqual(channel.code, 200, msg=channel.result)
  438. nonce = channel.json_body["nonce"]
  439. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  440. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  441. if admin:
  442. nonce_str += b"\x00admin"
  443. else:
  444. nonce_str += b"\x00notadmin"
  445. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  446. want_mac = want_mac.hexdigest()
  447. body = json.dumps(
  448. {
  449. "nonce": nonce,
  450. "username": username,
  451. "displayname": displayname,
  452. "password": password,
  453. "admin": admin,
  454. "mac": want_mac,
  455. "inhibit_login": True,
  456. }
  457. )
  458. channel = self.make_request(
  459. "POST", "/_synapse/admin/v1/register", body.encode("utf8")
  460. )
  461. self.assertEqual(channel.code, 200, channel.json_body)
  462. user_id = channel.json_body["user_id"]
  463. return user_id
  464. def login(self, username, password, device_id=None):
  465. """
  466. Log in a user, and get an access token. Requires the Login API be
  467. registered.
  468. """
  469. body = {"type": "m.login.password", "user": username, "password": password}
  470. if device_id:
  471. body["device_id"] = device_id
  472. channel = self.make_request(
  473. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  474. )
  475. self.assertEqual(channel.code, 200, channel.result)
  476. access_token = channel.json_body["access_token"]
  477. return access_token
  478. def create_and_send_event(
  479. self, room_id, user, soft_failed=False, prev_event_ids=None
  480. ):
  481. """
  482. Create and send an event.
  483. Args:
  484. soft_failed (bool): Whether to create a soft failed event or not
  485. prev_event_ids (list[str]|None): Explicitly set the prev events,
  486. or if None just use the default
  487. Returns:
  488. str: The new event's ID.
  489. """
  490. event_creator = self.hs.get_event_creation_handler()
  491. secrets = self.hs.get_secrets()
  492. requester = create_requester(user)
  493. event, context = self.get_success(
  494. event_creator.create_event(
  495. requester,
  496. {
  497. "type": EventTypes.Message,
  498. "room_id": room_id,
  499. "sender": user.to_string(),
  500. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  501. },
  502. prev_event_ids=prev_event_ids,
  503. )
  504. )
  505. if soft_failed:
  506. event.internal_metadata.soft_failed = True
  507. self.get_success(
  508. event_creator.handle_new_client_event(requester, event, context)
  509. )
  510. return event.event_id
  511. def add_extremity(self, room_id, event_id):
  512. """
  513. Add the given event as an extremity to the room.
  514. """
  515. self.get_success(
  516. self.hs.get_datastore().db_pool.simple_insert(
  517. table="event_forward_extremities",
  518. values={"room_id": room_id, "event_id": event_id},
  519. desc="test_add_extremity",
  520. )
  521. )
  522. self.hs.get_datastore().get_latest_event_ids_in_room.invalidate((room_id,))
  523. def attempt_wrong_password_login(self, username, password):
  524. """Attempts to login as the user with the given password, asserting
  525. that the attempt *fails*.
  526. """
  527. body = {"type": "m.login.password", "user": username, "password": password}
  528. channel = self.make_request(
  529. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  530. )
  531. self.assertEqual(channel.code, 403, channel.result)
  532. def inject_room_member(self, room: str, user: str, membership: Membership) -> None:
  533. """
  534. Inject a membership event into a room.
  535. Deprecated: use event_injection.inject_room_member directly
  536. Args:
  537. room: Room ID to inject the event into.
  538. user: MXID of the user to inject the membership for.
  539. membership: The membership type.
  540. """
  541. self.get_success(
  542. event_injection.inject_member_event(self.hs, room, user, membership)
  543. )
  544. class FederatingHomeserverTestCase(HomeserverTestCase):
  545. """
  546. A federating homeserver that authenticates incoming requests as `other.example.com`.
  547. """
  548. def create_resource_dict(self) -> Dict[str, Resource]:
  549. d = super().create_resource_dict()
  550. d["/_matrix/federation"] = TestTransportLayerServer(self.hs)
  551. return d
  552. class TestTransportLayerServer(JsonResource):
  553. """A test implementation of TransportLayerServer
  554. authenticates incoming requests as `other.example.com`.
  555. """
  556. def __init__(self, hs):
  557. super().__init__(hs)
  558. class Authenticator:
  559. def authenticate_request(self, request, content):
  560. return succeed("other.example.com")
  561. authenticator = Authenticator()
  562. ratelimiter = FederationRateLimiter(
  563. hs.get_clock(),
  564. FederationRateLimitConfig(
  565. window_size=1,
  566. sleep_limit=1,
  567. sleep_msec=1,
  568. reject_limit=1000,
  569. concurrent_requests=1000,
  570. ),
  571. )
  572. federation_server.register_servlets(hs, self, authenticator, ratelimiter)
  573. def override_config(extra_config):
  574. """A decorator which can be applied to test functions to give additional HS config
  575. For use
  576. For example:
  577. class MyTestCase(HomeserverTestCase):
  578. @override_config({"enable_registration": False, ...})
  579. def test_foo(self):
  580. ...
  581. Args:
  582. extra_config(dict): Additional config settings to be merged into the default
  583. config dict before instantiating the test homeserver.
  584. """
  585. def decorator(func):
  586. func._extra_config = extra_config
  587. return func
  588. return decorator