1
0

utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import atexit
  16. import hashlib
  17. import os
  18. import time
  19. import uuid
  20. import warnings
  21. from inspect import getcallargs
  22. from mock import Mock, patch
  23. from six.moves.urllib import parse as urlparse
  24. from twisted.internet import defer, reactor
  25. from synapse.api.constants import EventTypes, RoomVersions
  26. from synapse.api.errors import CodeMessageException, cs_error
  27. from synapse.config.server import ServerConfig
  28. from synapse.federation.transport import server
  29. from synapse.http.server import HttpServer
  30. from synapse.server import HomeServer
  31. from synapse.storage import DataStore
  32. from synapse.storage.engines import PostgresEngine, create_engine
  33. from synapse.storage.prepare_database import (
  34. _get_or_create_schema_state,
  35. _setup_new_database,
  36. prepare_database,
  37. )
  38. from synapse.util.logcontext import LoggingContext
  39. from synapse.util.ratelimitutils import FederationRateLimiter
  40. # set this to True to run the tests against postgres instead of sqlite.
  41. USE_POSTGRES_FOR_TESTS = os.environ.get("SYNAPSE_POSTGRES", False)
  42. LEAVE_DB = os.environ.get("SYNAPSE_LEAVE_DB", False)
  43. POSTGRES_USER = os.environ.get("SYNAPSE_POSTGRES_USER", "postgres")
  44. POSTGRES_BASE_DB = "_synapse_unit_tests_base_%s" % (os.getpid(),)
  45. def setupdb():
  46. # If we're using PostgreSQL, set up the db once
  47. if USE_POSTGRES_FOR_TESTS:
  48. pgconfig = {
  49. "name": "psycopg2",
  50. "args": {
  51. "database": POSTGRES_BASE_DB,
  52. "user": POSTGRES_USER,
  53. "cp_min": 1,
  54. "cp_max": 5,
  55. },
  56. }
  57. config = Mock()
  58. config.password_providers = []
  59. config.database_config = pgconfig
  60. db_engine = create_engine(pgconfig)
  61. db_conn = db_engine.module.connect(user=POSTGRES_USER)
  62. db_conn.autocommit = True
  63. cur = db_conn.cursor()
  64. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  65. cur.execute("CREATE DATABASE %s;" % (POSTGRES_BASE_DB,))
  66. cur.close()
  67. db_conn.close()
  68. # Set up in the db
  69. db_conn = db_engine.module.connect(
  70. database=POSTGRES_BASE_DB, user=POSTGRES_USER
  71. )
  72. cur = db_conn.cursor()
  73. _get_or_create_schema_state(cur, db_engine)
  74. _setup_new_database(cur, db_engine)
  75. db_conn.commit()
  76. cur.close()
  77. db_conn.close()
  78. def _cleanup():
  79. db_conn = db_engine.module.connect(user=POSTGRES_USER)
  80. db_conn.autocommit = True
  81. cur = db_conn.cursor()
  82. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  83. cur.close()
  84. db_conn.close()
  85. atexit.register(_cleanup)
  86. def default_config(name):
  87. """
  88. Create a reasonable test config.
  89. """
  90. config = Mock()
  91. config.signing_key = [MockKey()]
  92. config.event_cache_size = 1
  93. config.enable_registration = True
  94. config.macaroon_secret_key = "not even a little secret"
  95. config.expire_access_token = False
  96. config.server_name = name
  97. config.trusted_third_party_id_servers = []
  98. config.room_invite_state_types = []
  99. config.password_providers = []
  100. config.worker_replication_url = ""
  101. config.worker_app = None
  102. config.email_enable_notifs = False
  103. config.block_non_admin_invites = False
  104. config.federation_domain_whitelist = None
  105. config.federation_rc_reject_limit = 10
  106. config.federation_rc_sleep_limit = 10
  107. config.federation_rc_sleep_delay = 100
  108. config.federation_rc_concurrent = 10
  109. config.filter_timeline_limit = 5000
  110. config.user_directory_search_all_users = False
  111. config.user_consent_server_notice_content = None
  112. config.block_events_without_consent_error = None
  113. config.user_consent_at_registration = False
  114. config.user_consent_policy_name = "Privacy Policy"
  115. config.media_storage_providers = []
  116. config.autocreate_auto_join_rooms = True
  117. config.auto_join_rooms = []
  118. config.limit_usage_by_mau = False
  119. config.hs_disabled = False
  120. config.hs_disabled_message = ""
  121. config.hs_disabled_limit_type = ""
  122. config.max_mau_value = 50
  123. config.mau_trial_days = 0
  124. config.mau_stats_only = False
  125. config.mau_limits_reserved_threepids = []
  126. config.admin_contact = None
  127. config.rc_messages_per_second = 10000
  128. config.rc_message_burst_count = 10000
  129. config.saml2_enabled = False
  130. config.public_baseurl = None
  131. config.default_identity_server = None
  132. config.use_frozen_dicts = False
  133. # we need a sane default_room_version, otherwise attempts to create rooms will
  134. # fail.
  135. config.default_room_version = "1"
  136. # disable user directory updates, because they get done in the
  137. # background, which upsets the test runner.
  138. config.update_user_directory = False
  139. def is_threepid_reserved(threepid):
  140. return ServerConfig.is_threepid_reserved(
  141. config.mau_limits_reserved_threepids, threepid
  142. )
  143. config.is_threepid_reserved.side_effect = is_threepid_reserved
  144. return config
  145. class TestHomeServer(HomeServer):
  146. DATASTORE_CLASS = DataStore
  147. @defer.inlineCallbacks
  148. def setup_test_homeserver(
  149. cleanup_func,
  150. name="test",
  151. datastore=None,
  152. config=None,
  153. reactor=None,
  154. homeserverToUse=TestHomeServer,
  155. **kargs
  156. ):
  157. """
  158. Setup a homeserver suitable for running tests against. Keyword arguments
  159. are passed to the Homeserver constructor.
  160. If no datastore is supplied, one is created and given to the homeserver.
  161. Args:
  162. cleanup_func : The function used to register a cleanup routine for
  163. after the test.
  164. """
  165. if reactor is None:
  166. from twisted.internet import reactor
  167. if config is None:
  168. config = default_config(name)
  169. config.ldap_enabled = False
  170. if "clock" not in kargs:
  171. kargs["clock"] = MockClock()
  172. if USE_POSTGRES_FOR_TESTS:
  173. test_db = "synapse_test_%s" % uuid.uuid4().hex
  174. config.database_config = {
  175. "name": "psycopg2",
  176. "args": {"database": test_db, "cp_min": 1, "cp_max": 5},
  177. }
  178. else:
  179. config.database_config = {
  180. "name": "sqlite3",
  181. "args": {"database": ":memory:", "cp_min": 1, "cp_max": 1},
  182. }
  183. db_engine = create_engine(config.database_config)
  184. # Create the database before we actually try and connect to it, based off
  185. # the template database we generate in setupdb()
  186. if datastore is None and isinstance(db_engine, PostgresEngine):
  187. db_conn = db_engine.module.connect(
  188. database=POSTGRES_BASE_DB, user=POSTGRES_USER
  189. )
  190. db_conn.autocommit = True
  191. cur = db_conn.cursor()
  192. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  193. cur.execute(
  194. "CREATE DATABASE %s WITH TEMPLATE %s;" % (test_db, POSTGRES_BASE_DB)
  195. )
  196. cur.close()
  197. db_conn.close()
  198. # we need to configure the connection pool to run the on_new_connection
  199. # function, so that we can test code that uses custom sqlite functions
  200. # (like rank).
  201. config.database_config["args"]["cp_openfun"] = db_engine.on_new_connection
  202. if datastore is None:
  203. hs = homeserverToUse(
  204. name,
  205. config=config,
  206. db_config=config.database_config,
  207. version_string="Synapse/tests",
  208. database_engine=db_engine,
  209. room_list_handler=object(),
  210. tls_server_context_factory=Mock(),
  211. tls_client_options_factory=Mock(),
  212. reactor=reactor,
  213. **kargs
  214. )
  215. # Prepare the DB on SQLite -- PostgreSQL is a copy of an already up to
  216. # date db
  217. if not isinstance(db_engine, PostgresEngine):
  218. db_conn = hs.get_db_conn()
  219. yield prepare_database(db_conn, db_engine, config)
  220. db_conn.commit()
  221. db_conn.close()
  222. else:
  223. # We need to do cleanup on PostgreSQL
  224. def cleanup():
  225. import psycopg2
  226. # Close all the db pools
  227. hs.get_db_pool().close()
  228. dropped = False
  229. # Drop the test database
  230. db_conn = db_engine.module.connect(
  231. database=POSTGRES_BASE_DB, user=POSTGRES_USER
  232. )
  233. db_conn.autocommit = True
  234. cur = db_conn.cursor()
  235. # Try a few times to drop the DB. Some things may hold on to the
  236. # database for a few more seconds due to flakiness, preventing
  237. # us from dropping it when the test is over. If we can't drop
  238. # it, warn and move on.
  239. for x in range(5):
  240. try:
  241. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  242. db_conn.commit()
  243. dropped = True
  244. except psycopg2.OperationalError as e:
  245. warnings.warn(
  246. "Couldn't drop old db: " + str(e), category=UserWarning
  247. )
  248. time.sleep(0.5)
  249. cur.close()
  250. db_conn.close()
  251. if not dropped:
  252. warnings.warn("Failed to drop old DB.", category=UserWarning)
  253. if not LEAVE_DB:
  254. # Register the cleanup hook
  255. cleanup_func(cleanup)
  256. hs.setup()
  257. else:
  258. hs = homeserverToUse(
  259. name,
  260. db_pool=None,
  261. datastore=datastore,
  262. config=config,
  263. version_string="Synapse/tests",
  264. database_engine=db_engine,
  265. room_list_handler=object(),
  266. tls_server_context_factory=Mock(),
  267. tls_client_options_factory=Mock(),
  268. reactor=reactor,
  269. **kargs
  270. )
  271. # bcrypt is far too slow to be doing in unit tests
  272. # Need to let the HS build an auth handler and then mess with it
  273. # because AuthHandler's constructor requires the HS, so we can't make one
  274. # beforehand and pass it in to the HS's constructor (chicken / egg)
  275. hs.get_auth_handler().hash = lambda p: hashlib.md5(p.encode('utf8')).hexdigest()
  276. hs.get_auth_handler().validate_hash = (
  277. lambda p, h: hashlib.md5(p.encode('utf8')).hexdigest() == h
  278. )
  279. fed = kargs.get("resource_for_federation", None)
  280. if fed:
  281. server.register_servlets(
  282. hs,
  283. resource=fed,
  284. authenticator=server.Authenticator(hs),
  285. ratelimiter=FederationRateLimiter(
  286. hs.get_clock(),
  287. window_size=hs.config.federation_rc_window_size,
  288. sleep_limit=hs.config.federation_rc_sleep_limit,
  289. sleep_msec=hs.config.federation_rc_sleep_delay,
  290. reject_limit=hs.config.federation_rc_reject_limit,
  291. concurrent_requests=hs.config.federation_rc_concurrent,
  292. ),
  293. )
  294. defer.returnValue(hs)
  295. def get_mock_call_args(pattern_func, mock_func):
  296. """ Return the arguments the mock function was called with interpreted
  297. by the pattern functions argument list.
  298. """
  299. invoked_args, invoked_kargs = mock_func.call_args
  300. return getcallargs(pattern_func, *invoked_args, **invoked_kargs)
  301. def mock_getRawHeaders(headers=None):
  302. headers = headers if headers is not None else {}
  303. def getRawHeaders(name, default=None):
  304. return headers.get(name, default)
  305. return getRawHeaders
  306. # This is a mock /resource/ not an entire server
  307. class MockHttpResource(HttpServer):
  308. def __init__(self, prefix=""):
  309. self.callbacks = [] # 3-tuple of method/pattern/function
  310. self.prefix = prefix
  311. def trigger_get(self, path):
  312. return self.trigger(b"GET", path, None)
  313. @patch('twisted.web.http.Request')
  314. @defer.inlineCallbacks
  315. def trigger(
  316. self, http_method, path, content, mock_request, federation_auth_origin=None
  317. ):
  318. """ Fire an HTTP event.
  319. Args:
  320. http_method : The HTTP method
  321. path : The HTTP path
  322. content : The HTTP body
  323. mock_request : Mocked request to pass to the event so it can get
  324. content.
  325. federation_auth_origin (bytes|None): domain to authenticate as, for federation
  326. Returns:
  327. A tuple of (code, response)
  328. Raises:
  329. KeyError If no event is found which will handle the path.
  330. """
  331. path = self.prefix + path
  332. # annoyingly we return a twisted http request which has chained calls
  333. # to get at the http content, hence mock it here.
  334. mock_content = Mock()
  335. config = {'read.return_value': content}
  336. mock_content.configure_mock(**config)
  337. mock_request.content = mock_content
  338. mock_request.method = http_method.encode('ascii')
  339. mock_request.uri = path.encode('ascii')
  340. mock_request.getClientIP.return_value = "-"
  341. headers = {}
  342. if federation_auth_origin is not None:
  343. headers[b"Authorization"] = [
  344. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,)
  345. ]
  346. mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers)
  347. # return the right path if the event requires it
  348. mock_request.path = path
  349. # add in query params to the right place
  350. try:
  351. mock_request.args = urlparse.parse_qs(path.split('?')[1])
  352. mock_request.path = path.split('?')[0]
  353. path = mock_request.path
  354. except Exception:
  355. pass
  356. if isinstance(path, bytes):
  357. path = path.decode('utf8')
  358. for (method, pattern, func) in self.callbacks:
  359. if http_method != method:
  360. continue
  361. matcher = pattern.match(path)
  362. if matcher:
  363. try:
  364. args = [urlparse.unquote(u) for u in matcher.groups()]
  365. (code, response) = yield func(mock_request, *args)
  366. defer.returnValue((code, response))
  367. except CodeMessageException as e:
  368. defer.returnValue((e.code, cs_error(e.msg, code=e.errcode)))
  369. raise KeyError("No event can handle %s" % path)
  370. def register_paths(self, method, path_patterns, callback):
  371. for path_pattern in path_patterns:
  372. self.callbacks.append((method, path_pattern, callback))
  373. class MockKey(object):
  374. alg = "mock_alg"
  375. version = "mock_version"
  376. signature = b"\x9a\x87$"
  377. @property
  378. def verify_key(self):
  379. return self
  380. def sign(self, message):
  381. return self
  382. def verify(self, message, sig):
  383. assert sig == b"\x9a\x87$"
  384. class MockClock(object):
  385. now = 1000
  386. def __init__(self):
  387. # list of lists of [absolute_time, callback, expired] in no particular
  388. # order
  389. self.timers = []
  390. self.loopers = []
  391. def time(self):
  392. return self.now
  393. def time_msec(self):
  394. return self.time() * 1000
  395. def call_later(self, delay, callback, *args, **kwargs):
  396. current_context = LoggingContext.current_context()
  397. def wrapped_callback():
  398. LoggingContext.thread_local.current_context = current_context
  399. callback(*args, **kwargs)
  400. t = [self.now + delay, wrapped_callback, False]
  401. self.timers.append(t)
  402. return t
  403. def looping_call(self, function, interval):
  404. self.loopers.append([function, interval / 1000., self.now])
  405. def cancel_call_later(self, timer, ignore_errs=False):
  406. if timer[2]:
  407. if not ignore_errs:
  408. raise Exception("Cannot cancel an expired timer")
  409. timer[2] = True
  410. self.timers = [t for t in self.timers if t != timer]
  411. # For unit testing
  412. def advance_time(self, secs):
  413. self.now += secs
  414. timers = self.timers
  415. self.timers = []
  416. for t in timers:
  417. time, callback, expired = t
  418. if expired:
  419. raise Exception("Timer already expired")
  420. if self.now >= time:
  421. t[2] = True
  422. callback()
  423. else:
  424. self.timers.append(t)
  425. for looped in self.loopers:
  426. func, interval, last = looped
  427. if last + interval < self.now:
  428. func()
  429. looped[2] = self.now
  430. def advance_time_msec(self, ms):
  431. self.advance_time(ms / 1000.)
  432. def time_bound_deferred(self, d, *args, **kwargs):
  433. # We don't bother timing things out for now.
  434. return d
  435. def _format_call(args, kwargs):
  436. return ", ".join(
  437. ["%r" % (a) for a in args] + ["%s=%r" % (k, v) for k, v in kwargs.items()]
  438. )
  439. class DeferredMockCallable(object):
  440. """A callable instance that stores a set of pending call expectations and
  441. return values for them. It allows a unit test to assert that the given set
  442. of function calls are eventually made, by awaiting on them to be called.
  443. """
  444. def __init__(self):
  445. self.expectations = []
  446. self.calls = []
  447. def __call__(self, *args, **kwargs):
  448. self.calls.append((args, kwargs))
  449. if not self.expectations:
  450. raise ValueError(
  451. "%r has no pending calls to handle call(%s)"
  452. % (self, _format_call(args, kwargs))
  453. )
  454. for (call, result, d) in self.expectations:
  455. if args == call[1] and kwargs == call[2]:
  456. d.callback(None)
  457. return result
  458. failure = AssertionError(
  459. "Was not expecting call(%s)" % (_format_call(args, kwargs))
  460. )
  461. for _, _, d in self.expectations:
  462. try:
  463. d.errback(failure)
  464. except Exception:
  465. pass
  466. raise failure
  467. def expect_call_and_return(self, call, result):
  468. self.expectations.append((call, result, defer.Deferred()))
  469. @defer.inlineCallbacks
  470. def await_calls(self, timeout=1000):
  471. deferred = defer.DeferredList(
  472. [d for _, _, d in self.expectations], fireOnOneErrback=True
  473. )
  474. timer = reactor.callLater(
  475. timeout / 1000,
  476. deferred.errback,
  477. AssertionError(
  478. "%d pending calls left: %s"
  479. % (
  480. len([e for e in self.expectations if not e[2].called]),
  481. [e for e in self.expectations if not e[2].called],
  482. )
  483. ),
  484. )
  485. yield deferred
  486. timer.cancel()
  487. self.calls = []
  488. def assert_had_no_calls(self):
  489. if self.calls:
  490. calls = self.calls
  491. self.calls = []
  492. raise AssertionError(
  493. "Expected not to received any calls, got:\n"
  494. + "\n".join(["call(%s)" % _format_call(c[0], c[1]) for c in calls])
  495. )
  496. @defer.inlineCallbacks
  497. def create_room(hs, room_id, creator_id):
  498. """Creates and persist a creation event for the given room
  499. Args:
  500. hs
  501. room_id (str)
  502. creator_id (str)
  503. """
  504. store = hs.get_datastore()
  505. event_builder_factory = hs.get_event_builder_factory()
  506. event_creation_handler = hs.get_event_creation_handler()
  507. builder = event_builder_factory.new(
  508. RoomVersions.V1,
  509. {
  510. "type": EventTypes.Create,
  511. "state_key": "",
  512. "sender": creator_id,
  513. "room_id": room_id,
  514. "content": {},
  515. }
  516. )
  517. event, context = yield event_creation_handler.create_new_client_event(builder)
  518. yield store.persist_event(event, context)