test_additional_resource.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright 2018 New Vector Ltd
  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. from typing import Any
  15. from twisted.web.server import Request
  16. from synapse.http.additional_resource import AdditionalResource
  17. from synapse.http.server import respond_with_json
  18. from synapse.http.site import SynapseRequest
  19. from synapse.types import JsonDict
  20. from tests.server import FakeSite, make_request
  21. from tests.unittest import HomeserverTestCase
  22. class _AsyncTestCustomEndpoint:
  23. def __init__(self, config: JsonDict, module_api: Any) -> None:
  24. pass
  25. async def handle_request(self, request: Request) -> None:
  26. assert isinstance(request, SynapseRequest)
  27. respond_with_json(request, 200, {"some_key": "some_value_async"})
  28. class _SyncTestCustomEndpoint:
  29. def __init__(self, config: JsonDict, module_api: Any) -> None:
  30. pass
  31. async def handle_request(self, request: Request) -> None:
  32. assert isinstance(request, SynapseRequest)
  33. respond_with_json(request, 200, {"some_key": "some_value_sync"})
  34. class AdditionalResourceTests(HomeserverTestCase):
  35. """Very basic tests that `AdditionalResource` works correctly with sync
  36. and async handlers.
  37. """
  38. def test_async(self) -> None:
  39. handler = _AsyncTestCustomEndpoint({}, None).handle_request
  40. resource = AdditionalResource(self.hs, handler)
  41. channel = make_request(
  42. self.reactor, FakeSite(resource, self.reactor), "GET", "/"
  43. )
  44. self.assertEqual(channel.code, 200)
  45. self.assertEqual(channel.json_body, {"some_key": "some_value_async"})
  46. def test_sync(self) -> None:
  47. handler = _SyncTestCustomEndpoint({}, None).handle_request
  48. resource = AdditionalResource(self.hs, handler)
  49. channel = make_request(
  50. self.reactor, FakeSite(resource, self.reactor), "GET", "/"
  51. )
  52. self.assertEqual(channel.code, 200)
  53. self.assertEqual(channel.json_body, {"some_key": "some_value_sync"})