utils.py 13 KB

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