test_oembed.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright 2021 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 twisted.test.proto_helpers import MemoryReactor
  16. from synapse.rest.media.v1.oembed import OEmbedProvider, OEmbedResult
  17. from synapse.server import HomeServer
  18. from synapse.types import JsonDict
  19. from synapse.util import Clock
  20. from tests.unittest import HomeserverTestCase
  21. class OEmbedTests(HomeserverTestCase):
  22. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  23. self.oembed = OEmbedProvider(hs)
  24. def parse_response(self, response: JsonDict) -> OEmbedResult:
  25. return self.oembed.parse_oembed_response(
  26. "https://test", json.dumps(response).encode("utf-8")
  27. )
  28. def test_version(self) -> None:
  29. """Accept versions that are similar to 1.0 as a string or int (or missing)."""
  30. for version in ("1.0", 1.0, 1):
  31. result = self.parse_response({"version": version, "type": "link"})
  32. # An empty Open Graph response is an error, ensure the URL is included.
  33. self.assertIn("og:url", result.open_graph_result)
  34. # A missing version should be treated as 1.0.
  35. result = self.parse_response({"type": "link"})
  36. self.assertIn("og:url", result.open_graph_result)
  37. # Invalid versions should be rejected.
  38. for version in ("2.0", "1", 1.1, 0, None, {}, []):
  39. result = self.parse_response({"version": version, "type": "link"})
  40. # An empty Open Graph response is an error, ensure the URL is included.
  41. self.assertEqual({}, result.open_graph_result)