impl.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. import typing
  3. import types
  4. import functools
  5. import itertools
  6. from time import time
  7. from urllib.parse import urlparse
  8. import re
  9. import cld3
  10. import requests.exceptions
  11. from searx import poolrequests, logger
  12. from searx.results import ResultContainer
  13. from searx.search.models import SearchQuery, EngineRef
  14. from searx.search.processors import EngineProcessor
  15. logger = logger.getChild('searx.search.checker')
  16. HTML_TAGS = [
  17. 'embed', 'iframe', 'object', 'param', 'picture', 'source', 'svg', 'math', 'canvas', 'noscript', 'script',
  18. 'del', 'ins', 'area', 'audio', 'img', 'map', 'track', 'video', 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite',
  19. 'code', 'data', 'dfn', 'em', 'i', 'kdb', 'mark', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'small',
  20. 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr', 'style', 'blockquote', 'dd', 'div', 'dl', 'dt',
  21. 'figcaption', 'figure', 'hr', 'li', 'ol', 'p', 'pre', 'ul', 'button', 'datalist', 'fieldset', 'form', 'input',
  22. 'label', 'legend', 'meter', 'optgroup', 'option', 'output', 'progress', 'select', 'textarea', 'applet',
  23. 'frame', 'frameset'
  24. ]
  25. def get_check_no_html():
  26. rep = ['<' + tag + '[^\>]*>' for tag in HTML_TAGS]
  27. rep += ['</' + tag + '>' for tag in HTML_TAGS]
  28. pattern = re.compile('|'.join(rep))
  29. def f(text):
  30. return pattern.search(text.lower()) is None
  31. return f
  32. _check_no_html = get_check_no_html()
  33. def _is_url(url):
  34. try:
  35. result = urlparse(url)
  36. except ValueError:
  37. return False
  38. if result.scheme not in ('http', 'https'):
  39. return False
  40. return True
  41. @functools.lru_cache(maxsize=8192)
  42. def _is_url_image(image_url):
  43. if not isinstance(image_url, str):
  44. return False
  45. if image_url.startswith('//'):
  46. image_url = 'https:' + image_url
  47. if image_url.startswith('data:'):
  48. return image_url.startswith('data:image/')
  49. if not _is_url(image_url):
  50. return False
  51. retry = 2
  52. while retry > 0:
  53. a = time()
  54. try:
  55. poolrequests.set_timeout_for_thread(10.0, time())
  56. r = poolrequests.get(image_url, timeout=10.0, allow_redirects=True, headers={
  57. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
  58. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  59. 'Accept-Language': 'en-US;q=0.5,en;q=0.3',
  60. 'Accept-Encoding': 'gzip, deflate, br',
  61. 'DNT': '1',
  62. 'Connection': 'keep-alive',
  63. 'Upgrade-Insecure-Requests': '1',
  64. 'Sec-GPC': '1',
  65. 'Cache-Control': 'max-age=0'
  66. })
  67. if r.headers["content-type"].startswith('image/'):
  68. return True
  69. return False
  70. except requests.exceptions.Timeout:
  71. logger.error('Timeout for %s: %i', image_url, int(time() - a))
  72. retry -= 1
  73. except requests.exceptions.RequestException:
  74. logger.exception('Exception for %s', image_url)
  75. return False
  76. def _search_query_to_dict(search_query: SearchQuery) -> typing.Dict[str, typing.Any]:
  77. return {
  78. 'query': search_query.query,
  79. 'lang': search_query.lang,
  80. 'pageno': search_query.pageno,
  81. 'safesearch': search_query.safesearch,
  82. 'time_range': search_query.time_range,
  83. }
  84. def _search_query_diff(sq1: SearchQuery, sq2: SearchQuery)\
  85. -> typing.Tuple[typing.Dict[str, typing.Any], typing.Dict[str, typing.Any]]:
  86. param1 = _search_query_to_dict(sq1)
  87. param2 = _search_query_to_dict(sq2)
  88. common = {}
  89. diff = {}
  90. for k, value1 in param1.items():
  91. value2 = param2[k]
  92. if value1 == value2:
  93. common[k] = value1
  94. else:
  95. diff[k] = (value1, value2)
  96. return (common, diff)
  97. class TestResults:
  98. __slots__ = 'errors', 'logs', 'languages'
  99. def __init__(self):
  100. self.errors: typing.Dict[str, typing.List[str]] = {}
  101. self.logs: typing.Dict[str, typing.List[typing.Any]] = {}
  102. self.languages: typing.Set[str] = set()
  103. def add_error(self, test, message, *args):
  104. # message to self.errors
  105. errors_for_test = self.errors.setdefault(test, [])
  106. if message not in errors_for_test:
  107. errors_for_test.append(message)
  108. # (message, *args) to self.logs
  109. logs_for_test = self.logs.setdefault(test, [])
  110. if (message, *args) not in logs_for_test:
  111. logs_for_test.append((message, *args))
  112. def add_language(self, language):
  113. self.languages.add(language)
  114. @property
  115. def succesfull(self):
  116. return len(self.errors) == 0
  117. def __iter__(self):
  118. for test_name, errors in self.errors.items():
  119. for error in sorted(errors):
  120. yield (test_name, error)
  121. class ResultContainerTests:
  122. __slots__ = 'test_name', 'search_query', 'result_container', 'languages', 'stop_test', 'test_results'
  123. def __init__(self,
  124. test_results: TestResults,
  125. test_name: str,
  126. search_query: SearchQuery,
  127. result_container: ResultContainer):
  128. self.test_name = test_name
  129. self.search_query = search_query
  130. self.result_container = result_container
  131. self.languages: typing.Set[str] = set()
  132. self.test_results = test_results
  133. self.stop_test = False
  134. @property
  135. def result_urls(self):
  136. results = self.result_container.get_ordered_results()
  137. return [result['url'] for result in results]
  138. def _record_error(self, message: str, *args) -> None:
  139. sq = _search_query_to_dict(self.search_query)
  140. sqstr = ' '.join(['{}={!r}'.format(k, v) for k, v in sq.items()])
  141. self.test_results.add_error(self.test_name, message, *args, '(' + sqstr + ')')
  142. def _add_language(self, text: str) -> typing.Optional[str]:
  143. r = cld3.get_language(str(text)) # pylint: disable=E1101
  144. if r is not None and r.probability >= 0.98 and r.is_reliable:
  145. self.languages.add(r.language)
  146. self.test_results.add_language(r.language)
  147. return None
  148. def _check_result(self, result):
  149. if not _check_no_html(result.get('title', '')):
  150. self._record_error('HTML in title', repr(result.get('title', '')))
  151. if not _check_no_html(result.get('content', '')):
  152. self._record_error('HTML in content', repr(result.get('content', '')))
  153. self._add_language(result.get('title', ''))
  154. self._add_language(result.get('content', ''))
  155. template = result.get('template', 'default.html')
  156. if template == 'default.html':
  157. return
  158. if template == 'code.html':
  159. return
  160. if template == 'torrent.html':
  161. return
  162. if template == 'map.html':
  163. return
  164. if template == 'images.html':
  165. thumbnail_src = result.get('thumbnail_src')
  166. if thumbnail_src is not None:
  167. if not _is_url_image(thumbnail_src):
  168. self._record_error('thumbnail_src URL is invalid', thumbnail_src)
  169. elif not _is_url_image(result.get('img_src')):
  170. self._record_error('img_src URL is invalid', result.get('img_src'))
  171. if template == 'videos.html' and not _is_url_image(result.get('thumbnail')):
  172. self._record_error('thumbnail URL is invalid', result.get('img_src'))
  173. def _check_results(self, results: list):
  174. for result in results:
  175. self._check_result(result)
  176. def _check_answers(self, answers):
  177. for answer in answers:
  178. if not _check_no_html(answer):
  179. self._record_error('HTML in answer', answer)
  180. def _check_infoboxes(self, infoboxes):
  181. for infobox in infoboxes:
  182. if not _check_no_html(infobox.get('content', '')):
  183. self._record_error('HTML in infobox content', infobox.get('content', ''))
  184. self._add_language(infobox.get('content', ''))
  185. for attribute in infobox.get('attributes', {}):
  186. if not _check_no_html(attribute.get('value', '')):
  187. self._record_error('HTML in infobox attribute value', attribute.get('value', ''))
  188. def check_basic(self):
  189. if len(self.result_container.unresponsive_engines) > 0:
  190. for message in self.result_container.unresponsive_engines:
  191. self._record_error(message[1] + ' ' + (message[2] or ''))
  192. self.stop_test = True
  193. return
  194. results = self.result_container.get_ordered_results()
  195. if len(results) > 0:
  196. self._check_results(results)
  197. if len(self.result_container.answers) > 0:
  198. self._check_answers(self.result_container.answers)
  199. if len(self.result_container.infoboxes) > 0:
  200. self._check_infoboxes(self.result_container.infoboxes)
  201. def has_infobox(self):
  202. """Check the ResultContainer has at least one infobox"""
  203. if len(self.result_container.infoboxes) == 0:
  204. self._record_error('No infobox')
  205. def has_answer(self):
  206. """Check the ResultContainer has at least one answer"""
  207. if len(self.result_container.answers) == 0:
  208. self._record_error('No answer')
  209. def has_language(self, lang):
  210. """Check at least one title or content of the results is written in the `lang`.
  211. Detected using pycld3, may be not accurate"""
  212. if lang not in self.languages:
  213. self._record_error(lang + ' not found')
  214. def not_empty(self):
  215. """Check the ResultContainer has at least one answer or infobox or result"""
  216. result_types = set()
  217. results = self.result_container.get_ordered_results()
  218. if len(results) > 0:
  219. result_types.add('results')
  220. if len(self.result_container.answers) > 0:
  221. result_types.add('answers')
  222. if len(self.result_container.infoboxes) > 0:
  223. result_types.add('infoboxes')
  224. if len(result_types) == 0:
  225. self._record_error('No result')
  226. def one_title_contains(self, title: str):
  227. """Check one of the title contains `title` (case insensitive comparaison)"""
  228. title = title.lower()
  229. for result in self.result_container.get_ordered_results():
  230. if title in result['title'].lower():
  231. return
  232. self._record_error(('{!r} not found in the title'.format(title)))
  233. class CheckerTests:
  234. __slots__ = 'test_results', 'test_name', 'result_container_tests_list'
  235. def __init__(self,
  236. test_results: TestResults,
  237. test_name: str,
  238. result_container_tests_list: typing.List[ResultContainerTests]):
  239. self.test_results = test_results
  240. self.test_name = test_name
  241. self.result_container_tests_list = result_container_tests_list
  242. def unique_results(self):
  243. """Check the results of each ResultContain is unique"""
  244. urls_list = [rct.result_urls for rct in self.result_container_tests_list]
  245. if len(urls_list[0]) > 0:
  246. # results on the first page
  247. for i, urls_i in enumerate(urls_list):
  248. for j, urls_j in enumerate(urls_list):
  249. if i < j and urls_i == urls_j:
  250. common, diff = _search_query_diff(self.result_container_tests_list[i].search_query,
  251. self.result_container_tests_list[j].search_query)
  252. common_str = ' '.join(['{}={!r}'.format(k, v) for k, v in common.items()])
  253. diff1_str = ', ' .join(['{}={!r}'.format(k, v1) for (k, (v1, v2)) in diff.items()])
  254. diff2_str = ', ' .join(['{}={!r}'.format(k, v2) for (k, (v1, v2)) in diff.items()])
  255. self.test_results.add_error(self.test_name,
  256. 'results are identitical for {} and {} ({})'
  257. .format(diff1_str, diff2_str, common_str))
  258. class Checker:
  259. __slots__ = 'processor', 'tests', 'test_results'
  260. def __init__(self, processor: EngineProcessor):
  261. self.processor = processor
  262. self.tests = self.processor.get_tests()
  263. self.test_results = TestResults()
  264. @property
  265. def engineref_list(self):
  266. engine_name = self.processor.engine_name
  267. engine_category = self.processor.engine.categories[0]
  268. return [EngineRef(engine_name, engine_category)]
  269. @staticmethod
  270. def search_query_matrix_iterator(engineref_list, matrix):
  271. p = []
  272. for name, values in matrix.items():
  273. if isinstance(values, (tuple, list)):
  274. l = [(name, value) for value in values]
  275. else:
  276. l = [(name, values)]
  277. p.append(l)
  278. for kwargs in itertools.product(*p):
  279. kwargs = {k: v for k, v in kwargs}
  280. query = kwargs['query']
  281. params = dict(kwargs)
  282. del params['query']
  283. yield SearchQuery(query, engineref_list, **params)
  284. def call_test(self, obj, test_description):
  285. if isinstance(test_description, (tuple, list)):
  286. method, args = test_description[0], test_description[1:]
  287. else:
  288. method = test_description
  289. args = ()
  290. if isinstance(method, str) and hasattr(obj, method):
  291. getattr(obj, method)(*args)
  292. elif isinstance(method, types.FunctionType):
  293. method(*args)
  294. else:
  295. self.test_results.add_error(obj.test_name,
  296. 'method {!r} ({}) not found for {}'
  297. .format(method, method.__class__.__name__, obj.__class__.__name__))
  298. def call_tests(self, obj, test_descriptions):
  299. for test_description in test_descriptions:
  300. self.call_test(obj, test_description)
  301. def search(self, search_query: SearchQuery) -> ResultContainer:
  302. result_container = ResultContainer()
  303. engineref_category = search_query.engineref_list[0].category
  304. params = self.processor.get_params(search_query, engineref_category)
  305. if params is not None:
  306. self.processor.search(search_query.query, params, result_container, time(), 5)
  307. return result_container
  308. def get_result_container_tests(self, test_name: str, search_query: SearchQuery) -> ResultContainerTests:
  309. result_container = self.search(search_query)
  310. result_container_check = ResultContainerTests(self.test_results, test_name, search_query, result_container)
  311. result_container_check.check_basic()
  312. return result_container_check
  313. def run_test(self, test_name):
  314. test_parameters = self.tests[test_name]
  315. search_query_list = list(Checker.search_query_matrix_iterator(self.engineref_list, test_parameters['matrix']))
  316. rct_list = [self.get_result_container_tests(test_name, search_query) for search_query in search_query_list]
  317. stop_test = False
  318. if 'result_container' in test_parameters:
  319. for rct in rct_list:
  320. stop_test = stop_test or rct.stop_test
  321. if not rct.stop_test:
  322. self.call_tests(rct, test_parameters['result_container'])
  323. if not stop_test:
  324. if 'test' in test_parameters:
  325. checker_tests = CheckerTests(self.test_results, test_name, rct_list)
  326. self.call_tests(checker_tests, test_parameters['test'])
  327. def run(self):
  328. for test_name in self.tests:
  329. self.run_test(test_name)