_base.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # Copyright 2022 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. # Unles4s 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. from http import HTTPStatus
  15. from typing import Any, Callable, Optional, Union
  16. from unittest import mock
  17. from twisted.internet.error import ConnectionDone
  18. from synapse.http.server import (
  19. HTTP_STATUS_REQUEST_CANCELLED,
  20. respond_with_html_bytes,
  21. respond_with_json,
  22. )
  23. from synapse.types import JsonDict
  24. from tests import unittest
  25. from tests.server import FakeChannel, ThreadedMemoryReactorClock
  26. class EndpointCancellationTestHelperMixin(unittest.TestCase):
  27. """Provides helper methods for testing cancellation of endpoints."""
  28. def _test_disconnect(
  29. self,
  30. reactor: ThreadedMemoryReactorClock,
  31. channel: FakeChannel,
  32. expect_cancellation: bool,
  33. expected_body: Union[bytes, JsonDict],
  34. expected_code: Optional[int] = None,
  35. ) -> None:
  36. """Disconnects an in-flight request and checks the response.
  37. Args:
  38. reactor: The twisted reactor running the request handler.
  39. channel: The `FakeChannel` for the request.
  40. expect_cancellation: `True` if request processing is expected to be
  41. cancelled, `False` if the request should run to completion.
  42. expected_body: The expected response for the request.
  43. expected_code: The expected status code for the request. Defaults to `200`
  44. or `499` depending on `expect_cancellation`.
  45. """
  46. # Determine the expected status code.
  47. if expected_code is None:
  48. if expect_cancellation:
  49. expected_code = HTTP_STATUS_REQUEST_CANCELLED
  50. else:
  51. expected_code = HTTPStatus.OK
  52. request = channel.request
  53. self.assertFalse(
  54. channel.is_finished(),
  55. "Request finished before we could disconnect - "
  56. "was `await_result=False` passed to `make_request`?",
  57. )
  58. # We're about to disconnect the request. This also disconnects the channel, so
  59. # we have to rely on mocks to extract the response.
  60. respond_method: Callable[..., Any]
  61. if isinstance(expected_body, bytes):
  62. respond_method = respond_with_html_bytes
  63. else:
  64. respond_method = respond_with_json
  65. with mock.patch(
  66. f"synapse.http.server.{respond_method.__name__}", wraps=respond_method
  67. ) as respond_mock:
  68. # Disconnect the request.
  69. request.connectionLost(reason=ConnectionDone())
  70. if expect_cancellation:
  71. # An immediate cancellation is expected.
  72. respond_mock.assert_called_once()
  73. args, _kwargs = respond_mock.call_args
  74. code, body = args[1], args[2]
  75. self.assertEqual(code, expected_code)
  76. self.assertEqual(request.code, expected_code)
  77. self.assertEqual(body, expected_body)
  78. else:
  79. respond_mock.assert_not_called()
  80. # The handler is expected to run to completion.
  81. reactor.pump([1.0])
  82. respond_mock.assert_called_once()
  83. args, _kwargs = respond_mock.call_args
  84. code, body = args[1], args[2]
  85. self.assertEqual(code, expected_code)
  86. self.assertEqual(request.code, expected_code)
  87. self.assertEqual(body, expected_body)