unittest.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector
  3. # Copyright 2019 Matrix.org Federation C.I.C
  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 inspect
  20. import logging
  21. import secrets
  22. import time
  23. from typing import (
  24. Any,
  25. AnyStr,
  26. Callable,
  27. ClassVar,
  28. Dict,
  29. Iterable,
  30. List,
  31. Optional,
  32. Tuple,
  33. Type,
  34. TypeVar,
  35. Union,
  36. )
  37. from unittest.mock import Mock, patch
  38. from canonicaljson import json
  39. from twisted.internet.defer import Deferred, ensureDeferred, succeed
  40. from twisted.python.failure import Failure
  41. from twisted.python.threadpool import ThreadPool
  42. from twisted.test.proto_helpers import MemoryReactor
  43. from twisted.trial import unittest
  44. from twisted.web.resource import Resource
  45. from twisted.web.server import Request
  46. from synapse import events
  47. from synapse.api.constants import EventTypes, Membership
  48. from synapse.config.homeserver import HomeServerConfig
  49. from synapse.config.ratelimiting import FederationRateLimitConfig
  50. from synapse.federation.transport import server as federation_server
  51. from synapse.http.server import JsonResource
  52. from synapse.http.site import SynapseRequest, SynapseSite
  53. from synapse.logging.context import (
  54. SENTINEL_CONTEXT,
  55. LoggingContext,
  56. current_context,
  57. set_current_context,
  58. )
  59. from synapse.rest import RegisterServletsFunc
  60. from synapse.server import HomeServer
  61. from synapse.types import JsonDict, UserID, create_requester
  62. from synapse.util import Clock
  63. from synapse.util.httpresourcetree import create_resource_tree
  64. from synapse.util.ratelimitutils import FederationRateLimiter
  65. from tests.server import FakeChannel, get_clock, make_request, setup_test_homeserver
  66. from tests.test_utils import event_injection, setup_awaitable_errors
  67. from tests.test_utils.logging_setup import setup_logging
  68. from tests.utils import default_config, setupdb
  69. setupdb()
  70. setup_logging()
  71. def around(target):
  72. """A CLOS-style 'around' modifier, which wraps the original method of the
  73. given instance with another piece of code.
  74. @around(self)
  75. def method_name(orig, *args, **kwargs):
  76. return orig(*args, **kwargs)
  77. """
  78. def _around(code):
  79. name = code.__name__
  80. orig = getattr(target, name)
  81. def new(*args, **kwargs):
  82. return code(orig, *args, **kwargs)
  83. setattr(target, name, new)
  84. return _around
  85. class TestCase(unittest.TestCase):
  86. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  87. attributes on both itself and its individual test methods, to override the
  88. root logger's logging level while that test (case|method) runs."""
  89. def __init__(self, methodName: str):
  90. super().__init__(methodName)
  91. method = getattr(self, methodName)
  92. level = getattr(method, "loglevel", getattr(self, "loglevel", None))
  93. @around(self)
  94. def setUp(orig):
  95. # if we're not starting in the sentinel logcontext, then to be honest
  96. # all future bets are off.
  97. if current_context():
  98. self.fail(
  99. "Test starting with non-sentinel logging context %s"
  100. % (current_context(),)
  101. )
  102. old_level = logging.getLogger().level
  103. if level is not None and old_level != level:
  104. @around(self)
  105. def tearDown(orig):
  106. ret = orig()
  107. logging.getLogger().setLevel(old_level)
  108. return ret
  109. logging.getLogger().setLevel(level)
  110. # Trial messes with the warnings configuration, thus this has to be
  111. # done in the context of an individual TestCase.
  112. self.addCleanup(setup_awaitable_errors())
  113. return orig()
  114. @around(self)
  115. def tearDown(orig):
  116. ret = orig()
  117. # force a GC to workaround problems with deferreds leaking logcontexts when
  118. # they are GCed (see the logcontext docs)
  119. gc.collect()
  120. set_current_context(SENTINEL_CONTEXT)
  121. return ret
  122. def assertObjectHasAttributes(self, attrs, obj):
  123. """Asserts that the given object has each of the attributes given, and
  124. that the value of each matches according to assertEquals."""
  125. for key in attrs.keys():
  126. if not hasattr(obj, key):
  127. raise AssertionError("Expected obj to have a '.%s'" % key)
  128. try:
  129. self.assertEquals(attrs[key], getattr(obj, key))
  130. except AssertionError as e:
  131. raise (type(e))(f"Assert error for '.{key}':") from e
  132. def assert_dict(self, required, actual):
  133. """Does a partial assert of a dict.
  134. Args:
  135. required (dict): The keys and value which MUST be in 'actual'.
  136. actual (dict): The test result. Extra keys will not be checked.
  137. """
  138. for key in required:
  139. self.assertEquals(
  140. required[key], actual[key], msg="%s mismatch. %s" % (key, actual)
  141. )
  142. def DEBUG(target):
  143. """A decorator to set the .loglevel attribute to logging.DEBUG.
  144. Can apply to either a TestCase or an individual test method."""
  145. target.loglevel = logging.DEBUG
  146. return target
  147. def INFO(target):
  148. """A decorator to set the .loglevel attribute to logging.INFO.
  149. Can apply to either a TestCase or an individual test method."""
  150. target.loglevel = logging.INFO
  151. return target
  152. def logcontext_clean(target):
  153. """A decorator which marks the TestCase or method as 'logcontext_clean'
  154. ... ie, any logcontext errors should cause a test failure
  155. """
  156. def logcontext_error(msg):
  157. raise AssertionError("logcontext error: %s" % (msg))
  158. patcher = patch("synapse.logging.context.logcontext_error", new=logcontext_error)
  159. return patcher(target)
  160. class HomeserverTestCase(TestCase):
  161. """
  162. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  163. Defines a setUp method which creates a mock reactor, and instantiates a homeserver
  164. running on that reactor.
  165. There are various hooks for modifying the way that the homeserver is instantiated:
  166. * override make_homeserver, for example by making it pass different parameters into
  167. setup_test_homeserver.
  168. * override default_config, to return a modified configuration dictionary for use
  169. by setup_test_homeserver.
  170. * On a per-test basis, you can use the @override_config decorator to give a
  171. dictionary containing additional configuration settings to be added to the basic
  172. config dict.
  173. Attributes:
  174. servlets: List of servlet registration function.
  175. user_id (str): The user ID to assume if auth is hijacked.
  176. hijack_auth: Whether to hijack auth to return the user specified
  177. in user_id.
  178. """
  179. hijack_auth: ClassVar[bool] = True
  180. needs_threadpool: ClassVar[bool] = False
  181. servlets: ClassVar[List[RegisterServletsFunc]] = []
  182. def __init__(self, methodName: str):
  183. super().__init__(methodName)
  184. # see if we have any additional config for this test
  185. method = getattr(self, methodName)
  186. self._extra_config = getattr(method, "_extra_config", None)
  187. def setUp(self):
  188. """
  189. Set up the TestCase by calling the homeserver constructor, optionally
  190. hijacking the authentication system to return a fixed user, and then
  191. calling the prepare function.
  192. """
  193. self.reactor, self.clock = get_clock()
  194. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  195. self.hs = self.make_homeserver(self.reactor, self.clock)
  196. # Honour the `use_frozen_dicts` config option. We have to do this
  197. # manually because this is taken care of in the app `start` code, which
  198. # we don't run. Plus we want to reset it on tearDown.
  199. events.USE_FROZEN_DICTS = self.hs.config.server.use_frozen_dicts
  200. if self.hs is None:
  201. raise Exception("No homeserver returned from make_homeserver.")
  202. if not isinstance(self.hs, HomeServer):
  203. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  204. # create the root resource, and a site to wrap it.
  205. self.resource = self.create_test_resource()
  206. self.site = SynapseSite(
  207. logger_name="synapse.access.http.fake",
  208. site_tag=self.hs.config.server.server_name,
  209. config=self.hs.config.server.listeners[0],
  210. resource=self.resource,
  211. server_version_string="1",
  212. max_request_body_size=1234,
  213. reactor=self.reactor,
  214. )
  215. from tests.rest.client.utils import RestHelper
  216. self.helper = RestHelper(self.hs, self.site, getattr(self, "user_id", None))
  217. if hasattr(self, "user_id"):
  218. if self.hijack_auth:
  219. # We need a valid token ID to satisfy foreign key constraints.
  220. token_id = self.get_success(
  221. self.hs.get_datastore().add_access_token_to_user(
  222. self.helper.auth_user_id,
  223. "some_fake_token",
  224. None,
  225. None,
  226. )
  227. )
  228. async def get_user_by_access_token(token=None, allow_guest=False):
  229. return {
  230. "user": UserID.from_string(self.helper.auth_user_id),
  231. "token_id": token_id,
  232. "is_guest": False,
  233. }
  234. async def get_user_by_req(request, allow_guest=False, rights="access"):
  235. return create_requester(
  236. UserID.from_string(self.helper.auth_user_id),
  237. token_id,
  238. False,
  239. False,
  240. None,
  241. )
  242. # Type ignore: mypy doesn't like us assigning to methods.
  243. self.hs.get_auth().get_user_by_req = get_user_by_req # type: ignore[assignment]
  244. self.hs.get_auth().get_user_by_access_token = get_user_by_access_token # type: ignore[assignment]
  245. self.hs.get_auth().get_access_token_from_request = Mock( # type: ignore[assignment]
  246. return_value="1234"
  247. )
  248. if self.needs_threadpool:
  249. self.reactor.threadpool = ThreadPool()
  250. self.addCleanup(self.reactor.threadpool.stop)
  251. self.reactor.threadpool.start()
  252. if hasattr(self, "prepare"):
  253. self.prepare(self.reactor, self.clock, self.hs)
  254. def tearDown(self):
  255. # Reset to not use frozen dicts.
  256. events.USE_FROZEN_DICTS = False
  257. def wait_on_thread(self, deferred, timeout=10):
  258. """
  259. Wait until a Deferred is done, where it's waiting on a real thread.
  260. """
  261. start_time = time.time()
  262. while not deferred.called:
  263. if start_time + timeout < time.time():
  264. raise ValueError("Timed out waiting for threadpool")
  265. self.reactor.advance(0.01)
  266. time.sleep(0.01)
  267. def wait_for_background_updates(self) -> None:
  268. """Block until all background database updates have completed."""
  269. while not self.get_success(
  270. self.store.db_pool.updates.has_completed_background_updates()
  271. ):
  272. self.get_success(
  273. self.store.db_pool.updates.do_next_background_update(100), by=0.1
  274. )
  275. def make_homeserver(self, reactor, clock):
  276. """
  277. Make and return a homeserver.
  278. Args:
  279. reactor: A Twisted Reactor, or something that pretends to be one.
  280. clock (synapse.util.Clock): The Clock, associated with the reactor.
  281. Returns:
  282. A homeserver (synapse.server.HomeServer) suitable for testing.
  283. Function to be overridden in subclasses.
  284. """
  285. hs = self.setup_test_homeserver()
  286. return hs
  287. def create_test_resource(self) -> Resource:
  288. """
  289. Create a the root resource for the test server.
  290. The default calls `self.create_resource_dict` and builds the resultant dict
  291. into a tree.
  292. """
  293. root_resource = Resource()
  294. create_resource_tree(self.create_resource_dict(), root_resource)
  295. return root_resource
  296. def create_resource_dict(self) -> Dict[str, Resource]:
  297. """Create a resource tree for the test server
  298. A resource tree is a mapping from path to twisted.web.resource.
  299. The default implementation creates a JsonResource and calls each function in
  300. `servlets` to register servlets against it.
  301. """
  302. servlet_resource = JsonResource(self.hs)
  303. for servlet in self.servlets:
  304. servlet(self.hs, servlet_resource)
  305. return {
  306. "/_matrix/client": servlet_resource,
  307. "/_synapse/admin": servlet_resource,
  308. }
  309. def default_config(self):
  310. """
  311. Get a default HomeServer config dict.
  312. """
  313. config = default_config("test")
  314. # apply any additional config which was specified via the override_config
  315. # decorator.
  316. if self._extra_config is not None:
  317. config.update(self._extra_config)
  318. return config
  319. def prepare(self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer):
  320. """
  321. Prepare for the test. This involves things like mocking out parts of
  322. the homeserver, or building test data common across the whole test
  323. suite.
  324. Args:
  325. reactor: A Twisted Reactor, or something that pretends to be one.
  326. clock (synapse.util.Clock): The Clock, associated with the reactor.
  327. homeserver (synapse.server.HomeServer): The HomeServer to test
  328. against.
  329. Function to optionally be overridden in subclasses.
  330. """
  331. def make_request(
  332. self,
  333. method: Union[bytes, str],
  334. path: Union[bytes, str],
  335. content: Union[bytes, str, JsonDict] = b"",
  336. access_token: Optional[str] = None,
  337. request: Type[Request] = SynapseRequest,
  338. shorthand: bool = True,
  339. federation_auth_origin: Optional[bytes] = None,
  340. content_is_form: bool = False,
  341. await_result: bool = True,
  342. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  343. client_ip: str = "127.0.0.1",
  344. ) -> FakeChannel:
  345. """
  346. Create a SynapseRequest at the path using the method and containing the
  347. given content.
  348. Args:
  349. method (bytes/unicode): The HTTP request method ("verb").
  350. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  351. escaped UTF-8 & spaces and such).
  352. content (bytes or dict): The body of the request. JSON-encoded, if
  353. a dict.
  354. shorthand: Whether to try and be helpful and prefix the given URL
  355. with the usual REST API path, if it doesn't contain it.
  356. federation_auth_origin: if set to not-None, we will add a fake
  357. Authorization header pretenting to be the given server name.
  358. content_is_form: Whether the content is URL encoded form data. Adds the
  359. 'Content-Type': 'application/x-www-form-urlencoded' header.
  360. await_result: whether to wait for the request to complete rendering. If
  361. true (the default), will pump the test reactor until the the renderer
  362. tells the channel the request is finished.
  363. custom_headers: (name, value) pairs to add as request headers
  364. client_ip: The IP to use as the requesting IP. Useful for testing
  365. ratelimiting.
  366. Returns:
  367. The FakeChannel object which stores the result of the request.
  368. """
  369. return make_request(
  370. self.reactor,
  371. self.site,
  372. method,
  373. path,
  374. content,
  375. access_token,
  376. request,
  377. shorthand,
  378. federation_auth_origin,
  379. content_is_form,
  380. await_result,
  381. custom_headers,
  382. client_ip,
  383. )
  384. def setup_test_homeserver(self, *args: Any, **kwargs: Any) -> HomeServer:
  385. """
  386. Set up the test homeserver, meant to be called by the overridable
  387. make_homeserver. It automatically passes through the test class's
  388. clock & reactor.
  389. Args:
  390. See tests.utils.setup_test_homeserver.
  391. Returns:
  392. synapse.server.HomeServer
  393. """
  394. kwargs = dict(kwargs)
  395. kwargs.update(self._hs_args)
  396. if "config" not in kwargs:
  397. config = self.default_config()
  398. else:
  399. config = kwargs["config"]
  400. # Parse the config from a config dict into a HomeServerConfig
  401. config_obj = HomeServerConfig()
  402. config_obj.parse_config_dict(config, "", "")
  403. kwargs["config"] = config_obj
  404. async def run_bg_updates():
  405. with LoggingContext("run_bg_updates"):
  406. while not await stor.db_pool.updates.has_completed_background_updates():
  407. await stor.db_pool.updates.do_next_background_update(1)
  408. hs = setup_test_homeserver(self.addCleanup, *args, **kwargs)
  409. stor = hs.get_datastore()
  410. # Run the database background updates, when running against "master".
  411. if hs.__class__.__name__ == "TestHomeServer":
  412. self.get_success(run_bg_updates())
  413. return hs
  414. def pump(self, by=0.0):
  415. """
  416. Pump the reactor enough that Deferreds will fire.
  417. """
  418. self.reactor.pump([by] * 100)
  419. def get_success(self, d, by=0.0):
  420. if inspect.isawaitable(d):
  421. d = ensureDeferred(d)
  422. if not isinstance(d, Deferred):
  423. return d
  424. self.pump(by=by)
  425. return self.successResultOf(d)
  426. def get_failure(self, d, exc):
  427. """
  428. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  429. """
  430. if inspect.isawaitable(d):
  431. d = ensureDeferred(d)
  432. if not isinstance(d, Deferred):
  433. return d
  434. self.pump()
  435. return self.failureResultOf(d, exc)
  436. def get_success_or_raise(self, d, by=0.0):
  437. """Drive deferred to completion and return result or raise exception
  438. on failure.
  439. """
  440. if inspect.isawaitable(d):
  441. deferred = ensureDeferred(d)
  442. if not isinstance(deferred, Deferred):
  443. return d
  444. results: list = []
  445. deferred.addBoth(results.append)
  446. self.pump(by=by)
  447. if not results:
  448. self.fail(
  449. "Success result expected on {!r}, found no result instead".format(
  450. deferred
  451. )
  452. )
  453. result = results[0]
  454. if isinstance(result, Failure):
  455. result.raiseException()
  456. return result
  457. def register_user(
  458. self,
  459. username: str,
  460. password: str,
  461. admin: Optional[bool] = False,
  462. displayname: Optional[str] = None,
  463. ) -> str:
  464. """
  465. Register a user. Requires the Admin API be registered.
  466. Args:
  467. username: The user part of the new user.
  468. password: The password of the new user.
  469. admin: Whether the user should be created as an admin or not.
  470. displayname: The displayname of the new user.
  471. Returns:
  472. The MXID of the new user.
  473. """
  474. self.hs.config.registration.registration_shared_secret = "shared"
  475. # Create the user
  476. channel = self.make_request("GET", "/_synapse/admin/v1/register")
  477. self.assertEqual(channel.code, 200, msg=channel.result)
  478. nonce = channel.json_body["nonce"]
  479. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  480. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  481. if admin:
  482. nonce_str += b"\x00admin"
  483. else:
  484. nonce_str += b"\x00notadmin"
  485. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  486. want_mac_digest = want_mac.hexdigest()
  487. body = json.dumps(
  488. {
  489. "nonce": nonce,
  490. "username": username,
  491. "displayname": displayname,
  492. "password": password,
  493. "admin": admin,
  494. "mac": want_mac_digest,
  495. "inhibit_login": True,
  496. }
  497. )
  498. channel = self.make_request(
  499. "POST", "/_synapse/admin/v1/register", body.encode("utf8")
  500. )
  501. self.assertEqual(channel.code, 200, channel.json_body)
  502. user_id = channel.json_body["user_id"]
  503. return user_id
  504. def register_appservice_user(
  505. self,
  506. username: str,
  507. appservice_token: str,
  508. ) -> str:
  509. """Register an appservice user as an application service.
  510. Requires the client-facing registration API be registered.
  511. Args:
  512. username: the user to be registered by an application service.
  513. Should be a full username, i.e. ""@localpart:hostname" as opposed to just "localpart"
  514. appservice_token: the acccess token for that application service.
  515. Raises: if the request to '/register' does not return 200 OK.
  516. Returns: the MXID of the new user.
  517. """
  518. channel = self.make_request(
  519. "POST",
  520. "/_matrix/client/r0/register",
  521. {
  522. "username": username,
  523. "type": "m.login.application_service",
  524. },
  525. access_token=appservice_token,
  526. )
  527. self.assertEqual(channel.code, 200, channel.json_body)
  528. return channel.json_body["user_id"]
  529. def login(
  530. self,
  531. username,
  532. password,
  533. device_id=None,
  534. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  535. ):
  536. """
  537. Log in a user, and get an access token. Requires the Login API be
  538. registered.
  539. """
  540. body = {"type": "m.login.password", "user": username, "password": password}
  541. if device_id:
  542. body["device_id"] = device_id
  543. channel = self.make_request(
  544. "POST",
  545. "/_matrix/client/r0/login",
  546. json.dumps(body).encode("utf8"),
  547. custom_headers=custom_headers,
  548. )
  549. self.assertEqual(channel.code, 200, channel.result)
  550. access_token = channel.json_body["access_token"]
  551. return access_token
  552. def create_and_send_event(
  553. self, room_id, user, soft_failed=False, prev_event_ids=None
  554. ):
  555. """
  556. Create and send an event.
  557. Args:
  558. soft_failed (bool): Whether to create a soft failed event or not
  559. prev_event_ids (list[str]|None): Explicitly set the prev events,
  560. or if None just use the default
  561. Returns:
  562. str: The new event's ID.
  563. """
  564. event_creator = self.hs.get_event_creation_handler()
  565. requester = create_requester(user)
  566. event, context = self.get_success(
  567. event_creator.create_event(
  568. requester,
  569. {
  570. "type": EventTypes.Message,
  571. "room_id": room_id,
  572. "sender": user.to_string(),
  573. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  574. },
  575. prev_event_ids=prev_event_ids,
  576. )
  577. )
  578. if soft_failed:
  579. event.internal_metadata.soft_failed = True
  580. self.get_success(
  581. event_creator.handle_new_client_event(requester, event, context)
  582. )
  583. return event.event_id
  584. def add_extremity(self, room_id, event_id):
  585. """
  586. Add the given event as an extremity to the room.
  587. """
  588. self.get_success(
  589. self.hs.get_datastore().db_pool.simple_insert(
  590. table="event_forward_extremities",
  591. values={"room_id": room_id, "event_id": event_id},
  592. desc="test_add_extremity",
  593. )
  594. )
  595. self.hs.get_datastore().get_latest_event_ids_in_room.invalidate((room_id,))
  596. def attempt_wrong_password_login(self, username, password):
  597. """Attempts to login as the user with the given password, asserting
  598. that the attempt *fails*.
  599. """
  600. body = {"type": "m.login.password", "user": username, "password": password}
  601. channel = self.make_request(
  602. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  603. )
  604. self.assertEqual(channel.code, 403, channel.result)
  605. def inject_room_member(self, room: str, user: str, membership: Membership) -> None:
  606. """
  607. Inject a membership event into a room.
  608. Deprecated: use event_injection.inject_room_member directly
  609. Args:
  610. room: Room ID to inject the event into.
  611. user: MXID of the user to inject the membership for.
  612. membership: The membership type.
  613. """
  614. self.get_success(
  615. event_injection.inject_member_event(self.hs, room, user, membership)
  616. )
  617. class FederatingHomeserverTestCase(HomeserverTestCase):
  618. """
  619. A federating homeserver that authenticates incoming requests as `other.example.com`.
  620. """
  621. def create_resource_dict(self) -> Dict[str, Resource]:
  622. d = super().create_resource_dict()
  623. d["/_matrix/federation"] = TestTransportLayerServer(self.hs)
  624. return d
  625. class TestTransportLayerServer(JsonResource):
  626. """A test implementation of TransportLayerServer
  627. authenticates incoming requests as `other.example.com`.
  628. """
  629. def __init__(self, hs):
  630. super().__init__(hs)
  631. class Authenticator:
  632. def authenticate_request(self, request, content):
  633. return succeed("other.example.com")
  634. authenticator = Authenticator()
  635. ratelimiter = FederationRateLimiter(
  636. hs.get_clock(),
  637. FederationRateLimitConfig(
  638. window_size=1,
  639. sleep_limit=1,
  640. sleep_delay=1,
  641. reject_limit=1000,
  642. concurrent=1000,
  643. ),
  644. )
  645. federation_server.register_servlets(hs, self, authenticator, ratelimiter)
  646. def override_config(extra_config):
  647. """A decorator which can be applied to test functions to give additional HS config
  648. For use
  649. For example:
  650. class MyTestCase(HomeserverTestCase):
  651. @override_config({"enable_registration": False, ...})
  652. def test_foo(self):
  653. ...
  654. Args:
  655. extra_config(dict): Additional config settings to be merged into the default
  656. config dict before instantiating the test homeserver.
  657. """
  658. def decorator(func):
  659. func._extra_config = extra_config
  660. return func
  661. return decorator
  662. TV = TypeVar("TV")
  663. def skip_unless(condition: bool, reason: str) -> Callable[[TV], TV]:
  664. """A test decorator which will skip the decorated test unless a condition is set
  665. For example:
  666. class MyTestCase(TestCase):
  667. @skip_unless(HAS_FOO, "Cannot test without foo")
  668. def test_foo(self):
  669. ...
  670. Args:
  671. condition: If true, the test will be skipped
  672. reason: the reason to give for skipping the test
  673. """
  674. def decorator(f: TV) -> TV:
  675. if not condition:
  676. f.skip = reason # type: ignore
  677. return f
  678. return decorator