1
0

test_typing.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. from typing import Dict
  16. from unittest.mock import ANY, Mock, call
  17. from twisted.internet import defer
  18. from twisted.web.resource import Resource
  19. from synapse.api.errors import AuthError
  20. from synapse.federation.transport.server import TransportLayerServer
  21. from synapse.types import UserID, create_requester
  22. from tests import unittest
  23. from tests.test_utils import make_awaitable
  24. from tests.unittest import override_config
  25. # Some local users to test with
  26. U_APPLE = UserID.from_string("@apple:test")
  27. U_BANANA = UserID.from_string("@banana:test")
  28. # Remote user
  29. U_ONION = UserID.from_string("@onion:farm")
  30. # Test room id
  31. ROOM_ID = "a-room"
  32. def _expect_edu_transaction(edu_type, content, origin="test"):
  33. return {
  34. "origin": origin,
  35. "origin_server_ts": 1000000,
  36. "pdus": [],
  37. "edus": [{"edu_type": edu_type, "content": content}],
  38. }
  39. def _make_edu_transaction_json(edu_type, content):
  40. return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8")
  41. class TypingNotificationsTestCase(unittest.HomeserverTestCase):
  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. federation_http_client=mock_federation_client,
  55. keyring=mock_keyring,
  56. replication_streams={},
  57. )
  58. return hs
  59. def create_resource_dict(self) -> Dict[str, Resource]:
  60. d = super().create_resource_dict()
  61. d["/_matrix/federation"] = TransportLayerServer(self.hs)
  62. return d
  63. def prepare(self, reactor, clock, hs):
  64. mock_notifier = hs.get_notifier()
  65. self.on_new_event = mock_notifier.on_new_event
  66. self.handler = hs.get_typing_handler()
  67. self.event_source = hs.get_event_sources().sources["typing"]
  68. self.datastore = hs.get_datastore()
  69. retry_timings_res = {
  70. "destination": "",
  71. "retry_last_ts": 0,
  72. "retry_interval": 0,
  73. "failure_ts": None,
  74. }
  75. self.datastore.get_destination_retry_timings = Mock(
  76. return_value=defer.succeed(retry_timings_res)
  77. )
  78. self.datastore.get_device_updates_by_remote = Mock(
  79. return_value=make_awaitable((0, []))
  80. )
  81. self.datastore.get_destination_last_successful_stream_ordering = Mock(
  82. return_value=make_awaitable(None)
  83. )
  84. def get_received_txn_response(*args):
  85. return defer.succeed(None)
  86. self.datastore.get_received_txn_response = get_received_txn_response
  87. self.room_members = []
  88. async def check_user_in_room(room_id, user_id):
  89. if user_id not in [u.to_string() for u in self.room_members]:
  90. raise AuthError(401, "User is not in the room")
  91. return None
  92. hs.get_auth().check_user_in_room = check_user_in_room
  93. def get_joined_hosts_for_room(room_id):
  94. return {member.domain for member in self.room_members}
  95. self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room
  96. async def get_users_in_room(room_id):
  97. return {str(u) for u in self.room_members}
  98. self.datastore.get_users_in_room = get_users_in_room
  99. self.datastore.get_user_directory_stream_pos = Mock(
  100. side_effect=(
  101. # we deliberately return a non-None stream pos to avoid doing an initial_spam
  102. lambda: make_awaitable(1)
  103. )
  104. )
  105. self.datastore.get_current_state_deltas = Mock(return_value=(0, None))
  106. self.datastore.get_to_device_stream_token = lambda: 0
  107. self.datastore.get_new_device_msgs_for_remote = (
  108. lambda *args, **kargs: make_awaitable(([], 0))
  109. )
  110. self.datastore.delete_device_msgs_for_remote = (
  111. lambda *args, **kargs: make_awaitable(None)
  112. )
  113. self.datastore.set_received_txn_response = (
  114. lambda *args, **kwargs: make_awaitable(None)
  115. )
  116. def test_started_typing_local(self):
  117. self.room_members = [U_APPLE, U_BANANA]
  118. self.assertEquals(self.event_source.get_current_key(), 0)
  119. self.get_success(
  120. self.handler.started_typing(
  121. target_user=U_APPLE,
  122. requester=create_requester(U_APPLE),
  123. room_id=ROOM_ID,
  124. timeout=20000,
  125. )
  126. )
  127. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  128. self.assertEquals(self.event_source.get_current_key(), 1)
  129. events = self.get_success(
  130. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  131. )
  132. self.assertEquals(
  133. events[0],
  134. [
  135. {
  136. "type": "m.typing",
  137. "room_id": ROOM_ID,
  138. "content": {"user_ids": [U_APPLE.to_string()]},
  139. }
  140. ],
  141. )
  142. @override_config({"send_federation": True})
  143. def test_started_typing_remote_send(self):
  144. self.room_members = [U_APPLE, U_ONION]
  145. self.get_success(
  146. self.handler.started_typing(
  147. target_user=U_APPLE,
  148. requester=create_requester(U_APPLE),
  149. room_id=ROOM_ID,
  150. timeout=20000,
  151. )
  152. )
  153. put_json = self.hs.get_federation_http_client().put_json
  154. put_json.assert_called_once_with(
  155. "farm",
  156. path="/_matrix/federation/v1/send/1000000",
  157. data=_expect_edu_transaction(
  158. "m.typing",
  159. content={
  160. "room_id": ROOM_ID,
  161. "user_id": U_APPLE.to_string(),
  162. "typing": True,
  163. },
  164. ),
  165. json_data_callback=ANY,
  166. long_retries=True,
  167. backoff_on_404=True,
  168. try_trailing_slash_on_400=True,
  169. )
  170. def test_started_typing_remote_recv(self):
  171. self.room_members = [U_APPLE, U_ONION]
  172. self.assertEquals(self.event_source.get_current_key(), 0)
  173. channel = self.make_request(
  174. "PUT",
  175. "/_matrix/federation/v1/send/1000000",
  176. _make_edu_transaction_json(
  177. "m.typing",
  178. content={
  179. "room_id": ROOM_ID,
  180. "user_id": U_ONION.to_string(),
  181. "typing": True,
  182. },
  183. ),
  184. federation_auth_origin=b"farm",
  185. )
  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.get_success(
  212. self.handler.stopped_typing(
  213. target_user=U_APPLE,
  214. requester=create_requester(U_APPLE),
  215. room_id=ROOM_ID,
  216. )
  217. )
  218. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  219. put_json = self.hs.get_federation_http_client().put_json
  220. put_json.assert_called_once_with(
  221. "farm",
  222. path="/_matrix/federation/v1/send/1000000",
  223. data=_expect_edu_transaction(
  224. "m.typing",
  225. content={
  226. "room_id": ROOM_ID,
  227. "user_id": U_APPLE.to_string(),
  228. "typing": False,
  229. },
  230. ),
  231. json_data_callback=ANY,
  232. long_retries=True,
  233. backoff_on_404=True,
  234. try_trailing_slash_on_400=True,
  235. )
  236. self.assertEquals(self.event_source.get_current_key(), 1)
  237. events = self.get_success(
  238. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  239. )
  240. self.assertEquals(
  241. events[0],
  242. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  243. )
  244. def test_typing_timeout(self):
  245. self.room_members = [U_APPLE, U_BANANA]
  246. self.assertEquals(self.event_source.get_current_key(), 0)
  247. self.get_success(
  248. self.handler.started_typing(
  249. target_user=U_APPLE,
  250. requester=create_requester(U_APPLE),
  251. room_id=ROOM_ID,
  252. timeout=10000,
  253. )
  254. )
  255. self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])])
  256. self.on_new_event.reset_mock()
  257. self.assertEquals(self.event_source.get_current_key(), 1)
  258. events = self.get_success(
  259. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  260. )
  261. self.assertEquals(
  262. events[0],
  263. [
  264. {
  265. "type": "m.typing",
  266. "room_id": ROOM_ID,
  267. "content": {"user_ids": [U_APPLE.to_string()]},
  268. }
  269. ],
  270. )
  271. self.reactor.pump([16])
  272. self.on_new_event.assert_has_calls([call("typing_key", 2, rooms=[ROOM_ID])])
  273. self.assertEquals(self.event_source.get_current_key(), 2)
  274. events = self.get_success(
  275. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=1)
  276. )
  277. self.assertEquals(
  278. events[0],
  279. [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}],
  280. )
  281. # SYN-230 - see if we can still set after timeout
  282. self.get_success(
  283. self.handler.started_typing(
  284. target_user=U_APPLE,
  285. requester=create_requester(U_APPLE),
  286. room_id=ROOM_ID,
  287. timeout=10000,
  288. )
  289. )
  290. self.on_new_event.assert_has_calls([call("typing_key", 3, rooms=[ROOM_ID])])
  291. self.on_new_event.reset_mock()
  292. self.assertEquals(self.event_source.get_current_key(), 3)
  293. events = self.get_success(
  294. self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0)
  295. )
  296. self.assertEquals(
  297. events[0],
  298. [
  299. {
  300. "type": "m.typing",
  301. "room_id": ROOM_ID,
  302. "content": {"user_ids": [U_APPLE.to_string()]},
  303. }
  304. ],
  305. )