test_typing.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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.utils import register_federation_servlets
  22. # Some local users to test with
  23. U_APPLE = UserID.from_string("@apple:test")
  24. U_BANANA = UserID.from_string("@banana:test")
  25. # Remote user
  26. U_ONION = UserID.from_string("@onion:farm")
  27. # Test room id
  28. ROOM_ID = "a-room"
  29. def _expect_edu_transaction(edu_type, content, origin="test"):
  30. return {
  31. "origin": origin,
  32. "origin_server_ts": 1000000,
  33. "pdus": [],
  34. "edus": [{"edu_type": edu_type, "content": content}],
  35. }
  36. def _make_edu_transaction_json(edu_type, content):
  37. return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8")
  38. class TypingNotificationsTestCase(unittest.HomeserverTestCase):
  39. servlets = [register_federation_servlets]
  40. def make_homeserver(self, reactor, clock):
  41. # we mock out the keyring so as to skip the authentication check on the
  42. # federation API call.
  43. mock_keyring = Mock(spec=["verify_json_for_server"])
  44. mock_keyring.verify_json_for_server.return_value = defer.succeed(True)
  45. # we mock out the federation client too
  46. mock_federation_client = Mock(spec=["put_json"])
  47. mock_federation_client.put_json.return_value = defer.succeed((200, "OK"))
  48. hs = self.setup_test_homeserver(
  49. datastore=(
  50. 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. ]
  63. )
  64. ),
  65. notifier=Mock(),
  66. http_client=mock_federation_client,
  67. keyring=mock_keyring,
  68. )
  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_devices_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 = 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. def test_started_typing_local(self):
  111. self.room_members = [U_APPLE, U_BANANA]
  112. self.assertEquals(self.event_source.get_current_key(), 0)
  113. self.successResultOf(
  114. self.handler.started_typing(
  115. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  116. )
  117. )
  118. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  119. self.assertEquals(self.event_source.get_current_key(), 1)
  120. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  121. self.assertEquals(
  122. events[0],
  123. [
  124. {
  125. "type": "m.typing",
  126. "room_id": ROOM_ID,
  127. "content": {"user_ids": [U_APPLE.to_string()]},
  128. }
  129. ],
  130. )
  131. def test_started_typing_remote_send(self):
  132. self.room_members = [U_APPLE, U_ONION]
  133. self.successResultOf(
  134. self.handler.started_typing(
  135. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  136. )
  137. )
  138. put_json = self.hs.get_http_client().put_json
  139. put_json.assert_called_once_with(
  140. "farm",
  141. path="/_matrix/federation/v1/send/1000000",
  142. data=_expect_edu_transaction(
  143. "m.typing",
  144. content={
  145. "room_id": ROOM_ID,
  146. "user_id": U_APPLE.to_string(),
  147. "typing": True,
  148. },
  149. ),
  150. json_data_callback=ANY,
  151. long_retries=True,
  152. backoff_on_404=True,
  153. try_trailing_slash_on_400=True,
  154. )
  155. def test_started_typing_remote_recv(self):
  156. self.room_members = [U_APPLE, U_ONION]
  157. self.assertEquals(self.event_source.get_current_key(), 0)
  158. (request, channel) = self.make_request(
  159. "PUT",
  160. "/_matrix/federation/v1/send/1000000",
  161. _make_edu_transaction_json(
  162. "m.typing",
  163. content={
  164. "room_id": ROOM_ID,
  165. "user_id": U_ONION.to_string(),
  166. "typing": True,
  167. },
  168. ),
  169. federation_auth_origin=b"farm",
  170. )
  171. self.render(request)
  172. self.assertEqual(channel.code, 200)
  173. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  174. self.assertEquals(self.event_source.get_current_key(), 1)
  175. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  176. self.assertEquals(
  177. events[0],
  178. [
  179. {
  180. "type": "m.typing",
  181. "room_id": ROOM_ID,
  182. "content": {"user_ids": [U_ONION.to_string()]},
  183. }
  184. ],
  185. )
  186. def test_stopped_typing(self):
  187. self.room_members = [U_APPLE, U_BANANA, U_ONION]
  188. # Gut-wrenching
  189. from synapse.handlers.typing import RoomMember
  190. member = RoomMember(ROOM_ID, U_APPLE.to_string())
  191. self.handler._member_typing_until[member] = 1002000
  192. self.handler._room_typing[ROOM_ID] = set([U_APPLE.to_string()])
  193. self.assertEquals(self.event_source.get_current_key(), 0)
  194. self.successResultOf(
  195. self.handler.stopped_typing(
  196. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID
  197. )
  198. )
  199. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  200. put_json = self.hs.get_http_client().put_json
  201. put_json.assert_called_once_with(
  202. "farm",
  203. path="/_matrix/federation/v1/send/1000000",
  204. data=_expect_edu_transaction(
  205. "m.typing",
  206. content={
  207. "room_id": ROOM_ID,
  208. "user_id": U_APPLE.to_string(),
  209. "typing": False,
  210. },
  211. ),
  212. json_data_callback=ANY,
  213. long_retries=True,
  214. backoff_on_404=True,
  215. try_trailing_slash_on_400=True,
  216. )
  217. self.assertEquals(self.event_source.get_current_key(), 1)
  218. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  219. self.assertEquals(
  220. events[0],
  221. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  222. )
  223. def test_typing_timeout(self):
  224. self.room_members = [U_APPLE, U_BANANA]
  225. self.assertEquals(self.event_source.get_current_key(), 0)
  226. self.successResultOf(
  227. self.handler.started_typing(
  228. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  229. )
  230. )
  231. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  232. self.on_new_event.reset_mock()
  233. self.assertEquals(self.event_source.get_current_key(), 1)
  234. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  235. self.assertEquals(
  236. events[0],
  237. [
  238. {
  239. "type": "m.typing",
  240. "room_id": ROOM_ID,
  241. "content": {"user_ids": [U_APPLE.to_string()]},
  242. }
  243. ],
  244. )
  245. self.reactor.pump([16])
  246. self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])])
  247. self.assertEquals(self.event_source.get_current_key(), 2)
  248. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1)
  249. self.assertEquals(
  250. events[0],
  251. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  252. )
  253. # SYN-230 - see if we can still set after timeout
  254. self.successResultOf(
  255. self.handler.started_typing(
  256. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  257. )
  258. )
  259. self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])])
  260. self.on_new_event.reset_mock()
  261. self.assertEquals(self.event_source.get_current_key(), 3)
  262. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  263. self.assertEquals(
  264. events[0],
  265. [
  266. {
  267. "type": "m.typing",
  268. "room_id": ROOM_ID,
  269. "content": {"user_ids": [U_APPLE.to_string()]},
  270. }
  271. ],
  272. )