1
0

unittest.py 25 KB

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