test_client.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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 List, Optional
  16. from unittest.mock import Mock
  17. import ijson.common
  18. from synapse.api.room_versions import RoomVersions
  19. from synapse.federation.transport.client import SendJoinParser
  20. from synapse.types import JsonDict
  21. from synapse.util import ExceptionBundle
  22. from tests.unittest import TestCase
  23. class SendJoinParserTestCase(TestCase):
  24. def test_two_writes(self) -> None:
  25. """Test that the parser can sensibly deserialise an input given in two slices."""
  26. parser = SendJoinParser(RoomVersions.V1, True)
  27. parent_event = {
  28. "content": {
  29. "see_room_version_spec": "The event format changes depending on the room version."
  30. },
  31. "event_id": "$authparent",
  32. "room_id": "!somewhere:example.org",
  33. "type": "m.room.minimal_pdu",
  34. }
  35. state = {
  36. "content": {
  37. "see_room_version_spec": "The event format changes depending on the room version."
  38. },
  39. "event_id": "$DoNotThinkAboutTheEvent",
  40. "room_id": "!somewhere:example.org",
  41. "type": "m.room.minimal_pdu",
  42. }
  43. response = [
  44. 200,
  45. {
  46. "auth_chain": [parent_event],
  47. "origin": "matrix.org",
  48. "state": [state],
  49. },
  50. ]
  51. serialised_response = json.dumps(response).encode()
  52. # Send data to the parser
  53. parser.write(serialised_response[:100])
  54. parser.write(serialised_response[100:])
  55. # Retrieve the parsed SendJoinResponse
  56. parsed_response = parser.finish()
  57. # Sanity check the parsing gave us sensible data.
  58. self.assertEqual(len(parsed_response.auth_events), 1, parsed_response)
  59. self.assertEqual(len(parsed_response.state), 1, parsed_response)
  60. self.assertEqual(parsed_response.event_dict, {}, parsed_response)
  61. self.assertIsNone(parsed_response.event, parsed_response)
  62. self.assertFalse(parsed_response.members_omitted, parsed_response)
  63. self.assertEqual(parsed_response.servers_in_room, None, parsed_response)
  64. def test_partial_state(self) -> None:
  65. """Check that the members_omitted flag is correctly parsed"""
  66. def parse(response: JsonDict) -> bool:
  67. parser = SendJoinParser(RoomVersions.V1, False)
  68. serialised_response = json.dumps(response).encode()
  69. # Send data to the parser
  70. parser.write(serialised_response)
  71. # Retrieve and check the parsed SendJoinResponse
  72. parsed_response = parser.finish()
  73. return parsed_response.members_omitted
  74. self.assertTrue(parse({"members_omitted": True}))
  75. self.assertTrue(parse({"org.matrix.msc3706.partial_state": True}))
  76. self.assertFalse(parse({"members_omitted": False}))
  77. self.assertFalse(parse({"org.matrix.msc3706.partial_state": False}))
  78. # If there's a conflict, the stable field wins.
  79. self.assertTrue(
  80. parse({"members_omitted": True, "org.matrix.msc3706.partial_state": False})
  81. )
  82. self.assertFalse(
  83. parse({"members_omitted": False, "org.matrix.msc3706.partial_state": True})
  84. )
  85. def test_servers_in_room(self) -> None:
  86. """Check that the servers_in_room field is correctly parsed"""
  87. def parse(response: JsonDict) -> Optional[List[str]]:
  88. parser = SendJoinParser(RoomVersions.V1, False)
  89. serialised_response = json.dumps(response).encode()
  90. # Send data to the parser
  91. parser.write(serialised_response)
  92. # Retrieve and check the parsed SendJoinResponse
  93. parsed_response = parser.finish()
  94. return parsed_response.servers_in_room
  95. self.assertEqual(
  96. parse({"org.matrix.msc3706.servers_in_room": ["hs1", "hs2"]}),
  97. ["hs1", "hs2"],
  98. )
  99. self.assertEqual(parse({"servers_in_room": ["example.com"]}), ["example.com"])
  100. # If both are provided, the stable identifier should win
  101. self.assertEqual(
  102. parse(
  103. {
  104. "org.matrix.msc3706.servers_in_room": ["old"],
  105. "servers_in_room": ["new"],
  106. }
  107. ),
  108. ["new"],
  109. )
  110. # And lastly, we should be able to tell if neither field was present.
  111. self.assertEqual(
  112. parse({}),
  113. None,
  114. )
  115. def test_errors_closing_coroutines(self) -> None:
  116. """Check we close all coroutines, even if closing the first raises an Exception.
  117. We also check that an Exception of some kind is raised, but we don't make any
  118. assertions about its attributes or type.
  119. """
  120. parser = SendJoinParser(RoomVersions.V1, False)
  121. response = {"org.matrix.msc3706.servers_in_room": ["hs1", "hs2"]}
  122. serialisation = json.dumps(response).encode()
  123. # Mock the coroutines managed by this parser.
  124. # The first one will error when we try to close it.
  125. coro_1 = Mock()
  126. coro_1.close = Mock(side_effect=RuntimeError("Couldn't close coro 1"))
  127. coro_2 = Mock()
  128. coro_3 = Mock()
  129. coro_3.close = Mock(side_effect=RuntimeError("Couldn't close coro 3"))
  130. original_coros = parser._coros
  131. parser._coros = [coro_1, coro_2, coro_3]
  132. # Close the original coroutines. If we don't, when we garbage collect them
  133. # they will throw, failing the test. (Oddly, this only started in CPython 3.11).
  134. for coro in original_coros:
  135. try:
  136. coro.close()
  137. except ijson.common.IncompleteJSONError:
  138. pass
  139. # Send half of the data to the parser
  140. parser.write(serialisation[: len(serialisation) // 2])
  141. # Close the parser. There should be _some_ kind of exception.
  142. with self.assertRaises(ExceptionBundle):
  143. parser.finish()
  144. # In any case, we should have tried to close both coros.
  145. coro_1.close.assert_called()
  146. coro_2.close.assert_called()
  147. coro_3.close.assert_called()