unittest.py 24 KB

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