You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

834 lines
27 KiB

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