test_typing.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. "maybe_store_room_on_invite",
  60. # Bits that user_directory needs
  61. "get_user_directory_stream_pos",
  62. "get_current_state_deltas",
  63. "get_device_updates_by_remote",
  64. ]
  65. )
  66. # the tests assume that we are starting at unix time 1000
  67. reactor.pump((1000,))
  68. hs = self.setup_test_homeserver(
  69. notifier=Mock(),
  70. http_client=mock_federation_client,
  71. keyring=mock_keyring,
  72. replication_streams={},
  73. )
  74. hs.datastores = datastores
  75. return hs
  76. def prepare(self, reactor, clock, hs):
  77. mock_notifier = hs.get_notifier()
  78. self.on_new_event = mock_notifier.on_new_event
  79. self.handler = hs.get_typing_handler()
  80. self.event_source = hs.get_event_sources().sources["typing"]
  81. self.datastore = hs.get_datastore()
  82. retry_timings_res = {
  83. "destination": "",
  84. "retry_last_ts": 0,
  85. "retry_interval": 0,
  86. "failure_ts": None,
  87. }
  88. self.datastore.get_destination_retry_timings.return_value = defer.succeed(
  89. retry_timings_res
  90. )
  91. self.datastore.get_device_updates_by_remote.return_value = defer.succeed(
  92. (0, [])
  93. )
  94. def get_received_txn_response(*args):
  95. return defer.succeed(None)
  96. self.datastore.get_received_txn_response = get_received_txn_response
  97. self.room_members = []
  98. def check_user_in_room(room_id, user_id):
  99. if user_id not in [u.to_string() for u in self.room_members]:
  100. raise AuthError(401, "User is not in the room")
  101. hs.get_auth().check_user_in_room = check_user_in_room
  102. def get_joined_hosts_for_room(room_id):
  103. return {member.domain for member in self.room_members}
  104. self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room
  105. def get_current_users_in_room(room_id):
  106. return {str(u) for u in self.room_members}
  107. hs.get_state_handler().get_current_users_in_room = get_current_users_in_room
  108. self.datastore.get_user_directory_stream_pos.return_value = (
  109. # we deliberately return a non-None stream pos to avoid doing an initial_spam
  110. defer.succeed(1)
  111. )
  112. self.datastore.get_current_state_deltas.return_value = (0, None)
  113. self.datastore.get_to_device_stream_token = lambda: 0
  114. self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: defer.succeed(
  115. ([], 0)
  116. )
  117. self.datastore.delete_device_msgs_for_remote = lambda *args, **kargs: None
  118. self.datastore.set_received_txn_response = lambda *args, **kwargs: defer.succeed(
  119. None
  120. )
  121. def test_started_typing_local(self):
  122. self.room_members = [U_APPLE, U_BANANA]
  123. self.assertEquals(self.event_source.get_current_key(), 0)
  124. self.successResultOf(
  125. self.handler.started_typing(
  126. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  127. )
  128. )
  129. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  130. self.assertEquals(self.event_source.get_current_key(), 1)
  131. events = self.get_success(
  132. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  133. )
  134. self.assertEquals(
  135. events[0],
  136. [
  137. {
  138. "type": "m.typing",
  139. "room_id": ROOM_ID,
  140. "content": {"user_ids": [U_APPLE.to_string()]},
  141. }
  142. ],
  143. )
  144. @override_config({"send_federation": True})
  145. def test_started_typing_remote_send(self):
  146. self.room_members = [U_APPLE, U_ONION]
  147. self.successResultOf(
  148. self.handler.started_typing(
  149. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  150. )
  151. )
  152. put_json = self.hs.get_http_client().put_json
  153. put_json.assert_called_once_with(
  154. "farm",
  155. path="/_matrix/federation/v1/send/1000000",
  156. data=_expect_edu_transaction(
  157. "m.typing",
  158. content={
  159. "room_id": ROOM_ID,
  160. "user_id": U_APPLE.to_string(),
  161. "typing": True,
  162. },
  163. ),
  164. json_data_callback=ANY,
  165. long_retries=True,
  166. backoff_on_404=True,
  167. try_trailing_slash_on_400=True,
  168. )
  169. def test_started_typing_remote_recv(self):
  170. self.room_members = [U_APPLE, U_ONION]
  171. self.assertEquals(self.event_source.get_current_key(), 0)
  172. (request, channel) = self.make_request(
  173. "PUT",
  174. "/_matrix/federation/v1/send/1000000",
  175. _make_edu_transaction_json(
  176. "m.typing",
  177. content={
  178. "room_id": ROOM_ID,
  179. "user_id": U_ONION.to_string(),
  180. "typing": True,
  181. },
  182. ),
  183. federation_auth_origin=b"farm",
  184. )
  185. self.render(request)
  186. self.assertEqual(channel.code, 200)
  187. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  188. self.assertEquals(self.event_source.get_current_key(), 1)
  189. events = self.get_success(
  190. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  191. )
  192. self.assertEquals(
  193. events[0],
  194. [
  195. {
  196. "type": "m.typing",
  197. "room_id": ROOM_ID,
  198. "content": {"user_ids": [U_ONION.to_string()]},
  199. }
  200. ],
  201. )
  202. @override_config({"send_federation": True})
  203. def test_stopped_typing(self):
  204. self.room_members = [U_APPLE, U_BANANA, U_ONION]
  205. # Gut-wrenching
  206. from synapse.handlers.typing import RoomMember
  207. member = RoomMember(ROOM_ID, U_APPLE.to_string())
  208. self.handler._member_typing_until[member] = 1002000
  209. self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()}
  210. self.assertEquals(self.event_source.get_current_key(), 0)
  211. self.successResultOf(
  212. self.handler.stopped_typing(
  213. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID
  214. )
  215. )
  216. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  217. put_json = self.hs.get_http_client().put_json
  218. put_json.assert_called_once_with(
  219. "farm",
  220. path="/_matrix/federation/v1/send/1000000",
  221. data=_expect_edu_transaction(
  222. "m.typing",
  223. content={
  224. "room_id": ROOM_ID,
  225. "user_id": U_APPLE.to_string(),
  226. "typing": False,
  227. },
  228. ),
  229. json_data_callback=ANY,
  230. long_retries=True,
  231. backoff_on_404=True,
  232. try_trailing_slash_on_400=True,
  233. )
  234. self.assertEquals(self.event_source.get_current_key(), 1)
  235. events = self.get_success(
  236. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  237. )
  238. self.assertEquals(
  239. events[0],
  240. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  241. )
  242. def test_typing_timeout(self):
  243. self.room_members = [U_APPLE, U_BANANA]
  244. self.assertEquals(self.event_source.get_current_key(), 0)
  245. self.successResultOf(
  246. self.handler.started_typing(
  247. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  248. )
  249. )
  250. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  251. self.on_new_event.reset_mock()
  252. self.assertEquals(self.event_source.get_current_key(), 1)
  253. events = self.get_success(
  254. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  255. )
  256. self.assertEquals(
  257. events[0],
  258. [
  259. {
  260. "type": "m.typing",
  261. "room_id": ROOM_ID,
  262. "content": {"user_ids": [U_APPLE.to_string()]},
  263. }
  264. ],
  265. )
  266. self.reactor.pump([16])
  267. self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])])
  268. self.assertEquals(self.event_source.get_current_key(), 2)
  269. events = self.get_success(
  270. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1)
  271. )
  272. self.assertEquals(
  273. events[0],
  274. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  275. )
  276. # SYN-230 - see if we can still set after timeout
  277. self.successResultOf(
  278. self.handler.started_typing(
  279. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  280. )
  281. )
  282. self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])])
  283. self.on_new_event.reset_mock()
  284. self.assertEquals(self.event_source.get_current_key(), 3)
  285. events = self.get_success(
  286. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  287. )
  288. self.assertEquals(
  289. events[0],
  290. [
  291. {
  292. "type": "m.typing",
  293. "room_id": ROOM_ID,
  294. "content": {"user_ids": [U_APPLE.to_string()]},
  295. }
  296. ],
  297. )