test_typing.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 = {"destination": "", "retry_last_ts": 0, "retry_interval": 0}
  79. self.datastore.get_destination_retry_timings.return_value = defer.succeed(
  80. retry_timings_res
  81. )
  82. self.datastore.get_devices_by_remote.return_value = (0, [])
  83. def get_received_txn_response(*args):
  84. return defer.succeed(None)
  85. self.datastore.get_received_txn_response = get_received_txn_response
  86. self.room_members = []
  87. def check_joined_room(room_id, user_id):
  88. if user_id not in [u.to_string() for u in self.room_members]:
  89. raise AuthError(401, "User is not in the room")
  90. hs.get_auth().check_joined_room = check_joined_room
  91. def get_joined_hosts_for_room(room_id):
  92. return set(member.domain for member in self.room_members)
  93. self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room
  94. def get_current_users_in_room(room_id):
  95. return set(str(u) for u in self.room_members)
  96. hs.get_state_handler().get_current_users_in_room = get_current_users_in_room
  97. self.datastore.get_user_directory_stream_pos.return_value = (
  98. # we deliberately return a non-None stream pos to avoid doing an initial_spam
  99. defer.succeed(1)
  100. )
  101. self.datastore.get_current_state_deltas.return_value = None
  102. self.datastore.get_to_device_stream_token = lambda: 0
  103. self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: ([], 0)
  104. self.datastore.delete_device_msgs_for_remote = lambda *args, **kargs: None
  105. def test_started_typing_local(self):
  106. self.room_members = [U_APPLE, U_BANANA]
  107. self.assertEquals(self.event_source.get_current_key(), 0)
  108. self.successResultOf(
  109. self.handler.started_typing(
  110. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  111. )
  112. )
  113. self.on_new_event.assert_has_calls([call('typing_key', 1, rooms=[ROOM_ID])])
  114. self.assertEquals(self.event_source.get_current_key(), 1)
  115. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  116. self.assertEquals(
  117. events[0],
  118. [
  119. {
  120. "type": "m.typing",
  121. "room_id": ROOM_ID,
  122. "content": {"user_ids": [U_APPLE.to_string()]},
  123. }
  124. ],
  125. )
  126. def test_started_typing_remote_send(self):
  127. self.room_members = [U_APPLE, U_ONION]
  128. self.successResultOf(
  129. self.handler.started_typing(
  130. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=20000
  131. )
  132. )
  133. put_json = self.hs.get_http_client().put_json
  134. put_json.assert_called_once_with(
  135. "farm",
  136. path="/_matrix/federation/v1/send/1000000",
  137. data=_expect_edu_transaction(
  138. "m.typing",
  139. content={
  140. "room_id": ROOM_ID,
  141. "user_id": U_APPLE.to_string(),
  142. "typing": True,
  143. },
  144. ),
  145. json_data_callback=ANY,
  146. long_retries=True,
  147. backoff_on_404=True,
  148. try_trailing_slash_on_400=True,
  149. )
  150. def test_started_typing_remote_recv(self):
  151. self.room_members = [U_APPLE, U_ONION]
  152. self.assertEquals(self.event_source.get_current_key(), 0)
  153. (request, channel) = self.make_request(
  154. "PUT",
  155. "/_matrix/federation/v1/send/1000000",
  156. _make_edu_transaction_json(
  157. "m.typing",
  158. content={
  159. "room_id": ROOM_ID,
  160. "user_id": U_ONION.to_string(),
  161. "typing": True,
  162. },
  163. ),
  164. federation_auth_origin=b'farm',
  165. )
  166. self.render(request)
  167. self.assertEqual(channel.code, 200)
  168. self.on_new_event.assert_has_calls([call('typing_key', 1, rooms=[ROOM_ID])])
  169. self.assertEquals(self.event_source.get_current_key(), 1)
  170. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  171. self.assertEquals(
  172. events[0],
  173. [
  174. {
  175. "type": "m.typing",
  176. "room_id": ROOM_ID,
  177. "content": {"user_ids": [U_ONION.to_string()]},
  178. }
  179. ],
  180. )
  181. def test_stopped_typing(self):
  182. self.room_members = [U_APPLE, U_BANANA, U_ONION]
  183. # Gut-wrenching
  184. from synapse.handlers.typing import RoomMember
  185. member = RoomMember(ROOM_ID, U_APPLE.to_string())
  186. self.handler._member_typing_until[member] = 1002000
  187. self.handler._room_typing[ROOM_ID] = set([U_APPLE.to_string()])
  188. self.assertEquals(self.event_source.get_current_key(), 0)
  189. self.successResultOf(
  190. self.handler.stopped_typing(
  191. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID
  192. )
  193. )
  194. self.on_new_event.assert_has_calls([call('typing_key', 1, rooms=[ROOM_ID])])
  195. put_json = self.hs.get_http_client().put_json
  196. put_json.assert_called_once_with(
  197. "farm",
  198. path="/_matrix/federation/v1/send/1000000",
  199. data=_expect_edu_transaction(
  200. "m.typing",
  201. content={
  202. "room_id": ROOM_ID,
  203. "user_id": U_APPLE.to_string(),
  204. "typing": False,
  205. },
  206. ),
  207. json_data_callback=ANY,
  208. long_retries=True,
  209. backoff_on_404=True,
  210. try_trailing_slash_on_400=True,
  211. )
  212. self.assertEquals(self.event_source.get_current_key(), 1)
  213. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  214. self.assertEquals(
  215. events[0],
  216. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  217. )
  218. def test_typing_timeout(self):
  219. self.room_members = [U_APPLE, U_BANANA]
  220. self.assertEquals(self.event_source.get_current_key(), 0)
  221. self.successResultOf(
  222. self.handler.started_typing(
  223. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  224. )
  225. )
  226. self.on_new_event.assert_has_calls([call('typing_key', 1, rooms=[ROOM_ID])])
  227. self.on_new_event.reset_mock()
  228. self.assertEquals(self.event_source.get_current_key(), 1)
  229. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  230. self.assertEquals(
  231. events[0],
  232. [
  233. {
  234. "type": "m.typing",
  235. "room_id": ROOM_ID,
  236. "content": {"user_ids": [U_APPLE.to_string()]},
  237. }
  238. ],
  239. )
  240. self.reactor.pump([16])
  241. self.on_new_event.assert_has_calls([call('typing_key', 2, rooms=[ROOM_ID])])
  242. self.assertEquals(self.event_source.get_current_key(), 2)
  243. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1)
  244. self.assertEquals(
  245. events[0],
  246. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  247. )
  248. # SYN-230 - see if we can still set after timeout
  249. self.successResultOf(
  250. self.handler.started_typing(
  251. target_user=U_APPLE, auth_user=U_APPLE, room_id=ROOM_ID, timeout=10000
  252. )
  253. )
  254. self.on_new_event.assert_has_calls([call('typing_key', 3, rooms=[ROOM_ID])])
  255. self.on_new_event.reset_mock()
  256. self.assertEquals(self.event_source.get_current_key(), 3)
  257. events = self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  258. self.assertEquals(
  259. events[0],
  260. [
  261. {
  262. "type": "m.typing",
  263. "room_id": ROOM_ID,
  264. "content": {"user_ids": [U_APPLE.to_string()]},
  265. }
  266. ],
  267. )