utils.py 13 KB

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