test_client.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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.assertFalse(parse({"members_omitted": False}))
  76. def test_servers_in_room(self) -> None:
  77. """Check that the servers_in_room field is correctly parsed"""
  78. def parse(response: JsonDict) -> Optional[List[str]]:
  79. parser = SendJoinParser(RoomVersions.V1, False)
  80. serialised_response = json.dumps(response).encode()
  81. # Send data to the parser
  82. parser.write(serialised_response)
  83. # Retrieve and check the parsed SendJoinResponse
  84. parsed_response = parser.finish()
  85. return parsed_response.servers_in_room
  86. self.assertEqual(parse({"servers_in_room": ["example.com"]}), ["example.com"])
  87. # We should be able to tell the field is not present.
  88. self.assertEqual(parse({}), None)
  89. def test_errors_closing_coroutines(self) -> None:
  90. """Check we close all coroutines, even if closing the first raises an Exception.
  91. We also check that an Exception of some kind is raised, but we don't make any
  92. assertions about its attributes or type.
  93. """
  94. parser = SendJoinParser(RoomVersions.V1, False)
  95. response = {"servers_in_room": ["hs1", "hs2"]}
  96. serialisation = json.dumps(response).encode()
  97. # Mock the coroutines managed by this parser.
  98. # The first one will error when we try to close it.
  99. coro_1 = Mock()
  100. coro_1.close = Mock(side_effect=RuntimeError("Couldn't close coro 1"))
  101. coro_2 = Mock()
  102. coro_3 = Mock()
  103. coro_3.close = Mock(side_effect=RuntimeError("Couldn't close coro 3"))
  104. original_coros = parser._coros
  105. parser._coros = [coro_1, coro_2, coro_3]
  106. # Close the original coroutines. If we don't, when we garbage collect them
  107. # they will throw, failing the test. (Oddly, this only started in CPython 3.11).
  108. for coro in original_coros:
  109. try:
  110. coro.close()
  111. except ijson.common.IncompleteJSONError:
  112. pass
  113. # Send half of the data to the parser
  114. parser.write(serialisation[: len(serialisation) // 2])
  115. # Close the parser. There should be _some_ kind of exception.
  116. with self.assertRaises(ExceptionBundle):
  117. parser.finish()
  118. # In any case, we should have tried to close both coros.
  119. coro_1.close.assert_called()
  120. coro_2.close.assert_called()
  121. coro_3.close.assert_called()