test_resource_limits_server_notices.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018, 2019 New Vector 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. from mock import Mock
  16. from twisted.internet import defer
  17. from synapse.api.constants import EventTypes, ServerNoticeMsgType
  18. from synapse.api.errors import ResourceLimitError
  19. from synapse.server_notices.resource_limits_server_notices import (
  20. ResourceLimitsServerNotices,
  21. )
  22. from tests import unittest
  23. class TestResourceLimitsServerNotices(unittest.HomeserverTestCase):
  24. def make_homeserver(self, reactor, clock):
  25. hs_config = self.default_config("test")
  26. hs_config["server_notices"] = {
  27. "system_mxid_localpart": "server",
  28. "system_mxid_display_name": "test display name",
  29. "system_mxid_avatar_url": None,
  30. "room_name": "Server Notices",
  31. }
  32. hs = self.setup_test_homeserver(config=hs_config)
  33. return hs
  34. def prepare(self, reactor, clock, hs):
  35. self.server_notices_sender = self.hs.get_server_notices_sender()
  36. # relying on [1] is far from ideal, but the only case where
  37. # ResourceLimitsServerNotices class needs to be isolated is this test,
  38. # general code should never have a reason to do so ...
  39. self._rlsn = self.server_notices_sender._server_notices[1]
  40. if not isinstance(self._rlsn, ResourceLimitsServerNotices):
  41. raise Exception("Failed to find reference to ResourceLimitsServerNotices")
  42. self._rlsn._store.user_last_seen_monthly_active = Mock(
  43. return_value=defer.succeed(1000)
  44. )
  45. self._send_notice = self._rlsn._server_notices_manager.send_notice
  46. self._rlsn._server_notices_manager.send_notice = Mock()
  47. self._rlsn._state.get_current_state = Mock(return_value=defer.succeed(None))
  48. self._rlsn._store.get_events = Mock(return_value=defer.succeed({}))
  49. self._send_notice = self._rlsn._server_notices_manager.send_notice
  50. self.hs.config.limit_usage_by_mau = True
  51. self.user_id = "@user_id:test"
  52. # self.server_notices_mxid = "@server:test"
  53. # self.server_notices_mxid_display_name = None
  54. # self.server_notices_mxid_avatar_url = None
  55. # self.server_notices_room_name = "Server Notices"
  56. self._rlsn._server_notices_manager.get_notice_room_for_user = Mock(
  57. returnValue=""
  58. )
  59. self._rlsn._store.add_tag_to_room = Mock()
  60. self._rlsn._store.get_tags_for_room = Mock(return_value={})
  61. self.hs.config.admin_contact = "mailto:user@test.com"
  62. def test_maybe_send_server_notice_to_user_flag_off(self):
  63. """Tests cases where the flags indicate nothing to do"""
  64. # test hs disabled case
  65. self.hs.config.hs_disabled = True
  66. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  67. self._send_notice.assert_not_called()
  68. # Test when mau limiting disabled
  69. self.hs.config.hs_disabled = False
  70. self.hs.config.limit_usage_by_mau = False
  71. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  72. self._send_notice.assert_not_called()
  73. def test_maybe_send_server_notice_to_user_remove_blocked_notice(self):
  74. """Test when user has blocked notice, but should have it removed"""
  75. self._rlsn._auth.check_auth_blocking = Mock()
  76. mock_event = Mock(
  77. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  78. )
  79. self._rlsn._store.get_events = Mock(
  80. return_value=defer.succeed({"123": mock_event})
  81. )
  82. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  83. # Would be better to check the content, but once == remove blocking event
  84. self._send_notice.assert_called_once()
  85. def test_maybe_send_server_notice_to_user_remove_blocked_notice_noop(self):
  86. """
  87. Test when user has blocked notice, but notice ought to be there (NOOP)
  88. """
  89. self._rlsn._auth.check_auth_blocking = Mock(
  90. side_effect=ResourceLimitError(403, "foo")
  91. )
  92. mock_event = Mock(
  93. type=EventTypes.Message, content={"msgtype": ServerNoticeMsgType}
  94. )
  95. self._rlsn._store.get_events = Mock(
  96. return_value=defer.succeed({"123": mock_event})
  97. )
  98. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  99. self._send_notice.assert_not_called()
  100. def test_maybe_send_server_notice_to_user_add_blocked_notice(self):
  101. """
  102. Test when user does not have blocked notice, but should have one
  103. """
  104. self._rlsn._auth.check_auth_blocking = Mock(
  105. side_effect=ResourceLimitError(403, "foo")
  106. )
  107. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  108. # Would be better to check contents, but 2 calls == set blocking event
  109. self.assertTrue(self._send_notice.call_count == 2)
  110. def test_maybe_send_server_notice_to_user_add_blocked_notice_noop(self):
  111. """
  112. Test when user does not have blocked notice, nor should they (NOOP)
  113. """
  114. self._rlsn._auth.check_auth_blocking = Mock()
  115. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  116. self._send_notice.assert_not_called()
  117. def test_maybe_send_server_notice_to_user_not_in_mau_cohort(self):
  118. """
  119. Test when user is not part of the MAU cohort - this should not ever
  120. happen - but ...
  121. """
  122. self._rlsn._auth.check_auth_blocking = Mock()
  123. self._rlsn._store.user_last_seen_monthly_active = Mock(
  124. return_value=defer.succeed(None)
  125. )
  126. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  127. self._send_notice.assert_not_called()
  128. class TestResourceLimitsServerNoticesWithRealRooms(unittest.HomeserverTestCase):
  129. def prepare(self, reactor, clock, hs):
  130. self.store = self.hs.get_datastore()
  131. self.server_notices_sender = self.hs.get_server_notices_sender()
  132. self.server_notices_manager = self.hs.get_server_notices_manager()
  133. self.event_source = self.hs.get_event_sources()
  134. # relying on [1] is far from ideal, but the only case where
  135. # ResourceLimitsServerNotices class needs to be isolated is this test,
  136. # general code should never have a reason to do so ...
  137. self._rlsn = self.server_notices_sender._server_notices[1]
  138. if not isinstance(self._rlsn, ResourceLimitsServerNotices):
  139. raise Exception("Failed to find reference to ResourceLimitsServerNotices")
  140. self.hs.config.limit_usage_by_mau = True
  141. self.hs.config.hs_disabled = False
  142. self.hs.config.max_mau_value = 5
  143. self.hs.config.server_notices_mxid = "@server:test"
  144. self.hs.config.server_notices_mxid_display_name = None
  145. self.hs.config.server_notices_mxid_avatar_url = None
  146. self.hs.config.server_notices_room_name = "Test Server Notice Room"
  147. self.user_id = "@user_id:test"
  148. self.hs.config.admin_contact = "mailto:user@test.com"
  149. def test_server_notice_only_sent_once(self):
  150. self.store.get_monthly_active_count = Mock(return_value=1000)
  151. self.store.user_last_seen_monthly_active = Mock(return_value=1000)
  152. # Call the function multiple times to ensure we only send the notice once
  153. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  154. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  155. self.get_success(self._rlsn.maybe_send_server_notice_to_user(self.user_id))
  156. # Now lets get the last load of messages in the service notice room and
  157. # check that there is only one server notice
  158. room_id = self.get_success(
  159. self.server_notices_manager.get_notice_room_for_user(self.user_id)
  160. )
  161. token = self.get_success(self.event_source.get_current_token())
  162. events, _ = self.get_success(
  163. self.store.get_recent_events_for_room(
  164. room_id, limit=100, end_token=token.room_key
  165. )
  166. )
  167. count = 0
  168. for event in events:
  169. if event.type != EventTypes.Message:
  170. continue
  171. if event.content.get("msgtype") != ServerNoticeMsgType:
  172. continue
  173. count += 1
  174. self.assertEqual(count, 1)