test_servlet.py 4.5 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 test_disconnect
  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. result1 = parse_json_value_from_request(make_request(obj))
  45. self.assertEqual(result1, obj)
  46. # Results don't have to be objects.
  47. result2 = parse_json_value_from_request(make_request(b'["foo"]'))
  48. self.assertEqual(result2, ["foo"])
  49. # Test empty.
  50. with self.assertRaises(SynapseError):
  51. parse_json_value_from_request(make_request(b""))
  52. result3 = parse_json_value_from_request(
  53. make_request(b""), allow_empty_body=True
  54. )
  55. self.assertIsNone(result3)
  56. # Invalid UTF-8.
  57. with self.assertRaises(SynapseError):
  58. parse_json_value_from_request(make_request(b"\xFF\x00"))
  59. # Invalid JSON.
  60. with self.assertRaises(SynapseError):
  61. parse_json_value_from_request(make_request(b"foo"))
  62. with self.assertRaises(SynapseError):
  63. parse_json_value_from_request(make_request(b'{"foo": Infinity}'))
  64. def test_parse_json_object(self):
  65. """Basic tests for parse_json_object_from_request."""
  66. # Test empty.
  67. result = parse_json_object_from_request(
  68. make_request(b""), allow_empty_body=True
  69. )
  70. self.assertEqual(result, {})
  71. # Test not an object
  72. with self.assertRaises(SynapseError):
  73. parse_json_object_from_request(make_request(b'["foo"]'))
  74. class CancellableRestServlet(RestServlet):
  75. """A `RestServlet` with a mix of cancellable and uncancellable handlers."""
  76. PATTERNS = client_patterns("/sleep$")
  77. def __init__(self, hs: HomeServer):
  78. super().__init__()
  79. self.clock = hs.get_clock()
  80. @cancellable
  81. async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  82. await self.clock.sleep(1.0)
  83. return HTTPStatus.OK, {"result": True}
  84. async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  85. await self.clock.sleep(1.0)
  86. return HTTPStatus.OK, {"result": True}
  87. class TestRestServletCancellation(unittest.HomeserverTestCase):
  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. 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. test_disconnect(
  105. self.reactor,
  106. channel,
  107. expect_cancellation=False,
  108. expected_body={"result": True},
  109. )