test_client.py 5.3 KB

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