utils.py 16 KB

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