unittest.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. Note that callers must ensure there's a store property created on the
  270. testcase.
  271. """
  272. while not self.get_success(
  273. self.store.db_pool.updates.has_completed_background_updates()
  274. ):
  275. self.get_success(
  276. self.store.db_pool.updates.do_next_background_update(False), by=0.1
  277. )
  278. def make_homeserver(self, reactor, clock):
  279. """
  280. Make and return a homeserver.
  281. Args:
  282. reactor: A Twisted Reactor, or something that pretends to be one.
  283. clock (synapse.util.Clock): The Clock, associated with the reactor.
  284. Returns:
  285. A homeserver (synapse.server.HomeServer) suitable for testing.
  286. Function to be overridden in subclasses.
  287. """
  288. hs = self.setup_test_homeserver()
  289. return hs
  290. def create_test_resource(self) -> Resource:
  291. """
  292. Create a the root resource for the test server.
  293. The default calls `self.create_resource_dict` and builds the resultant dict
  294. into a tree.
  295. """
  296. root_resource = Resource()
  297. create_resource_tree(self.create_resource_dict(), root_resource)
  298. return root_resource
  299. def create_resource_dict(self) -> Dict[str, Resource]:
  300. """Create a resource tree for the test server
  301. A resource tree is a mapping from path to twisted.web.resource.
  302. The default implementation creates a JsonResource and calls each function in
  303. `servlets` to register servlets against it.
  304. """
  305. servlet_resource = JsonResource(self.hs)
  306. for servlet in self.servlets:
  307. servlet(self.hs, servlet_resource)
  308. return {
  309. "/_matrix/client": servlet_resource,
  310. "/_synapse/admin": servlet_resource,
  311. }
  312. def default_config(self):
  313. """
  314. Get a default HomeServer config dict.
  315. """
  316. config = default_config("test")
  317. # apply any additional config which was specified via the override_config
  318. # decorator.
  319. if self._extra_config is not None:
  320. config.update(self._extra_config)
  321. return config
  322. def prepare(self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer):
  323. """
  324. Prepare for the test. This involves things like mocking out parts of
  325. the homeserver, or building test data common across the whole test
  326. suite.
  327. Args:
  328. reactor: A Twisted Reactor, or something that pretends to be one.
  329. clock (synapse.util.Clock): The Clock, associated with the reactor.
  330. homeserver (synapse.server.HomeServer): The HomeServer to test
  331. against.
  332. Function to optionally be overridden in subclasses.
  333. """
  334. def make_request(
  335. self,
  336. method: Union[bytes, str],
  337. path: Union[bytes, str],
  338. content: Union[bytes, str, JsonDict] = b"",
  339. access_token: Optional[str] = None,
  340. request: Type[Request] = SynapseRequest,
  341. shorthand: bool = True,
  342. federation_auth_origin: Optional[bytes] = None,
  343. content_is_form: bool = False,
  344. await_result: bool = True,
  345. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  346. client_ip: str = "127.0.0.1",
  347. ) -> FakeChannel:
  348. """
  349. Create a SynapseRequest at the path using the method and containing the
  350. given content.
  351. Args:
  352. method (bytes/unicode): The HTTP request method ("verb").
  353. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  354. escaped UTF-8 & spaces and such).
  355. content (bytes or dict): The body of the request. JSON-encoded, if
  356. a dict.
  357. shorthand: Whether to try and be helpful and prefix the given URL
  358. with the usual REST API path, if it doesn't contain it.
  359. federation_auth_origin: if set to not-None, we will add a fake
  360. Authorization header pretenting to be the given server name.
  361. content_is_form: Whether the content is URL encoded form data. Adds the
  362. 'Content-Type': 'application/x-www-form-urlencoded' header.
  363. await_result: whether to wait for the request to complete rendering. If
  364. true (the default), will pump the test reactor until the the renderer
  365. tells the channel the request is finished.
  366. custom_headers: (name, value) pairs to add as request headers
  367. client_ip: The IP to use as the requesting IP. Useful for testing
  368. ratelimiting.
  369. Returns:
  370. The FakeChannel object which stores the result of the request.
  371. """
  372. return make_request(
  373. self.reactor,
  374. self.site,
  375. method,
  376. path,
  377. content,
  378. access_token,
  379. request,
  380. shorthand,
  381. federation_auth_origin,
  382. content_is_form,
  383. await_result,
  384. custom_headers,
  385. client_ip,
  386. )
  387. def setup_test_homeserver(self, *args: Any, **kwargs: Any) -> HomeServer:
  388. """
  389. Set up the test homeserver, meant to be called by the overridable
  390. make_homeserver. It automatically passes through the test class's
  391. clock & reactor.
  392. Args:
  393. See tests.utils.setup_test_homeserver.
  394. Returns:
  395. synapse.server.HomeServer
  396. """
  397. kwargs = dict(kwargs)
  398. kwargs.update(self._hs_args)
  399. if "config" not in kwargs:
  400. config = self.default_config()
  401. else:
  402. config = kwargs["config"]
  403. # Parse the config from a config dict into a HomeServerConfig
  404. config_obj = HomeServerConfig()
  405. config_obj.parse_config_dict(config, "", "")
  406. kwargs["config"] = config_obj
  407. async def run_bg_updates():
  408. with LoggingContext("run_bg_updates"):
  409. self.get_success(stor.db_pool.updates.run_background_updates(False))
  410. hs = setup_test_homeserver(self.addCleanup, *args, **kwargs)
  411. stor = hs.get_datastore()
  412. # Run the database background updates, when running against "master".
  413. if hs.__class__.__name__ == "TestHomeServer":
  414. self.get_success(run_bg_updates())
  415. return hs
  416. def pump(self, by=0.0):
  417. """
  418. Pump the reactor enough that Deferreds will fire.
  419. """
  420. self.reactor.pump([by] * 100)
  421. def get_success(self, d, by=0.0):
  422. if inspect.isawaitable(d):
  423. d = ensureDeferred(d)
  424. if not isinstance(d, Deferred):
  425. return d
  426. self.pump(by=by)
  427. return self.successResultOf(d)
  428. def get_failure(self, d, exc):
  429. """
  430. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  431. """
  432. if inspect.isawaitable(d):
  433. d = ensureDeferred(d)
  434. if not isinstance(d, Deferred):
  435. return d
  436. self.pump()
  437. return self.failureResultOf(d, exc)
  438. def get_success_or_raise(self, d, by=0.0):
  439. """Drive deferred to completion and return result or raise exception
  440. on failure.
  441. """
  442. if inspect.isawaitable(d):
  443. deferred = ensureDeferred(d)
  444. if not isinstance(deferred, Deferred):
  445. return d
  446. results: list = []
  447. deferred.addBoth(results.append)
  448. self.pump(by=by)
  449. if not results:
  450. self.fail(
  451. "Success result expected on {!r}, found no result instead".format(
  452. deferred
  453. )
  454. )
  455. result = results[0]
  456. if isinstance(result, Failure):
  457. result.raiseException()
  458. return result
  459. def register_user(
  460. self,
  461. username: str,
  462. password: str,
  463. admin: Optional[bool] = False,
  464. displayname: Optional[str] = None,
  465. ) -> str:
  466. """
  467. Register a user. Requires the Admin API be registered.
  468. Args:
  469. username: The user part of the new user.
  470. password: The password of the new user.
  471. admin: Whether the user should be created as an admin or not.
  472. displayname: The displayname of the new user.
  473. Returns:
  474. The MXID of the new user.
  475. """
  476. self.hs.config.registration.registration_shared_secret = "shared"
  477. # Create the user
  478. channel = self.make_request("GET", "/_synapse/admin/v1/register")
  479. self.assertEqual(channel.code, 200, msg=channel.result)
  480. nonce = channel.json_body["nonce"]
  481. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  482. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  483. if admin:
  484. nonce_str += b"\x00admin"
  485. else:
  486. nonce_str += b"\x00notadmin"
  487. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  488. want_mac_digest = want_mac.hexdigest()
  489. body = json.dumps(
  490. {
  491. "nonce": nonce,
  492. "username": username,
  493. "displayname": displayname,
  494. "password": password,
  495. "admin": admin,
  496. "mac": want_mac_digest,
  497. "inhibit_login": True,
  498. }
  499. )
  500. channel = self.make_request(
  501. "POST", "/_synapse/admin/v1/register", body.encode("utf8")
  502. )
  503. self.assertEqual(channel.code, 200, channel.json_body)
  504. user_id = channel.json_body["user_id"]
  505. return user_id
  506. def register_appservice_user(
  507. self,
  508. username: str,
  509. appservice_token: str,
  510. ) -> str:
  511. """Register an appservice user as an application service.
  512. Requires the client-facing registration API be registered.
  513. Args:
  514. username: the user to be registered by an application service.
  515. Should be a full username, i.e. ""@localpart:hostname" as opposed to just "localpart"
  516. appservice_token: the acccess token for that application service.
  517. Raises: if the request to '/register' does not return 200 OK.
  518. Returns: the MXID of the new user.
  519. """
  520. channel = self.make_request(
  521. "POST",
  522. "/_matrix/client/r0/register",
  523. {
  524. "username": username,
  525. "type": "m.login.application_service",
  526. },
  527. access_token=appservice_token,
  528. )
  529. self.assertEqual(channel.code, 200, channel.json_body)
  530. return channel.json_body["user_id"]
  531. def login(
  532. self,
  533. username,
  534. password,
  535. device_id=None,
  536. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  537. ):
  538. """
  539. Log in a user, and get an access token. Requires the Login API be
  540. registered.
  541. """
  542. body = {"type": "m.login.password", "user": username, "password": password}
  543. if device_id:
  544. body["device_id"] = device_id
  545. channel = self.make_request(
  546. "POST",
  547. "/_matrix/client/r0/login",
  548. json.dumps(body).encode("utf8"),
  549. custom_headers=custom_headers,
  550. )
  551. self.assertEqual(channel.code, 200, channel.result)
  552. access_token = channel.json_body["access_token"]
  553. return access_token
  554. def create_and_send_event(
  555. self, room_id, user, soft_failed=False, prev_event_ids=None
  556. ):
  557. """
  558. Create and send an event.
  559. Args:
  560. soft_failed (bool): Whether to create a soft failed event or not
  561. prev_event_ids (list[str]|None): Explicitly set the prev events,
  562. or if None just use the default
  563. Returns:
  564. str: The new event's ID.
  565. """
  566. event_creator = self.hs.get_event_creation_handler()
  567. requester = create_requester(user)
  568. event, context = self.get_success(
  569. event_creator.create_event(
  570. requester,
  571. {
  572. "type": EventTypes.Message,
  573. "room_id": room_id,
  574. "sender": user.to_string(),
  575. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  576. },
  577. prev_event_ids=prev_event_ids,
  578. )
  579. )
  580. if soft_failed:
  581. event.internal_metadata.soft_failed = True
  582. self.get_success(
  583. event_creator.handle_new_client_event(requester, event, context)
  584. )
  585. return event.event_id
  586. def add_extremity(self, room_id, event_id):
  587. """
  588. Add the given event as an extremity to the room.
  589. """
  590. self.get_success(
  591. self.hs.get_datastore().db_pool.simple_insert(
  592. table="event_forward_extremities",
  593. values={"room_id": room_id, "event_id": event_id},
  594. desc="test_add_extremity",
  595. )
  596. )
  597. self.hs.get_datastore().get_latest_event_ids_in_room.invalidate((room_id,))
  598. def attempt_wrong_password_login(self, username, password):
  599. """Attempts to login as the user with the given password, asserting
  600. that the attempt *fails*.
  601. """
  602. body = {"type": "m.login.password", "user": username, "password": password}
  603. channel = self.make_request(
  604. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  605. )
  606. self.assertEqual(channel.code, 403, channel.result)
  607. def inject_room_member(self, room: str, user: str, membership: Membership) -> None:
  608. """
  609. Inject a membership event into a room.
  610. Deprecated: use event_injection.inject_room_member directly
  611. Args:
  612. room: Room ID to inject the event into.
  613. user: MXID of the user to inject the membership for.
  614. membership: The membership type.
  615. """
  616. self.get_success(
  617. event_injection.inject_member_event(self.hs, room, user, membership)
  618. )
  619. class FederatingHomeserverTestCase(HomeserverTestCase):
  620. """
  621. A federating homeserver that authenticates incoming requests as `other.example.com`.
  622. """
  623. def create_resource_dict(self) -> Dict[str, Resource]:
  624. d = super().create_resource_dict()
  625. d["/_matrix/federation"] = TestTransportLayerServer(self.hs)
  626. return d
  627. class TestTransportLayerServer(JsonResource):
  628. """A test implementation of TransportLayerServer
  629. authenticates incoming requests as `other.example.com`.
  630. """
  631. def __init__(self, hs):
  632. super().__init__(hs)
  633. class Authenticator:
  634. def authenticate_request(self, request, content):
  635. return succeed("other.example.com")
  636. authenticator = Authenticator()
  637. ratelimiter = FederationRateLimiter(
  638. hs.get_clock(),
  639. FederationRateLimitConfig(
  640. window_size=1,
  641. sleep_limit=1,
  642. sleep_delay=1,
  643. reject_limit=1000,
  644. concurrent=1000,
  645. ),
  646. )
  647. federation_server.register_servlets(hs, self, authenticator, ratelimiter)
  648. def override_config(extra_config):
  649. """A decorator which can be applied to test functions to give additional HS config
  650. For use
  651. For example:
  652. class MyTestCase(HomeserverTestCase):
  653. @override_config({"enable_registration": False, ...})
  654. def test_foo(self):
  655. ...
  656. Args:
  657. extra_config(dict): Additional config settings to be merged into the default
  658. config dict before instantiating the test homeserver.
  659. """
  660. def decorator(func):
  661. func._extra_config = extra_config
  662. return func
  663. return decorator
  664. TV = TypeVar("TV")
  665. def skip_unless(condition: bool, reason: str) -> Callable[[TV], TV]:
  666. """A test decorator which will skip the decorated test unless a condition is set
  667. For example:
  668. class MyTestCase(TestCase):
  669. @skip_unless(HAS_FOO, "Cannot test without foo")
  670. def test_foo(self):
  671. ...
  672. Args:
  673. condition: If true, the test will be skipped
  674. reason: the reason to give for skipping the test
  675. """
  676. def decorator(f: TV) -> TV:
  677. if not condition:
  678. f.skip = reason # type: ignore
  679. return f
  680. return decorator