test_preview.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. # Copyright 2014-2016 OpenMarket 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 synapse.rest.media.v1.preview_url_resource import (
  15. decode_and_calc_og,
  16. get_html_media_encoding,
  17. summarize_paragraphs,
  18. )
  19. from . import unittest
  20. try:
  21. import lxml
  22. except ImportError:
  23. lxml = None
  24. class SummarizeTestCase(unittest.TestCase):
  25. if not lxml:
  26. skip = "url preview feature requires lxml"
  27. def test_long_summarize(self):
  28. example_paras = [
  29. """Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:
  30. Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in
  31. Troms county, Norway. The administrative centre of the municipality is
  32. the city of Tromsø. Outside of Norway, Tromso and Tromsö are
  33. alternative spellings of the city.Tromsø is considered the northernmost
  34. city in the world with a population above 50,000. The most populous town
  35. north of it is Alta, Norway, with a population of 14,272 (2013).""",
  36. """Tromsø lies in Northern Norway. The municipality has a population of
  37. (2015) 72,066, but with an annual influx of students it has over 75,000
  38. most of the year. It is the largest urban area in Northern Norway and the
  39. third largest north of the Arctic Circle (following Murmansk and Norilsk).
  40. Most of Tromsø, including the city centre, is located on the island of
  41. Tromsøya, 350 kilometres (217 mi) north of the Arctic Circle. In 2012,
  42. Tromsøya had a population of 36,088. Substantial parts of the urban area
  43. are also situated on the mainland to the east, and on parts of Kvaløya—a
  44. large island to the west. Tromsøya is connected to the mainland by the Tromsø
  45. Bridge and the Tromsøysund Tunnel, and to the island of Kvaløya by the
  46. Sandnessund Bridge. Tromsø Airport connects the city to many destinations
  47. in Europe. The city is warmer than most other places located on the same
  48. latitude, due to the warming effect of the Gulf Stream.""",
  49. """The city centre of Tromsø contains the highest number of old wooden
  50. houses in Northern Norway, the oldest house dating from 1789. The Arctic
  51. Cathedral, a modern church from 1965, is probably the most famous landmark
  52. in Tromsø. The city is a cultural centre for its region, with several
  53. festivals taking place in the summer. Some of Norway's best-known
  54. musicians, Torbjørn Brundtland and Svein Berge of the electronica duo
  55. Röyksopp and Lene Marlin grew up and started their careers in Tromsø.
  56. Noted electronic musician Geir Jenssen also hails from Tromsø.""",
  57. ]
  58. desc = summarize_paragraphs(example_paras, min_size=200, max_size=500)
  59. self.assertEqual(
  60. desc,
  61. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  62. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  63. " Troms county, Norway. The administrative centre of the municipality is"
  64. " the city of Tromsø. Outside of Norway, Tromso and Tromsö are"
  65. " alternative spellings of the city.Tromsø is considered the northernmost"
  66. " city in the world with a population above 50,000. The most populous town"
  67. " north of it is Alta, Norway, with a population of 14,272 (2013).",
  68. )
  69. desc = summarize_paragraphs(example_paras[1:], min_size=200, max_size=500)
  70. self.assertEqual(
  71. desc,
  72. "Tromsø lies in Northern Norway. The municipality has a population of"
  73. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  74. " most of the year. It is the largest urban area in Northern Norway and the"
  75. " third largest north of the Arctic Circle (following Murmansk and Norilsk)."
  76. " Most of Tromsø, including the city centre, is located on the island of"
  77. " Tromsøya, 350 kilometres (217 mi) north of the Arctic Circle. In 2012,"
  78. " Tromsøya had a population of 36,088. Substantial parts of the urban…",
  79. )
  80. def test_short_summarize(self):
  81. example_paras = [
  82. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  83. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  84. " Troms county, Norway.",
  85. "Tromsø lies in Northern Norway. The municipality has a population of"
  86. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  87. " most of the year.",
  88. "The city centre of Tromsø contains the highest number of old wooden"
  89. " houses in Northern Norway, the oldest house dating from 1789. The Arctic"
  90. " Cathedral, a modern church from 1965, is probably the most famous landmark"
  91. " in Tromsø.",
  92. ]
  93. desc = summarize_paragraphs(example_paras, min_size=200, max_size=500)
  94. self.assertEqual(
  95. desc,
  96. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  97. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  98. " Troms county, Norway.\n"
  99. "\n"
  100. "Tromsø lies in Northern Norway. The municipality has a population of"
  101. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  102. " most of the year.",
  103. )
  104. def test_small_then_large_summarize(self):
  105. example_paras = [
  106. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  107. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  108. " Troms county, Norway.",
  109. "Tromsø lies in Northern Norway. The municipality has a population of"
  110. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  111. " most of the year."
  112. " The city centre of Tromsø contains the highest number of old wooden"
  113. " houses in Northern Norway, the oldest house dating from 1789. The Arctic"
  114. " Cathedral, a modern church from 1965, is probably the most famous landmark"
  115. " in Tromsø.",
  116. ]
  117. desc = summarize_paragraphs(example_paras, min_size=200, max_size=500)
  118. self.assertEqual(
  119. desc,
  120. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  121. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  122. " Troms county, Norway.\n"
  123. "\n"
  124. "Tromsø lies in Northern Norway. The municipality has a population of"
  125. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  126. " most of the year. The city centre of Tromsø contains the highest number"
  127. " of old wooden houses in Northern Norway, the oldest house dating from"
  128. " 1789. The Arctic Cathedral, a modern church from…",
  129. )
  130. class CalcOgTestCase(unittest.TestCase):
  131. if not lxml:
  132. skip = "url preview feature requires lxml"
  133. def test_simple(self):
  134. html = b"""
  135. <html>
  136. <head><title>Foo</title></head>
  137. <body>
  138. Some text.
  139. </body>
  140. </html>
  141. """
  142. og = decode_and_calc_og(html, "http://example.com/test.html")
  143. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  144. def test_comment(self):
  145. html = b"""
  146. <html>
  147. <head><title>Foo</title></head>
  148. <body>
  149. <!-- HTML comment -->
  150. Some text.
  151. </body>
  152. </html>
  153. """
  154. og = decode_and_calc_og(html, "http://example.com/test.html")
  155. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  156. def test_comment2(self):
  157. html = b"""
  158. <html>
  159. <head><title>Foo</title></head>
  160. <body>
  161. Some text.
  162. <!-- HTML comment -->
  163. Some more text.
  164. <p>Text</p>
  165. More text
  166. </body>
  167. </html>
  168. """
  169. og = decode_and_calc_og(html, "http://example.com/test.html")
  170. self.assertEqual(
  171. og,
  172. {
  173. "og:title": "Foo",
  174. "og:description": "Some text.\n\nSome more text.\n\nText\n\nMore text",
  175. },
  176. )
  177. def test_script(self):
  178. html = b"""
  179. <html>
  180. <head><title>Foo</title></head>
  181. <body>
  182. <script> (function() {})() </script>
  183. Some text.
  184. </body>
  185. </html>
  186. """
  187. og = decode_and_calc_og(html, "http://example.com/test.html")
  188. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  189. def test_missing_title(self):
  190. html = b"""
  191. <html>
  192. <body>
  193. Some text.
  194. </body>
  195. </html>
  196. """
  197. og = decode_and_calc_og(html, "http://example.com/test.html")
  198. self.assertEqual(og, {"og:title": None, "og:description": "Some text."})
  199. def test_h1_as_title(self):
  200. html = b"""
  201. <html>
  202. <meta property="og:description" content="Some text."/>
  203. <body>
  204. <h1>Title</h1>
  205. </body>
  206. </html>
  207. """
  208. og = decode_and_calc_og(html, "http://example.com/test.html")
  209. self.assertEqual(og, {"og:title": "Title", "og:description": "Some text."})
  210. def test_missing_title_and_broken_h1(self):
  211. html = b"""
  212. <html>
  213. <body>
  214. <h1><a href="foo"/></h1>
  215. Some text.
  216. </body>
  217. </html>
  218. """
  219. og = decode_and_calc_og(html, "http://example.com/test.html")
  220. self.assertEqual(og, {"og:title": None, "og:description": "Some text."})
  221. def test_empty(self):
  222. """Test a body with no data in it."""
  223. html = b""
  224. og = decode_and_calc_og(html, "http://example.com/test.html")
  225. self.assertEqual(og, {})
  226. def test_no_tree(self):
  227. """A valid body with no tree in it."""
  228. html = b"\x00"
  229. og = decode_and_calc_og(html, "http://example.com/test.html")
  230. self.assertEqual(og, {})
  231. def test_invalid_encoding(self):
  232. """An invalid character encoding should be ignored and treated as UTF-8, if possible."""
  233. html = b"""
  234. <html>
  235. <head><title>Foo</title></head>
  236. <body>
  237. Some text.
  238. </body>
  239. </html>
  240. """
  241. og = decode_and_calc_og(
  242. html, "http://example.com/test.html", "invalid-encoding"
  243. )
  244. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  245. def test_invalid_encoding2(self):
  246. """A body which doesn't match the sent character encoding."""
  247. # Note that this contains an invalid UTF-8 sequence in the title.
  248. html = b"""
  249. <html>
  250. <head><title>\xff\xff Foo</title></head>
  251. <body>
  252. Some text.
  253. </body>
  254. </html>
  255. """
  256. og = decode_and_calc_og(html, "http://example.com/test.html")
  257. self.assertEqual(og, {"og:title": "ÿÿ Foo", "og:description": "Some text."})
  258. class MediaEncodingTestCase(unittest.TestCase):
  259. def test_meta_charset(self):
  260. """A character encoding is found via the meta tag."""
  261. encoding = get_html_media_encoding(
  262. b"""
  263. <html>
  264. <head><meta charset="ascii">
  265. </head>
  266. </html>
  267. """,
  268. "text/html",
  269. )
  270. self.assertEqual(encoding, "ascii")
  271. # A less well-formed version.
  272. encoding = get_html_media_encoding(
  273. b"""
  274. <html>
  275. <head>< meta charset = ascii>
  276. </head>
  277. </html>
  278. """,
  279. "text/html",
  280. )
  281. self.assertEqual(encoding, "ascii")
  282. def test_xml_encoding(self):
  283. """A character encoding is found via the meta tag."""
  284. encoding = get_html_media_encoding(
  285. b"""
  286. <?xml version="1.0" encoding="ascii"?>
  287. <html>
  288. </html>
  289. """,
  290. "text/html",
  291. )
  292. self.assertEqual(encoding, "ascii")
  293. def test_meta_xml_encoding(self):
  294. """Meta tags take precedence over XML encoding."""
  295. encoding = get_html_media_encoding(
  296. b"""
  297. <?xml version="1.0" encoding="ascii"?>
  298. <html>
  299. <head><meta charset="UTF-16">
  300. </head>
  301. </html>
  302. """,
  303. "text/html",
  304. )
  305. self.assertEqual(encoding, "UTF-16")
  306. def test_content_type(self):
  307. """A character encoding is found via the Content-Type header."""
  308. # Test a few variations of the header.
  309. headers = (
  310. 'text/html; charset="ascii";',
  311. "text/html;charset=ascii;",
  312. 'text/html; charset="ascii"',
  313. "text/html; charset=ascii",
  314. 'text/html; charset="ascii;',
  315. 'text/html; charset=ascii";',
  316. )
  317. for header in headers:
  318. encoding = get_html_media_encoding(b"", header)
  319. self.assertEqual(encoding, "ascii")
  320. def test_fallback(self):
  321. """A character encoding cannot be found in the body or header."""
  322. encoding = get_html_media_encoding(b"", "text/html")
  323. self.assertEqual(encoding, "utf-8")