test_preview.py 17 KB

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