test_utils.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # -*- coding: utf-8 -*-
  2. import lxml.etree
  3. from lxml import html
  4. from searx.testing import SearxTestCase
  5. from searx.exceptions import SearxXPathSyntaxException, SearxEngineXPathException
  6. from searx import utils
  7. class TestUtils(SearxTestCase):
  8. def test_gen_useragent(self):
  9. self.assertIsInstance(utils.gen_useragent(), str)
  10. self.assertIsNotNone(utils.gen_useragent())
  11. self.assertTrue(utils.gen_useragent().startswith('Mozilla'))
  12. def test_searx_useragent(self):
  13. self.assertIsInstance(utils.searx_useragent(), str)
  14. self.assertIsNotNone(utils.searx_useragent())
  15. self.assertTrue(utils.searx_useragent().startswith('searx'))
  16. def test_html_to_text(self):
  17. html_str = """
  18. <a href="/testlink" class="link_access_account">
  19. <style>
  20. .toto {
  21. color: red;
  22. }
  23. </style>
  24. <span class="toto">
  25. <span>
  26. <img src="test.jpg" />
  27. </span>
  28. </span>
  29. <span class="titi">
  30. Test text
  31. </span>
  32. <script>value='dummy';</script>
  33. </a>
  34. """
  35. self.assertIsInstance(utils.html_to_text(html_str), str)
  36. self.assertIsNotNone(utils.html_to_text(html_str))
  37. self.assertEqual(utils.html_to_text(html_str), "Test text")
  38. def test_extract_text(self):
  39. html_str = """
  40. <a href="/testlink" class="link_access_account">
  41. <span class="toto">
  42. <span>
  43. <img src="test.jpg" />
  44. </span>
  45. </span>
  46. <span class="titi">
  47. Test text
  48. </span>
  49. </a>
  50. """
  51. dom = html.fromstring(html_str)
  52. self.assertEqual(utils.extract_text(dom), 'Test text')
  53. self.assertEqual(utils.extract_text(dom.xpath('//span')), 'Test text')
  54. self.assertEqual(utils.extract_text(dom.xpath('//span/text()')), 'Test text')
  55. self.assertEqual(utils.extract_text(dom.xpath('count(//span)')), '3.0')
  56. self.assertEqual(utils.extract_text(dom.xpath('boolean(//span)')), 'True')
  57. self.assertEqual(utils.extract_text(dom.xpath('//img/@src')), 'test.jpg')
  58. self.assertEqual(utils.extract_text(dom.xpath('//unexistingtag')), '')
  59. self.assertEqual(utils.extract_text(None, allow_none=True), None)
  60. with self.assertRaises(ValueError):
  61. utils.extract_text(None)
  62. with self.assertRaises(ValueError):
  63. utils.extract_text({})
  64. def test_extract_url(self):
  65. def f(html_str, search_url):
  66. return utils.extract_url(html.fromstring(html_str), search_url)
  67. self.assertEqual(f('<span id="42">https://example.com</span>', 'http://example.com/'), 'https://example.com/')
  68. self.assertEqual(f('https://example.com', 'http://example.com/'), 'https://example.com/')
  69. self.assertEqual(f('//example.com', 'http://example.com/'), 'http://example.com/')
  70. self.assertEqual(f('//example.com', 'https://example.com/'), 'https://example.com/')
  71. self.assertEqual(f('/path?a=1', 'https://example.com'), 'https://example.com/path?a=1')
  72. with self.assertRaises(lxml.etree.ParserError):
  73. f('', 'https://example.com')
  74. with self.assertRaises(Exception):
  75. utils.extract_url([], 'https://example.com')
  76. def test_html_to_text_invalid(self):
  77. html = '<p><b>Lorem ipsum</i>dolor sit amet</p>'
  78. self.assertEqual(utils.html_to_text(html), "Lorem ipsum")
  79. def test_match_language(self):
  80. self.assertEqual(utils.match_language('es', ['es']), 'es')
  81. self.assertEqual(utils.match_language('es', [], fallback='fallback'), 'fallback')
  82. self.assertEqual(utils.match_language('ja', ['jp'], {'ja': 'jp'}), 'jp')
  83. aliases = {'en-GB': 'en-UK', 'he': 'iw'}
  84. # guess country
  85. self.assertEqual(utils.match_language('de-DE', ['de']), 'de')
  86. self.assertEqual(utils.match_language('de', ['de-DE']), 'de-DE')
  87. self.assertEqual(utils.match_language('es-CO', ['es-AR', 'es-ES', 'es-MX']), 'es-ES')
  88. self.assertEqual(utils.match_language('es-CO', ['es-MX']), 'es-MX')
  89. self.assertEqual(utils.match_language('en-UK', ['en-AU', 'en-GB', 'en-US']), 'en-GB')
  90. self.assertEqual(utils.match_language('en-GB', ['en-AU', 'en-UK', 'en-US'], aliases), 'en-UK')
  91. # language aliases
  92. self.assertEqual(utils.match_language('iw', ['he']), 'he')
  93. self.assertEqual(utils.match_language('he', ['iw'], aliases), 'iw')
  94. self.assertEqual(utils.match_language('iw-IL', ['he']), 'he')
  95. self.assertEqual(utils.match_language('he-IL', ['iw'], aliases), 'iw')
  96. self.assertEqual(utils.match_language('iw', ['he-IL']), 'he-IL')
  97. self.assertEqual(utils.match_language('he', ['iw-IL'], aliases), 'iw-IL')
  98. self.assertEqual(utils.match_language('iw-IL', ['he-IL']), 'he-IL')
  99. self.assertEqual(utils.match_language('he-IL', ['iw-IL'], aliases), 'iw-IL')
  100. def test_ecma_unscape(self):
  101. self.assertEqual(utils.ecma_unescape('text%20with%20space'), 'text with space')
  102. self.assertEqual(utils.ecma_unescape('text using %xx: %F3'),
  103. 'text using %xx: ó')
  104. self.assertEqual(utils.ecma_unescape('text using %u: %u5409, %u4E16%u754c'),
  105. 'text using %u: 吉, 世界')
  106. class TestHTMLTextExtractor(SearxTestCase):
  107. def setUp(self):
  108. self.html_text_extractor = utils.HTMLTextExtractor()
  109. def test__init__(self):
  110. self.assertEqual(self.html_text_extractor.result, [])
  111. def test_handle_charref(self):
  112. self.html_text_extractor.handle_charref('xF')
  113. self.assertIn('\x0f', self.html_text_extractor.result)
  114. self.html_text_extractor.handle_charref('XF')
  115. self.assertIn('\x0f', self.html_text_extractor.result)
  116. self.html_text_extractor.handle_charref('97')
  117. self.assertIn('a', self.html_text_extractor.result)
  118. def test_handle_entityref(self):
  119. entity = 'test'
  120. self.html_text_extractor.handle_entityref(entity)
  121. self.assertIn(entity, self.html_text_extractor.result)
  122. def test_invalid_html(self):
  123. text = '<p><b>Lorem ipsum</i>dolor sit amet</p>'
  124. with self.assertRaises(utils.HTMLTextExtractorException):
  125. self.html_text_extractor.feed(text)
  126. class TestXPathUtils(SearxTestCase):
  127. TEST_DOC = """<ul>
  128. <li>Text in <b>bold</b> and <i>italic</i> </li>
  129. <li>Another <b>text</b> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="></li>
  130. </ul>"""
  131. def test_get_xpath_cache(self):
  132. xp1 = utils.get_xpath('//a')
  133. xp2 = utils.get_xpath('//div')
  134. xp3 = utils.get_xpath('//a')
  135. self.assertEqual(id(xp1), id(xp3))
  136. self.assertNotEqual(id(xp1), id(xp2))
  137. def test_get_xpath_type(self):
  138. utils.get_xpath(lxml.etree.XPath('//a'))
  139. with self.assertRaises(TypeError):
  140. utils.get_xpath([])
  141. def test_get_xpath_invalid(self):
  142. invalid_xpath = '//a[0].text'
  143. with self.assertRaises(SearxXPathSyntaxException) as context:
  144. utils.get_xpath(invalid_xpath)
  145. self.assertEqual(context.exception.message, 'Invalid expression')
  146. self.assertEqual(context.exception.xpath_str, invalid_xpath)
  147. def test_eval_xpath_unregistered_function(self):
  148. doc = html.fromstring(TestXPathUtils.TEST_DOC)
  149. invalid_function_xpath = 'int(//a)'
  150. with self.assertRaises(SearxEngineXPathException) as context:
  151. utils.eval_xpath(doc, invalid_function_xpath)
  152. self.assertEqual(context.exception.message, 'Unregistered function')
  153. self.assertEqual(context.exception.xpath_str, invalid_function_xpath)
  154. def test_eval_xpath(self):
  155. doc = html.fromstring(TestXPathUtils.TEST_DOC)
  156. self.assertEqual(utils.eval_xpath(doc, '//p'), [])
  157. self.assertEqual(utils.eval_xpath(doc, '//i/text()'), ['italic'])
  158. self.assertEqual(utils.eval_xpath(doc, 'count(//i)'), 1.0)
  159. def test_eval_xpath_list(self):
  160. doc = html.fromstring(TestXPathUtils.TEST_DOC)
  161. # check a not empty list
  162. self.assertEqual(utils.eval_xpath_list(doc, '//i/text()'), ['italic'])
  163. # check min_len parameter
  164. with self.assertRaises(SearxEngineXPathException) as context:
  165. utils.eval_xpath_list(doc, '//p', min_len=1)
  166. self.assertEqual(context.exception.message, 'len(xpath_str) < 1')
  167. self.assertEqual(context.exception.xpath_str, '//p')
  168. def test_eval_xpath_getindex(self):
  169. doc = html.fromstring(TestXPathUtils.TEST_DOC)
  170. # check index 0
  171. self.assertEqual(utils.eval_xpath_getindex(doc, '//i/text()', 0), 'italic')
  172. # default is 'something'
  173. self.assertEqual(utils.eval_xpath_getindex(doc, '//i/text()', 1, default='something'), 'something')
  174. # default is None
  175. self.assertEqual(utils.eval_xpath_getindex(doc, '//i/text()', 1, default=None), None)
  176. # index not found
  177. with self.assertRaises(SearxEngineXPathException) as context:
  178. utils.eval_xpath_getindex(doc, '//i/text()', 1)
  179. self.assertEqual(context.exception.message, 'index 1 not found')
  180. # not a list
  181. with self.assertRaises(SearxEngineXPathException) as context:
  182. utils.eval_xpath_getindex(doc, 'count(//i)', 1)
  183. self.assertEqual(context.exception.message, 'the result is not a list')