test_typing.py 12 KB

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