utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. from synapse.http.server import HttpServer
  16. from synapse.api.errors import cs_error, CodeMessageException, StoreError
  17. from synapse.api.constants import EventTypes
  18. from synapse.storage.prepare_database import prepare_database
  19. from synapse.storage.engines import create_engine
  20. from synapse.server import HomeServer
  21. from synapse.federation.transport import server
  22. from synapse.util.ratelimitutils import FederationRateLimiter
  23. from synapse.util.logcontext import LoggingContext
  24. from twisted.internet import defer, reactor
  25. from twisted.enterprise.adbapi import ConnectionPool
  26. from collections import namedtuple
  27. from mock import patch, Mock
  28. import hashlib
  29. import urllib
  30. import urlparse
  31. from inspect import getcallargs
  32. @defer.inlineCallbacks
  33. def setup_test_homeserver(name="test", datastore=None, config=None, **kargs):
  34. """Setup a homeserver suitable for running tests against. Keyword arguments
  35. are passed to the Homeserver constructor. If no datastore is supplied a
  36. datastore backed by an in-memory sqlite db will be given to the HS.
  37. """
  38. if config is None:
  39. config = Mock()
  40. config.signing_key = [MockKey()]
  41. config.event_cache_size = 1
  42. config.enable_registration = True
  43. config.macaroon_secret_key = "not even a little secret"
  44. config.expire_access_token = False
  45. config.server_name = name
  46. config.trusted_third_party_id_servers = []
  47. config.room_invite_state_types = []
  48. config.password_providers = []
  49. config.worker_replication_url = ""
  50. config.worker_app = None
  51. config.email_enable_notifs = False
  52. config.use_frozen_dicts = True
  53. config.database_config = {"name": "sqlite3"}
  54. config.ldap_enabled = False
  55. if "clock" not in kargs:
  56. kargs["clock"] = MockClock()
  57. if datastore is None:
  58. db_pool = SQLiteMemoryDbPool()
  59. yield db_pool.prepare()
  60. hs = HomeServer(
  61. name, db_pool=db_pool, config=config,
  62. version_string="Synapse/tests",
  63. database_engine=create_engine(config.database_config),
  64. get_db_conn=db_pool.get_db_conn,
  65. room_list_handler=object(),
  66. tls_server_context_factory=Mock(),
  67. **kargs
  68. )
  69. hs.setup()
  70. else:
  71. hs = HomeServer(
  72. name, db_pool=None, datastore=datastore, config=config,
  73. version_string="Synapse/tests",
  74. database_engine=create_engine(config.database_config),
  75. room_list_handler=object(),
  76. tls_server_context_factory=Mock(),
  77. **kargs
  78. )
  79. # bcrypt is far too slow to be doing in unit tests
  80. # Need to let the HS build an auth handler and then mess with it
  81. # because AuthHandler's constructor requires the HS, so we can't make one
  82. # beforehand and pass it in to the HS's constructor (chicken / egg)
  83. hs.get_auth_handler().hash = lambda p: hashlib.md5(p).hexdigest()
  84. hs.get_auth_handler().validate_hash = lambda p, h: hashlib.md5(p).hexdigest() == h
  85. fed = kargs.get("resource_for_federation", None)
  86. if fed:
  87. server.register_servlets(
  88. hs,
  89. resource=fed,
  90. authenticator=server.Authenticator(hs),
  91. ratelimiter=FederationRateLimiter(
  92. hs.get_clock(),
  93. window_size=hs.config.federation_rc_window_size,
  94. sleep_limit=hs.config.federation_rc_sleep_limit,
  95. sleep_msec=hs.config.federation_rc_sleep_delay,
  96. reject_limit=hs.config.federation_rc_reject_limit,
  97. concurrent_requests=hs.config.federation_rc_concurrent
  98. ),
  99. )
  100. defer.returnValue(hs)
  101. def get_mock_call_args(pattern_func, mock_func):
  102. """ Return the arguments the mock function was called with interpreted
  103. by the pattern functions argument list.
  104. """
  105. invoked_args, invoked_kargs = mock_func.call_args
  106. return getcallargs(pattern_func, *invoked_args, **invoked_kargs)
  107. def mock_getRawHeaders(headers=None):
  108. headers = headers if headers is not None else {}
  109. def getRawHeaders(name, default=None):
  110. return headers.get(name, default)
  111. return getRawHeaders
  112. # This is a mock /resource/ not an entire server
  113. class MockHttpResource(HttpServer):
  114. def __init__(self, prefix=""):
  115. self.callbacks = [] # 3-tuple of method/pattern/function
  116. self.prefix = prefix
  117. def trigger_get(self, path):
  118. return self.trigger("GET", path, None)
  119. @patch('twisted.web.http.Request')
  120. @defer.inlineCallbacks
  121. def trigger(self, http_method, path, content, mock_request, federation_auth=False):
  122. """ Fire an HTTP event.
  123. Args:
  124. http_method : The HTTP method
  125. path : The HTTP path
  126. content : The HTTP body
  127. mock_request : Mocked request to pass to the event so it can get
  128. content.
  129. Returns:
  130. A tuple of (code, response)
  131. Raises:
  132. KeyError If no event is found which will handle the path.
  133. """
  134. path = self.prefix + path
  135. # annoyingly we return a twisted http request which has chained calls
  136. # to get at the http content, hence mock it here.
  137. mock_content = Mock()
  138. config = {'read.return_value': content}
  139. mock_content.configure_mock(**config)
  140. mock_request.content = mock_content
  141. mock_request.method = http_method
  142. mock_request.uri = path
  143. mock_request.getClientIP.return_value = "-"
  144. headers = {}
  145. if federation_auth:
  146. headers["Authorization"] = ["X-Matrix origin=test,key=,sig="]
  147. mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers)
  148. # return the right path if the event requires it
  149. mock_request.path = path
  150. # add in query params to the right place
  151. try:
  152. mock_request.args = urlparse.parse_qs(path.split('?')[1])
  153. mock_request.path = path.split('?')[0]
  154. path = mock_request.path
  155. except:
  156. pass
  157. for (method, pattern, func) in self.callbacks:
  158. if http_method != method:
  159. continue
  160. matcher = pattern.match(path)
  161. if matcher:
  162. try:
  163. args = [
  164. urllib.unquote(u).decode("UTF-8")
  165. for u in matcher.groups()
  166. ]
  167. (code, response) = yield func(
  168. mock_request,
  169. *args
  170. )
  171. defer.returnValue((code, response))
  172. except CodeMessageException as e:
  173. defer.returnValue((e.code, cs_error(e.msg, code=e.errcode)))
  174. raise KeyError("No event can handle %s" % path)
  175. def register_paths(self, method, path_patterns, callback):
  176. for path_pattern in path_patterns:
  177. self.callbacks.append((method, path_pattern, callback))
  178. class MockKey(object):
  179. alg = "mock_alg"
  180. version = "mock_version"
  181. signature = b"\x9a\x87$"
  182. @property
  183. def verify_key(self):
  184. return self
  185. def sign(self, message):
  186. return self
  187. def verify(self, message, sig):
  188. assert sig == b"\x9a\x87$"
  189. class MockClock(object):
  190. now = 1000
  191. def __init__(self):
  192. # list of lists of [absolute_time, callback, expired] in no particular
  193. # order
  194. self.timers = []
  195. self.loopers = []
  196. def time(self):
  197. return self.now
  198. def time_msec(self):
  199. return self.time() * 1000
  200. def call_later(self, delay, callback, *args, **kwargs):
  201. current_context = LoggingContext.current_context()
  202. def wrapped_callback():
  203. LoggingContext.thread_local.current_context = current_context
  204. callback(*args, **kwargs)
  205. t = [self.now + delay, wrapped_callback, False]
  206. self.timers.append(t)
  207. return t
  208. def looping_call(self, function, interval):
  209. self.loopers.append([function, interval / 1000., self.now])
  210. def cancel_call_later(self, timer, ignore_errs=False):
  211. if timer[2]:
  212. if not ignore_errs:
  213. raise Exception("Cannot cancel an expired timer")
  214. timer[2] = True
  215. self.timers = [t for t in self.timers if t != timer]
  216. # For unit testing
  217. def advance_time(self, secs):
  218. self.now += secs
  219. timers = self.timers
  220. self.timers = []
  221. for t in timers:
  222. time, callback, expired = t
  223. if expired:
  224. raise Exception("Timer already expired")
  225. if self.now >= time:
  226. t[2] = True
  227. callback()
  228. else:
  229. self.timers.append(t)
  230. for looped in self.loopers:
  231. func, interval, last = looped
  232. if last + interval < self.now:
  233. func()
  234. looped[2] = self.now
  235. def advance_time_msec(self, ms):
  236. self.advance_time(ms / 1000.)
  237. def time_bound_deferred(self, d, *args, **kwargs):
  238. # We don't bother timing things out for now.
  239. return d
  240. class SQLiteMemoryDbPool(ConnectionPool, object):
  241. def __init__(self):
  242. super(SQLiteMemoryDbPool, self).__init__(
  243. "sqlite3", ":memory:",
  244. cp_min=1,
  245. cp_max=1,
  246. )
  247. self.config = Mock()
  248. self.config.database_config = {"name": "sqlite3"}
  249. def prepare(self):
  250. engine = self.create_engine()
  251. return self.runWithConnection(
  252. lambda conn: prepare_database(conn, engine, self.config)
  253. )
  254. def get_db_conn(self):
  255. conn = self.connect()
  256. engine = self.create_engine()
  257. prepare_database(conn, engine, self.config)
  258. return conn
  259. def create_engine(self):
  260. return create_engine(self.config.database_config)
  261. class MemoryDataStore(object):
  262. Room = namedtuple(
  263. "Room",
  264. ["room_id", "is_public", "creator"]
  265. )
  266. def __init__(self):
  267. self.tokens_to_users = {}
  268. self.paths_to_content = {}
  269. self.members = {}
  270. self.rooms = {}
  271. self.current_state = {}
  272. self.events = []
  273. class Snapshot(namedtuple("Snapshot", "room_id user_id membership_state")):
  274. def fill_out_prev_events(self, event):
  275. pass
  276. def snapshot_room(self, room_id, user_id, state_type=None, state_key=None):
  277. return self.Snapshot(
  278. room_id, user_id, self.get_room_member(user_id, room_id)
  279. )
  280. def register(self, user_id, token, password_hash):
  281. if user_id in self.tokens_to_users.values():
  282. raise StoreError(400, "User in use.")
  283. self.tokens_to_users[token] = user_id
  284. def get_user_by_access_token(self, token):
  285. try:
  286. return {
  287. "name": self.tokens_to_users[token],
  288. }
  289. except:
  290. raise StoreError(400, "User does not exist.")
  291. def get_room(self, room_id):
  292. try:
  293. return self.rooms[room_id]
  294. except:
  295. return None
  296. def store_room(self, room_id, room_creator_user_id, is_public):
  297. if room_id in self.rooms:
  298. raise StoreError(409, "Conflicting room!")
  299. room = MemoryDataStore.Room(
  300. room_id=room_id,
  301. is_public=is_public,
  302. creator=room_creator_user_id
  303. )
  304. self.rooms[room_id] = room
  305. def get_room_member(self, user_id, room_id):
  306. return self.members.get(room_id, {}).get(user_id)
  307. def get_room_members(self, room_id, membership=None):
  308. if membership:
  309. return [
  310. v for k, v in self.members.get(room_id, {}).items()
  311. if v.membership == membership
  312. ]
  313. else:
  314. return self.members.get(room_id, {}).values()
  315. def get_rooms_for_user_where_membership_is(self, user_id, membership_list):
  316. return [
  317. m[user_id] for m in self.members.values()
  318. if user_id in m and m[user_id].membership in membership_list
  319. ]
  320. def get_room_events_stream(self, user_id=None, from_key=None, to_key=None,
  321. limit=0, with_feedback=False):
  322. return ([], from_key) # TODO
  323. def get_joined_hosts_for_room(self, room_id):
  324. return defer.succeed([])
  325. def persist_event(self, event):
  326. if event.type == EventTypes.Member:
  327. room_id = event.room_id
  328. user = event.state_key
  329. self.members.setdefault(room_id, {})[user] = event
  330. if hasattr(event, "state_key"):
  331. key = (event.room_id, event.type, event.state_key)
  332. self.current_state[key] = event
  333. self.events.append(event)
  334. def get_current_state(self, room_id, event_type=None, state_key=""):
  335. if event_type:
  336. key = (room_id, event_type, state_key)
  337. if self.current_state.get(key):
  338. return [self.current_state.get(key)]
  339. return None
  340. else:
  341. return [
  342. e for e in self.current_state
  343. if e[0] == room_id
  344. ]
  345. def set_presence_state(self, user_localpart, state):
  346. return defer.succeed({"state": 0})
  347. def get_presence_list(self, user_localpart, accepted):
  348. return []
  349. def get_room_events_max_id(self):
  350. return "s0" # TODO (erikj)
  351. def get_send_event_level(self, room_id):
  352. return defer.succeed(0)
  353. def get_power_level(self, room_id, user_id):
  354. return defer.succeed(0)
  355. def get_add_state_level(self, room_id):
  356. return defer.succeed(0)
  357. def get_room_join_rule(self, room_id):
  358. # TODO (erikj): This should be configurable
  359. return defer.succeed("invite")
  360. def get_ops_levels(self, room_id):
  361. return defer.succeed((5, 5, 5))
  362. def insert_client_ip(self, user, access_token, ip, user_agent):
  363. return defer.succeed(None)
  364. def _format_call(args, kwargs):
  365. return ", ".join(
  366. ["%r" % (a) for a in args] +
  367. ["%s=%r" % (k, v) for k, v in kwargs.items()]
  368. )
  369. class DeferredMockCallable(object):
  370. """A callable instance that stores a set of pending call expectations and
  371. return values for them. It allows a unit test to assert that the given set
  372. of function calls are eventually made, by awaiting on them to be called.
  373. """
  374. def __init__(self):
  375. self.expectations = []
  376. self.calls = []
  377. def __call__(self, *args, **kwargs):
  378. self.calls.append((args, kwargs))
  379. if not self.expectations:
  380. raise ValueError("%r has no pending calls to handle call(%s)" % (
  381. self, _format_call(args, kwargs))
  382. )
  383. for (call, result, d) in self.expectations:
  384. if args == call[1] and kwargs == call[2]:
  385. d.callback(None)
  386. return result
  387. failure = AssertionError("Was not expecting call(%s)" % (
  388. _format_call(args, kwargs)
  389. ))
  390. for _, _, d in self.expectations:
  391. try:
  392. d.errback(failure)
  393. except:
  394. pass
  395. raise failure
  396. def expect_call_and_return(self, call, result):
  397. self.expectations.append((call, result, defer.Deferred()))
  398. @defer.inlineCallbacks
  399. def await_calls(self, timeout=1000):
  400. deferred = defer.DeferredList(
  401. [d for _, _, d in self.expectations],
  402. fireOnOneErrback=True
  403. )
  404. timer = reactor.callLater(
  405. timeout / 1000,
  406. deferred.errback,
  407. AssertionError("%d pending calls left: %s" % (
  408. len([e for e in self.expectations if not e[2].called]),
  409. [e for e in self.expectations if not e[2].called]
  410. ))
  411. )
  412. yield deferred
  413. timer.cancel()
  414. self.calls = []
  415. def assert_had_no_calls(self):
  416. if self.calls:
  417. calls = self.calls
  418. self.calls = []
  419. raise AssertionError(
  420. "Expected not to received any calls, got:\n" + "\n".join([
  421. "call(%s)" % _format_call(c[0], c[1]) for c in calls
  422. ])
  423. )