1
0

test_typing.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. import json
  16. from mock import ANY, Mock, call
  17. from twisted.internet import defer
  18. from synapse.api.errors import AuthError
  19. from synapse.types import UserID
  20. from tests import unittest
  21. from tests.unittest import override_config
  22. from tests.utils import register_federation_servlets
  23. # Some local users to test with
  24. U_APPLE = UserID.from_string("@apple:test")
  25. U_BANANA = UserID.from_string("@banana:test")
  26. # Remote user
  27. U_ONION = UserID.from_string("@onion:farm")
  28. # Test room id
  29. ROOM_ID = "a-room"
  30. def _expect_edu_transaction(edu_type, content, origin="test"):
  31. return {
  32. "origin": origin,
  33. "origin_server_ts": 1000000,
  34. "pdus": [],
  35. "edus": [{"edu_type": edu_type, "content": content}],
  36. }
  37. def _make_edu_transaction_json(edu_type, content):
  38. return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8")
  39. class TypingNotificationsTestCase(unittest.HomeserverTestCase):
  40. servlets = [register_federation_servlets]
  41. def make_homeserver(self, reactor, clock):
  42. # we mock out the keyring so as to skip the authentication check on the
  43. # federation API call.
  44. mock_keyring = Mock(spec=["verify_json_for_server"])
  45. mock_keyring.verify_json_for_server.return_value = defer.succeed(True)
  46. # we mock out the federation client too
  47. mock_federation_client = Mock(spec=["put_json"])
  48. mock_federation_client.put_json.return_value = defer.succeed((200, "OK"))
  49. datastores = Mock()
  50. datastores.main = Mock(
  51. spec=[
  52. # Bits that Federation needs
  53. "prep_send_transaction",
  54. "delivered_txn",
  55. "get_received_txn_response",
  56. "set_received_txn_response",
  57. "get_destination_retry_timings",
  58. "get_devices_by_remote",
  59. # Bits that user_directory needs
  60. "get_user_directory_stream_pos",
  61. "get_current_state_deltas",
  62. "get_device_updates_by_remote",
  63. ]
  64. )
  65. hs = self.setup_test_homeserver(
  66. notifier=Mock(), http_client=mock_federation_client, keyring=mock_keyring
  67. )
  68. hs.datastores = datastores
  69. return hs
  70. def prepare(self, reactor, clock, hs):
  71. # the tests assume that we are starting at unix time 1000
  72. reactor.pump((1000,))
  73. mock_notifier = hs.get_notifier()
  74. self.on_new_event = mock_notifier.on_new_event
  75. self.handler = hs.get_typing_handler()
  76. self.event_source = hs.get_event_sources().sources["typing"]
  77. self.datastore = hs.get_datastore()
  78. retry_timings_res = {
  79. "destination": "",
  80. "retry_last_ts": 0,
  81. "retry_interval": 0,
  82. "failure_ts": None,
  83. }
  84. self.datastore.get_destination_retry_timings.return_value = defer.succeed(
  85. retry_timings_res
  86. )
  87. self.datastore.get_device_updates_by_remote.return_value = (0, [])
  88. def get_received_txn_response(*args):
  89. return defer.succeed(None)
  90. self.datastore.get_received_txn_response = get_received_txn_response
  91. self.room_members = []
  92. def check_joined_room(room_id, user_id):
  93. if user_id not in [u.to_string() for u in self.room_members]:
  94. raise AuthError(401, "User is not in the room")
  95. hs.get_auth().check_joined_room = check_joined_room
  96. def get_joined_hosts_for_room(room_id):
  97. return set(member.domain for member in self.room_members)
  98. self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room
  99. def get_current_users_in_room(room_id):
  100. return set(str(u) for u in self.room_members)
  101. hs.get_state_handler().get_current_users_in_room = get_current_users_in_room
  102. self.datastore.get_user_directory_stream_pos.return_value = (
  103. # we deliberately return a non-None stream pos to avoid doing an initial_spam
  104. defer.succeed(1)
  105. )
  106. self.datastore.get_current_state_deltas.return_value = (0, None)
  107. self.datastore.get_to_device_stream_token = lambda: 0
  108. self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: ([], 0)
  109. self.datastore.delete_device_msgs_for_remote = lambda *args, **kargs: None
  110. self.datastore.set_received_txn_response = lambda *args, **kwargs: defer.succeed(
  111. None
  112. )
  113. def test_started_typing_local(self):
  114. self.room_members = [U_APPLE, U_BANANA]
  115. self.assertEquals(self.event_source.get_current_key(), 0)
  116. self.successResultOf(
  117. self.handler.started_typing(
  118. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  119. )
  120. )
  121. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  122. self.assertEquals(self.event_source.get_current_key(), 1)
  123. events = self.get_success(
  124. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  125. )
  126. self.assertEquals(
  127. events[0],
  128. [
  129. {
  130. "type": "m.typing",
  131. "room_id": ROOM_ID,
  132. "content": {"user_ids": [U_APPLE.to_string()]},
  133. }
  134. ],
  135. )
  136. @override_config({"send_federation": True})
  137. def test_started_typing_remote_send(self):
  138. self.room_members = [U_APPLE, U_ONION]
  139. self.successResultOf(
  140. self.handler.started_typing(
  141. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  142. )
  143. )
  144. put_json = self.hs.get_http_client().put_json
  145. put_json.assert_called_once_with(
  146. "farm",
  147. path="/_matrix/federation/v1/send/1000000",
  148. data=_expect_edu_transaction(
  149. "m.typing",
  150. content={
  151. "room_id": ROOM_ID,
  152. "user_id": U_APPLE.to_string(),
  153. "typing": True,
  154. },
  155. ),
  156. json_data_callback=ANY,
  157. long_retries=True,
  158. backoff_on_404=True,
  159. try_trailing_slash_on_400=True,
  160. )
  161. def test_started_typing_remote_recv(self):
  162. self.room_members = [U_APPLE, U_ONION]
  163. self.assertEquals(self.event_source.get_current_key(), 0)
  164. (request, channel) = self.make_request(
  165. "PUT",
  166. "/_matrix/federation/v1/send/1000000",
  167. _make_edu_transaction_json(
  168. "m.typing",
  169. content={
  170. "room_id": ROOM_ID,
  171. "user_id": U_ONION.to_string(),
  172. "typing": True,
  173. },
  174. ),
  175. federation_auth_origin=b"farm",
  176. )
  177. self.render(request)
  178. self.assertEqual(channel.code, 200)
  179. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  180. self.assertEquals(self.event_source.get_current_key(), 1)
  181. events = self.get_success(
  182. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  183. )
  184. self.assertEquals(
  185. events[0],
  186. [
  187. {
  188. "type": "m.typing",
  189. "room_id": ROOM_ID,
  190. "content": {"user_ids": [U_ONION.to_string()]},
  191. }
  192. ],
  193. )
  194. @override_config({"send_federation": True})
  195. def test_stopped_typing(self):
  196. self.room_members = [U_APPLE, U_BANANA, U_ONION]
  197. # Gut-wrenching
  198. from synapse.handlers.typing import RoomMember
  199. member = RoomMember(ROOM_ID, U_APPLE.to_string())
  200. self.handler._member_typing_until[member] = 1002000
  201. self.handler._room_typing[ROOM_ID] = set([U_APPLE.to_string()])
  202. self.assertEquals(self.event_source.get_current_key(), 0)
  203. self.successResultOf(
  204. self.handler.stopped_typing(
  205. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID
  206. )
  207. )
  208. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  209. put_json = self.hs.get_http_client().put_json
  210. put_json.assert_called_once_with(
  211. "farm",
  212. path="/_matrix/federation/v1/send/1000000",
  213. data=_expect_edu_transaction(
  214. "m.typing",
  215. content={
  216. "room_id": ROOM_ID,
  217. "user_id": U_APPLE.to_string(),
  218. "typing": False,
  219. },
  220. ),
  221. json_data_callback=ANY,
  222. long_retries=True,
  223. backoff_on_404=True,
  224. try_trailing_slash_on_400=True,
  225. )
  226. self.assertEquals(self.event_source.get_current_key(), 1)
  227. events = self.get_success(
  228. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  229. )
  230. self.assertEquals(
  231. events[0],
  232. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  233. )
  234. def test_typing_timeout(self):
  235. self.room_members = [U_APPLE, U_BANANA]
  236. self.assertEquals(self.event_source.get_current_key(), 0)
  237. self.successResultOf(
  238. self.handler.started_typing(
  239. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  240. )
  241. )
  242. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  243. self.on_new_event.reset_mock()
  244. self.assertEquals(self.event_source.get_current_key(), 1)
  245. events = self.get_success(
  246. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  247. )
  248. self.assertEquals(
  249. events[0],
  250. [
  251. {
  252. "type": "m.typing",
  253. "room_id": ROOM_ID,
  254. "content": {"user_ids": [U_APPLE.to_string()]},
  255. }
  256. ],
  257. )
  258. self.reactor.pump([16])
  259. self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])])
  260. self.assertEquals(self.event_source.get_current_key(), 2)
  261. events = self.get_success(
  262. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1)
  263. )
  264. self.assertEquals(
  265. events[0],
  266. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  267. )
  268. # SYN-230 - see if we can still set after timeout
  269. self.successResultOf(
  270. self.handler.started_typing(
  271. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  272. )
  273. )
  274. self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])])
  275. self.on_new_event.reset_mock()
  276. self.assertEquals(self.event_source.get_current_key(), 3)
  277. events = self.get_success(
  278. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  279. )
  280. self.assertEquals(
  281. events[0],
  282. [
  283. {
  284. "type": "m.typing",
  285. "room_id": ROOM_ID,
  286. "content": {"user_ids": [U_APPLE.to_string()]},
  287. }
  288. ],
  289. )