impl.py 16 KB

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