1
0

test_servlet.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. from io import BytesIO
  17. from mock import Mock
  18. from synapse.api.errors import SynapseError
  19. from synapse.http.servlet import (
  20. parse_json_object_from_request,
  21. parse_json_value_from_request,
  22. )
  23. from tests import unittest
  24. def make_request(content):
  25. """Make an object that acts enough like a request."""
  26. request = Mock(spec=["content"])
  27. if isinstance(content, dict):
  28. content = json.dumps(content).encode("utf8")
  29. request.content = BytesIO(content)
  30. return request
  31. class TestServletUtils(unittest.TestCase):
  32. def test_parse_json_value(self):
  33. """Basic tests for parse_json_value_from_request."""
  34. # Test round-tripping.
  35. obj = {"foo": 1}
  36. result = parse_json_value_from_request(make_request(obj))
  37. self.assertEqual(result, obj)
  38. # Results don't have to be objects.
  39. result = parse_json_value_from_request(make_request(b'["foo"]'))
  40. self.assertEqual(result, ["foo"])
  41. # Test empty.
  42. with self.assertRaises(SynapseError):
  43. parse_json_value_from_request(make_request(b""))
  44. result = parse_json_value_from_request(make_request(b""), allow_empty_body=True)
  45. self.assertIsNone(result)
  46. # Invalid UTF-8.
  47. with self.assertRaises(SynapseError):
  48. parse_json_value_from_request(make_request(b"\xFF\x00"))
  49. # Invalid JSON.
  50. with self.assertRaises(SynapseError):
  51. parse_json_value_from_request(make_request(b"foo"))
  52. with self.assertRaises(SynapseError):
  53. parse_json_value_from_request(make_request(b'{"foo": Infinity}'))
  54. def test_parse_json_object(self):
  55. """Basic tests for parse_json_object_from_request."""
  56. # Test empty.
  57. result = parse_json_object_from_request(
  58. make_request(b""), allow_empty_body=True
  59. )
  60. self.assertEqual(result, {})
  61. # Test not an object
  62. with self.assertRaises(SynapseError):
  63. parse_json_object_from_request(make_request(b'["foo"]'))