test_servlet.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # Copyright 2020 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 http import HTTPStatus
  16. from io import BytesIO
  17. from typing import Tuple
  18. from unittest.mock import Mock
  19. from synapse.api.errors import Codes, SynapseError
  20. from synapse.http.server import cancellable
  21. from synapse.http.servlet import (
  22. RestServlet,
  23. parse_json_object_from_request,
  24. parse_json_value_from_request,
  25. )
  26. from synapse.http.site import SynapseRequest
  27. from synapse.rest.client._base import client_patterns
  28. from synapse.server import HomeServer
  29. from synapse.types import JsonDict
  30. from tests import unittest
  31. from tests.http.server._base import EndpointCancellationTestHelperMixin
  32. def make_request(content):
  33. """Make an object that acts enough like a request."""
  34. request = Mock(spec=["content"])
  35. if isinstance(content, dict):
  36. content = json.dumps(content).encode("utf8")
  37. request.content = BytesIO(content)
  38. return request
  39. class TestServletUtils(unittest.TestCase):
  40. def test_parse_json_value(self):
  41. """Basic tests for parse_json_value_from_request."""
  42. # Test round-tripping.
  43. obj = {"foo": 1}
  44. result = parse_json_value_from_request(make_request(obj))
  45. self.assertEqual(result, obj)
  46. # Results don't have to be objects.
  47. result = parse_json_value_from_request(make_request(b'["foo"]'))
  48. self.assertEqual(result, ["foo"])
  49. # Test empty.
  50. with self.assertRaises(SynapseError):
  51. parse_json_value_from_request(make_request(b""))
  52. result = parse_json_value_from_request(make_request(b""), allow_empty_body=True)
  53. self.assertIsNone(result)
  54. # Invalid UTF-8.
  55. with self.assertRaises(SynapseError):
  56. parse_json_value_from_request(make_request(b"\xFF\x00"))
  57. # Invalid JSON.
  58. with self.assertRaises(SynapseError):
  59. parse_json_value_from_request(make_request(b"foo"))
  60. with self.assertRaises(SynapseError):
  61. parse_json_value_from_request(make_request(b'{"foo": Infinity}'))
  62. def test_parse_json_object(self):
  63. """Basic tests for parse_json_object_from_request."""
  64. # Test empty.
  65. result = parse_json_object_from_request(
  66. make_request(b""), allow_empty_body=True
  67. )
  68. self.assertEqual(result, {})
  69. # Test not an object
  70. with self.assertRaises(SynapseError):
  71. parse_json_object_from_request(make_request(b'["foo"]'))
  72. class CancellableRestServlet(RestServlet):
  73. """A `RestServlet` with a mix of cancellable and uncancellable handlers."""
  74. PATTERNS = client_patterns("/sleep$")
  75. def __init__(self, hs: HomeServer):
  76. super().__init__()
  77. self.clock = hs.get_clock()
  78. @cancellable
  79. async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  80. await self.clock.sleep(1.0)
  81. return HTTPStatus.OK, {"result": True}
  82. async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  83. await self.clock.sleep(1.0)
  84. return HTTPStatus.OK, {"result": True}
  85. class TestRestServletCancellation(
  86. unittest.HomeserverTestCase, EndpointCancellationTestHelperMixin
  87. ):
  88. """Tests for `RestServlet` cancellation."""
  89. servlets = [
  90. lambda hs, http_server: CancellableRestServlet(hs).register(http_server)
  91. ]
  92. def test_cancellable_disconnect(self) -> None:
  93. """Test that handlers with the `@cancellable` flag can be cancelled."""
  94. channel = self.make_request("GET", "/sleep", await_result=False)
  95. self._test_disconnect(
  96. self.reactor,
  97. channel,
  98. expect_cancellation=True,
  99. expected_body={"error": "Request cancelled", "errcode": Codes.UNKNOWN},
  100. )
  101. def test_uncancellable_disconnect(self) -> None:
  102. """Test that handlers without the `@cancellable` flag cannot be cancelled."""
  103. channel = self.make_request("POST", "/sleep", await_result=False)
  104. self._test_disconnect(
  105. self.reactor,
  106. channel,
  107. expect_cancellation=False,
  108. expected_body={"result": True},
  109. )