test_servlet.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 io import BytesIO
  16. from unittest.mock import Mock
  17. from synapse.api.errors import SynapseError
  18. from synapse.http.servlet import (
  19. parse_json_object_from_request,
  20. parse_json_value_from_request,
  21. )
  22. from tests import unittest
  23. def make_request(content):
  24. """Make an object that acts enough like a request."""
  25. request = Mock(spec=["content"])
  26. if isinstance(content, dict):
  27. content = json.dumps(content).encode("utf8")
  28. request.content = BytesIO(content)
  29. return request
  30. class TestServletUtils(unittest.TestCase):
  31. def test_parse_json_value(self):
  32. """Basic tests for parse_json_value_from_request."""
  33. # Test round-tripping.
  34. obj = {"foo": 1}
  35. result = parse_json_value_from_request(make_request(obj))
  36. self.assertEqual(result, obj)
  37. # Results don't have to be objects.
  38. result = parse_json_value_from_request(make_request(b'["foo"]'))
  39. self.assertEqual(result, ["foo"])
  40. # Test empty.
  41. with self.assertRaises(SynapseError):
  42. parse_json_value_from_request(make_request(b""))
  43. result = parse_json_value_from_request(make_request(b""), allow_empty_body=True)
  44. self.assertIsNone(result)
  45. # Invalid UTF-8.
  46. with self.assertRaises(SynapseError):
  47. parse_json_value_from_request(make_request(b"\xFF\x00"))
  48. # Invalid JSON.
  49. with self.assertRaises(SynapseError):
  50. parse_json_value_from_request(make_request(b"foo"))
  51. with self.assertRaises(SynapseError):
  52. parse_json_value_from_request(make_request(b'{"foo": Infinity}'))
  53. def test_parse_json_object(self):
  54. """Basic tests for parse_json_object_from_request."""
  55. # Test empty.
  56. result = parse_json_object_from_request(
  57. make_request(b""), allow_empty_body=True
  58. )
  59. self.assertEqual(result, {})
  60. # Test not an object
  61. with self.assertRaises(SynapseError):
  62. parse_json_object_from_request(make_request(b'["foo"]'))