unittest.py 26 KB

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