utils.py 14 KB

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