unittest.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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
  24. from mock import Mock
  25. from canonicaljson import json
  26. from twisted.internet.defer import Deferred, ensureDeferred, succeed
  27. from twisted.python.threadpool import ThreadPool
  28. from twisted.trial import unittest
  29. from synapse.api.constants import EventTypes, Membership
  30. from synapse.config.homeserver import HomeServerConfig
  31. from synapse.config.ratelimiting import FederationRateLimitConfig
  32. from synapse.federation.transport import server as federation_server
  33. from synapse.http.server import JsonResource
  34. from synapse.http.site import SynapseRequest, SynapseSite
  35. from synapse.logging.context import (
  36. SENTINEL_CONTEXT,
  37. LoggingContext,
  38. current_context,
  39. set_current_context,
  40. )
  41. from synapse.server import HomeServer
  42. from synapse.types import Requester, UserID, create_requester
  43. from synapse.util.ratelimitutils import FederationRateLimiter
  44. from tests.server import (
  45. FakeChannel,
  46. get_clock,
  47. make_request,
  48. render,
  49. setup_test_homeserver,
  50. )
  51. from tests.test_utils import event_injection
  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. 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. class HomeserverTestCase(TestCase):
  136. """
  137. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  138. Defines a setUp method which creates a mock reactor, and instantiates a homeserver
  139. running on that reactor.
  140. There are various hooks for modifying the way that the homeserver is instantiated:
  141. * override make_homeserver, for example by making it pass different parameters into
  142. setup_test_homeserver.
  143. * override default_config, to return a modified configuration dictionary for use
  144. by setup_test_homeserver.
  145. * On a per-test basis, you can use the @override_config decorator to give a
  146. dictionary containing additional configuration settings to be added to the basic
  147. config dict.
  148. Attributes:
  149. servlets (list[function]): List of servlet registration function.
  150. user_id (str): The user ID to assume if auth is hijacked.
  151. hijack_auth (bool): Whether to hijack auth to return the user specified
  152. in user_id.
  153. """
  154. servlets = []
  155. hijack_auth = True
  156. needs_threadpool = False
  157. def __init__(self, methodName, *args, **kwargs):
  158. super().__init__(methodName, *args, **kwargs)
  159. # see if we have any additional config for this test
  160. method = getattr(self, methodName)
  161. self._extra_config = getattr(method, "_extra_config", None)
  162. def setUp(self):
  163. """
  164. Set up the TestCase by calling the homeserver constructor, optionally
  165. hijacking the authentication system to return a fixed user, and then
  166. calling the prepare function.
  167. """
  168. self.reactor, self.clock = get_clock()
  169. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  170. self.hs = self.make_homeserver(self.reactor, self.clock)
  171. if self.hs is None:
  172. raise Exception("No homeserver returned from make_homeserver.")
  173. if not isinstance(self.hs, HomeServer):
  174. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  175. # Register the resources
  176. self.resource = self.create_test_json_resource()
  177. # create a site to wrap the resource.
  178. self.site = SynapseSite(
  179. logger_name="synapse.access.http.fake",
  180. site_tag="test",
  181. config=self.hs.config.server.listeners[0],
  182. resource=self.resource,
  183. server_version_string="1",
  184. )
  185. from tests.rest.client.v1.utils import RestHelper
  186. self.helper = RestHelper(self.hs, self.resource, getattr(self, "user_id", None))
  187. if hasattr(self, "user_id"):
  188. if self.hijack_auth:
  189. async def get_user_by_access_token(token=None, allow_guest=False):
  190. return {
  191. "user": UserID.from_string(self.helper.auth_user_id),
  192. "token_id": 1,
  193. "is_guest": False,
  194. }
  195. async def get_user_by_req(request, allow_guest=False, rights="access"):
  196. return create_requester(
  197. UserID.from_string(self.helper.auth_user_id),
  198. 1,
  199. False,
  200. False,
  201. None,
  202. )
  203. self.hs.get_auth().get_user_by_req = get_user_by_req
  204. self.hs.get_auth().get_user_by_access_token = get_user_by_access_token
  205. self.hs.get_auth().get_access_token_from_request = Mock(
  206. return_value="1234"
  207. )
  208. if self.needs_threadpool:
  209. self.reactor.threadpool = ThreadPool()
  210. self.addCleanup(self.reactor.threadpool.stop)
  211. self.reactor.threadpool.start()
  212. if hasattr(self, "prepare"):
  213. self.prepare(self.reactor, self.clock, self.hs)
  214. def wait_on_thread(self, deferred, timeout=10):
  215. """
  216. Wait until a Deferred is done, where it's waiting on a real thread.
  217. """
  218. start_time = time.time()
  219. while not deferred.called:
  220. if start_time + timeout < time.time():
  221. raise ValueError("Timed out waiting for threadpool")
  222. self.reactor.advance(0.01)
  223. time.sleep(0.01)
  224. def make_homeserver(self, reactor, clock):
  225. """
  226. Make and return a homeserver.
  227. Args:
  228. reactor: A Twisted Reactor, or something that pretends to be one.
  229. clock (synapse.util.Clock): The Clock, associated with the reactor.
  230. Returns:
  231. A homeserver (synapse.server.HomeServer) suitable for testing.
  232. Function to be overridden in subclasses.
  233. """
  234. hs = self.setup_test_homeserver()
  235. return hs
  236. def create_test_json_resource(self):
  237. """
  238. Create a test JsonResource, with the relevant servlets registerd to it
  239. The default implementation calls each function in `servlets` to do the
  240. registration.
  241. Returns:
  242. JsonResource:
  243. """
  244. resource = JsonResource(self.hs)
  245. for servlet in self.servlets:
  246. servlet(self.hs, resource)
  247. return resource
  248. def default_config(self):
  249. """
  250. Get a default HomeServer config dict.
  251. """
  252. config = default_config("test")
  253. # apply any additional config which was specified via the override_config
  254. # decorator.
  255. if self._extra_config is not None:
  256. config.update(self._extra_config)
  257. return config
  258. def prepare(self, reactor, clock, homeserver):
  259. """
  260. Prepare for the test. This involves things like mocking out parts of
  261. the homeserver, or building test data common across the whole test
  262. suite.
  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. homeserver (synapse.server.HomeServer): The HomeServer to test
  267. against.
  268. Function to optionally be overridden in subclasses.
  269. """
  270. def make_request(
  271. self,
  272. method: Union[bytes, str],
  273. path: Union[bytes, str],
  274. content: Union[bytes, dict] = b"",
  275. access_token: Optional[str] = None,
  276. request: Type[T] = SynapseRequest,
  277. shorthand: bool = True,
  278. federation_auth_origin: str = None,
  279. content_is_form: bool = False,
  280. ) -> Tuple[T, FakeChannel]:
  281. """
  282. Create a SynapseRequest at the path using the method and containing the
  283. given content.
  284. Args:
  285. method (bytes/unicode): The HTTP request method ("verb").
  286. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  287. escaped UTF-8 & spaces and such).
  288. content (bytes or dict): The body of the request. JSON-encoded, if
  289. a dict.
  290. shorthand: Whether to try and be helpful and prefix the given URL
  291. with the usual REST API path, if it doesn't contain it.
  292. federation_auth_origin (bytes|None): if set to not-None, we will add a fake
  293. Authorization header pretenting to be the given server name.
  294. content_is_form: Whether the content is URL encoded form data. Adds the
  295. 'Content-Type': 'application/x-www-form-urlencoded' header.
  296. Returns:
  297. Tuple[synapse.http.site.SynapseRequest, channel]
  298. """
  299. if isinstance(content, dict):
  300. content = json.dumps(content).encode("utf8")
  301. return make_request(
  302. self.reactor,
  303. method,
  304. path,
  305. content,
  306. access_token,
  307. request,
  308. shorthand,
  309. federation_auth_origin,
  310. content_is_form,
  311. )
  312. def render(self, request):
  313. """
  314. Render a request against the resources registered by the test class's
  315. servlets.
  316. Args:
  317. request (synapse.http.site.SynapseRequest): The request to render.
  318. """
  319. render(request, self.resource, self.reactor)
  320. def setup_test_homeserver(self, *args, **kwargs):
  321. """
  322. Set up the test homeserver, meant to be called by the overridable
  323. make_homeserver. It automatically passes through the test class's
  324. clock & reactor.
  325. Args:
  326. See tests.utils.setup_test_homeserver.
  327. Returns:
  328. synapse.server.HomeServer
  329. """
  330. kwargs = dict(kwargs)
  331. kwargs.update(self._hs_args)
  332. if "config" not in kwargs:
  333. config = self.default_config()
  334. else:
  335. config = kwargs["config"]
  336. # Parse the config from a config dict into a HomeServerConfig
  337. config_obj = HomeServerConfig()
  338. config_obj.parse_config_dict(config, "", "")
  339. kwargs["config"] = config_obj
  340. async def run_bg_updates():
  341. with LoggingContext("run_bg_updates", request="run_bg_updates-1"):
  342. while not await stor.db_pool.updates.has_completed_background_updates():
  343. await stor.db_pool.updates.do_next_background_update(1)
  344. hs = setup_test_homeserver(self.addCleanup, *args, **kwargs)
  345. stor = hs.get_datastore()
  346. # Run the database background updates, when running against "master".
  347. if hs.__class__.__name__ == "TestHomeServer":
  348. self.get_success(run_bg_updates())
  349. return hs
  350. def pump(self, by=0.0):
  351. """
  352. Pump the reactor enough that Deferreds will fire.
  353. """
  354. self.reactor.pump([by] * 100)
  355. def get_success(self, d, by=0.0):
  356. if inspect.isawaitable(d):
  357. d = ensureDeferred(d)
  358. if not isinstance(d, Deferred):
  359. return d
  360. self.pump(by=by)
  361. return self.successResultOf(d)
  362. def get_failure(self, d, exc):
  363. """
  364. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  365. """
  366. if inspect.isawaitable(d):
  367. d = ensureDeferred(d)
  368. if not isinstance(d, Deferred):
  369. return d
  370. self.pump()
  371. return self.failureResultOf(d, exc)
  372. def register_user(self, username, password, admin=False):
  373. """
  374. Register a user. Requires the Admin API be registered.
  375. Args:
  376. username (bytes/unicode): The user part of the new user.
  377. password (bytes/unicode): The password of the new user.
  378. admin (bool): Whether the user should be created as an admin
  379. or not.
  380. Returns:
  381. The MXID of the new user (unicode).
  382. """
  383. self.hs.config.registration_shared_secret = "shared"
  384. # Create the user
  385. request, channel = self.make_request("GET", "/_matrix/client/r0/admin/register")
  386. self.render(request)
  387. self.assertEqual(channel.code, 200, msg=channel.result)
  388. nonce = channel.json_body["nonce"]
  389. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  390. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  391. if admin:
  392. nonce_str += b"\x00admin"
  393. else:
  394. nonce_str += b"\x00notadmin"
  395. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  396. want_mac = want_mac.hexdigest()
  397. body = json.dumps(
  398. {
  399. "nonce": nonce,
  400. "username": username,
  401. "password": password,
  402. "admin": admin,
  403. "mac": want_mac,
  404. "inhibit_login": True,
  405. }
  406. )
  407. request, channel = self.make_request(
  408. "POST", "/_matrix/client/r0/admin/register", body.encode("utf8")
  409. )
  410. self.render(request)
  411. self.assertEqual(channel.code, 200, channel.json_body)
  412. user_id = channel.json_body["user_id"]
  413. return user_id
  414. def login(self, username, password, device_id=None):
  415. """
  416. Log in a user, and get an access token. Requires the Login API be
  417. registered.
  418. """
  419. body = {"type": "m.login.password", "user": username, "password": password}
  420. if device_id:
  421. body["device_id"] = device_id
  422. request, channel = self.make_request(
  423. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  424. )
  425. self.render(request)
  426. self.assertEqual(channel.code, 200, channel.result)
  427. access_token = channel.json_body["access_token"]
  428. return access_token
  429. def create_and_send_event(
  430. self, room_id, user, soft_failed=False, prev_event_ids=None
  431. ):
  432. """
  433. Create and send an event.
  434. Args:
  435. soft_failed (bool): Whether to create a soft failed event or not
  436. prev_event_ids (list[str]|None): Explicitly set the prev events,
  437. or if None just use the default
  438. Returns:
  439. str: The new event's ID.
  440. """
  441. event_creator = self.hs.get_event_creation_handler()
  442. secrets = self.hs.get_secrets()
  443. requester = Requester(user, None, False, False, None, None)
  444. event, context = self.get_success(
  445. event_creator.create_event(
  446. requester,
  447. {
  448. "type": EventTypes.Message,
  449. "room_id": room_id,
  450. "sender": user.to_string(),
  451. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  452. },
  453. prev_event_ids=prev_event_ids,
  454. )
  455. )
  456. if soft_failed:
  457. event.internal_metadata.soft_failed = True
  458. self.get_success(event_creator.send_nonmember_event(requester, event, context))
  459. return event.event_id
  460. def add_extremity(self, room_id, event_id):
  461. """
  462. Add the given event as an extremity to the room.
  463. """
  464. self.get_success(
  465. self.hs.get_datastore().db_pool.simple_insert(
  466. table="event_forward_extremities",
  467. values={"room_id": room_id, "event_id": event_id},
  468. desc="test_add_extremity",
  469. )
  470. )
  471. self.hs.get_datastore().get_latest_event_ids_in_room.invalidate((room_id,))
  472. def attempt_wrong_password_login(self, username, password):
  473. """Attempts to login as the user with the given password, asserting
  474. that the attempt *fails*.
  475. """
  476. body = {"type": "m.login.password", "user": username, "password": password}
  477. request, channel = self.make_request(
  478. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  479. )
  480. self.render(request)
  481. self.assertEqual(channel.code, 403, channel.result)
  482. def inject_room_member(self, room: str, user: str, membership: Membership) -> None:
  483. """
  484. Inject a membership event into a room.
  485. Deprecated: use event_injection.inject_room_member directly
  486. Args:
  487. room: Room ID to inject the event into.
  488. user: MXID of the user to inject the membership for.
  489. membership: The membership type.
  490. """
  491. self.get_success(
  492. event_injection.inject_member_event(self.hs, room, user, membership)
  493. )
  494. class FederatingHomeserverTestCase(HomeserverTestCase):
  495. """
  496. A federating homeserver that authenticates incoming requests as `other.example.com`.
  497. """
  498. def prepare(self, reactor, clock, homeserver):
  499. class Authenticator:
  500. def authenticate_request(self, request, content):
  501. return succeed("other.example.com")
  502. ratelimiter = FederationRateLimiter(
  503. clock,
  504. FederationRateLimitConfig(
  505. window_size=1,
  506. sleep_limit=1,
  507. sleep_msec=1,
  508. reject_limit=1000,
  509. concurrent_requests=1000,
  510. ),
  511. )
  512. federation_server.register_servlets(
  513. homeserver, self.resource, Authenticator(), ratelimiter
  514. )
  515. return super().prepare(reactor, clock, homeserver)
  516. def override_config(extra_config):
  517. """A decorator which can be applied to test functions to give additional HS config
  518. For use
  519. For example:
  520. class MyTestCase(HomeserverTestCase):
  521. @override_config({"enable_registration": False, ...})
  522. def test_foo(self):
  523. ...
  524. Args:
  525. extra_config(dict): Additional config settings to be merged into the default
  526. config dict before instantiating the test homeserver.
  527. """
  528. def decorator(func):
  529. func._extra_config = extra_config
  530. return func
  531. return decorator