test_howdoi.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #!/usr/bin/env python
  2. """Tests for Howdoi."""
  3. import gzip
  4. import json
  5. import os
  6. import re
  7. import unittest
  8. from pathlib import Path
  9. from unittest.mock import patch
  10. import requests
  11. from cachelib import NullCache
  12. from pyquery import PyQuery as pq
  13. # pylint: disable=no-name-in-module
  14. from howdoi import howdoi
  15. # pylint: disable=protected-access
  16. original_get_result = howdoi._get_result
  17. def _get_result_mock(url):
  18. # pylint: disable=protected-access
  19. file_name = howdoi._format_url_to_filename(url, 'html.gz')
  20. # pylint: disable=no-member
  21. file_path = Path.joinpath(Path(howdoi.HTML_CACHE_PATH), Path(file_name)).resolve()
  22. try:
  23. with gzip.open(file_path, 'rb') as f:
  24. cached_page_content = str(f.read(), encoding='utf-8')
  25. return cached_page_content
  26. except FileNotFoundError:
  27. page_content = original_get_result(url)
  28. with gzip.open(file_path, 'wb') as f:
  29. f.write(bytes(page_content, encoding='utf-8'))
  30. return page_content
  31. # pylint: disable=protected-access
  32. class HowdoiTestCase(unittest.TestCase): # pylint: disable=too-many-public-methods
  33. def setUp(self):
  34. self.patcher_get_result = patch.object(howdoi, '_get_result')
  35. self.mock_get_result = self.patcher_get_result.start()
  36. self.mock_get_result.side_effect = _get_result_mock
  37. # ensure no cache is used during testing.
  38. howdoi.cache = NullCache()
  39. self.queries = ['format date bash',
  40. 'print stack trace python',
  41. 'convert mp4 to animated gif',
  42. 'create tar archive',
  43. 'cat']
  44. self.help_queries = howdoi.SUPPORTED_HELP_QUERIES
  45. self.pt_queries = ['abrir arquivo em python',
  46. 'enviar email em django',
  47. 'hello world em c']
  48. self.bad_queries = ['moe',
  49. 'mel']
  50. self.query_without_code_or_pre_block = 'Difference between element node and Text Node'
  51. def tearDown(self):
  52. self.patcher_get_result.stop()
  53. keys_to_remove = ['HOWDOI_URL', 'HOWDOI_SEARCH_ENGINE']
  54. for key in keys_to_remove:
  55. if key in os.environ:
  56. del os.environ[key]
  57. howdoi.BLOCKED_ENGINES = []
  58. def _negative_number_query(self):
  59. query = self.queries[0]
  60. howdoi.howdoi(query + ' -n -1')
  61. def _high_positive_number_query(self):
  62. query = self.queries[0]
  63. howdoi.howdoi(query + ' -n 21')
  64. def _negative_position_query(self):
  65. query = self.queries[0]
  66. howdoi.howdoi(query + ' -p -2')
  67. def _high_positive_position_query(self):
  68. query = self.queries[0]
  69. howdoi.howdoi(query + ' -p 40')
  70. def assertValidResponse(self, res): # pylint: disable=invalid-name
  71. self.assertTrue(len(res) > 0)
  72. def test_get_link_at_pos(self):
  73. self.assertEqual(howdoi.get_link_at_pos(['/questions/42/'], 1),
  74. '/questions/42/')
  75. self.assertEqual(howdoi.get_link_at_pos(['/questions/42/'], 2),
  76. '/questions/42/')
  77. self.assertEqual(howdoi.get_link_at_pos(['/howdoi', '/questions/42/'], 1),
  78. '/howdoi')
  79. self.assertEqual(howdoi.get_link_at_pos(['/howdoi', '/questions/42/'], 2),
  80. '/questions/42/')
  81. self.assertEqual(howdoi.get_link_at_pos(['/questions/42/', '/questions/142/'], 1),
  82. '/questions/42/')
  83. @patch.object(howdoi, '_get_result')
  84. def test_blockerror(self, mock_get_links):
  85. mock_get_links.side_effect = requests.HTTPError
  86. query = self.queries[0]
  87. response = howdoi.howdoi(query)
  88. self.assertEqual(response, "ERROR: \x1b[91mUnable to get a response from any search engine\n\x1b[0m")
  89. def test_answers(self):
  90. for query in self.queries:
  91. self.assertValidResponse(howdoi.howdoi(query))
  92. for query in self.bad_queries:
  93. self.assertValidResponse(howdoi.howdoi(query))
  94. os.environ['HOWDOI_URL'] = 'pt.stackoverflow.com'
  95. for query in self.pt_queries:
  96. self.assertValidResponse(howdoi.howdoi(query))
  97. def test_answers_bing(self):
  98. os.environ['HOWDOI_SEARCH_ENGINE'] = 'bing'
  99. for query in self.queries:
  100. self.assertValidResponse(howdoi.howdoi(query))
  101. for query in self.bad_queries:
  102. self.assertValidResponse(howdoi.howdoi(query))
  103. os.environ['HOWDOI_URL'] = 'pt.stackoverflow.com'
  104. for query in self.pt_queries:
  105. self.assertValidResponse(howdoi.howdoi(query))
  106. os.environ['HOWDOI_SEARCH_ENGINE'] = ''
  107. # commenting out duckduckgo test, re-enable when issue #404 (duckduckgo blocking requests) is resolved
  108. # def test_answers_duckduckgo(self):
  109. # os.environ['HOWDOI_SEARCH_ENGINE'] = 'duckduckgo'
  110. # for query in self.queries:
  111. # self.assertValidResponse(howdoi.howdoi(query))
  112. # for query in self.bad_queries:
  113. # self.assertValidResponse(howdoi.howdoi(query))
  114. # os.environ['HOWDOI_URL'] = 'pt.stackoverflow.com'
  115. # for query in self.pt_queries:
  116. # self.assertValidResponse(howdoi.howdoi(query))
  117. # os.environ['HOWDOI_SEARCH_ENGINE'] = ''
  118. def test_answer_links_using_l_option(self):
  119. for query in self.queries:
  120. response = howdoi.howdoi(query + ' -l')
  121. self.assertNotEqual(re.match(r'http.?://.*questions/\d.*', response, re.DOTALL), None)
  122. def test_answer_links_using_all_option(self):
  123. for query in self.queries:
  124. response = howdoi.howdoi(query + ' -a')
  125. self.assertNotEqual(re.match(r'.*http.?://.*questions/\d.*', response, re.DOTALL), None)
  126. def test_position(self):
  127. query = self.queries[0]
  128. first_answer = howdoi.howdoi(query)
  129. not_first_answer = howdoi.howdoi(query + ' -p5')
  130. self.assertNotEqual(first_answer, not_first_answer)
  131. def test_all_text(self):
  132. query = self.queries[0]
  133. first_answer = howdoi.howdoi(query)
  134. second_answer = howdoi.howdoi(query + ' -a')
  135. self.assertNotEqual(first_answer, second_answer)
  136. self.assertNotEqual(re.match('.*Answer from http.?://.*', second_answer, re.DOTALL), None)
  137. def test_json_output(self):
  138. query = self.queries[0]
  139. txt_answer = howdoi.howdoi(query)
  140. json_answer = howdoi.howdoi(query + ' -j')
  141. link_answer = howdoi.howdoi(query + ' -l')
  142. json_answer = json.loads(json_answer)[0]
  143. self.assertEqual(json_answer["answer"], txt_answer)
  144. self.assertEqual(json_answer["link"], link_answer)
  145. self.assertEqual(json_answer["position"], 1)
  146. def test_multiple_answers(self):
  147. query = self.queries[0]
  148. first_answer = howdoi.howdoi(query)
  149. second_answer = howdoi.howdoi(query + ' -n3')
  150. self.assertNotEqual(first_answer, second_answer)
  151. def test_unicode_answer(self): # pylint: disable=no-self-use
  152. assert howdoi.howdoi('make a log scale d3')
  153. assert howdoi.howdoi('python unittest -n3')
  154. assert howdoi.howdoi('parse html regex -a')
  155. assert howdoi.howdoi('delete remote git branch -a')
  156. def test_colorize(self):
  157. query = self.queries[0]
  158. normal = howdoi.howdoi(query)
  159. colorized = howdoi.howdoi('-c ' + query)
  160. self.assertTrue(normal.find('[38;') == -1)
  161. self.assertTrue(colorized.find('[38;') != -1)
  162. # pylint: disable=line-too-long
  163. def test_get_text_without_links(self):
  164. html = '''\n <p>The halting problem is basically a\n formal way of asking if you can tell\n whether or not an arbitrary program\n will eventually halt.</p>\n \n <p>In other words, can you write a\n program called a halting oracle,\n HaltingOracle(program, input), which\n returns true if program(input) would\n eventually halt, and which returns\n false if it wouldn't?</p>\n \n <p>The answer is: no, you can't.</p>\n''' # noqa: E501
  165. paragraph = pq(html)
  166. expected_output = '''The halting problem is basically a\n formal way of asking if you can tell\n whether or not an arbitrary program\n will eventually halt.\n\n \n \nIn other words, can you write a\n program called a halting oracle,\n HaltingOracle(program, input), which\n returns true if program(input) would\n eventually halt, and which returns\n false if it wouldn't?\n\n \n \nThe answer is: no, you can't.\n\n''' # noqa: E501
  167. actual_output = howdoi.get_text(paragraph)
  168. self.assertEqual(actual_output, expected_output)
  169. def test_get_text_with_one_link(self):
  170. html = '<p>It\'s a <a href="http://paulirish.com/2010/the-protocol-relative-url/">protocol-relative URL</a> (typically HTTP or HTTPS). So if I\'m on <code>http://example.org</code> and I link (or include an image, script, etc.) to <code>//example.com/1.png</code>, it goes to <code>http://example.com/1.png</code>. If I\'m on <code>https://example.org</code>, it goes to <code>https://example.com/1.png</code>.</p>' # noqa: E501
  171. paragraph = pq(html)
  172. expected_output = "It's a [protocol-relative URL](http://paulirish.com/2010/the-protocol-relative-url/) (typically HTTP or HTTPS). So if I'm on http://example.org and I link (or include an image, script, etc.) to //example.com/1.png, it goes to http://example.com/1.png. If I'm on https://example.org, it goes to https://example.com/1.png." # noqa: E501
  173. actual_output = howdoi.get_text(paragraph)
  174. self.assertEqual(actual_output, expected_output)
  175. def test_get_text_with_multiple_links_test_one(self):
  176. html = 'Here\'s a quote from <a href="http://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style#Links" rel="nofollow noreferrer">wikipedia\'s manual of style</a> section on links (but see also <a href="http://en.wikipedia.org/wiki/Wikipedia:External_links" rel="nofollow noreferrer">their comprehensive page on External Links</a>)' # noqa: E501
  177. paragraph = pq(html)
  178. expected_output = "Here's a quote from [wikipedia's manual of style](http://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style#Links) section on links (but see also [their comprehensive page on External Links](http://en.wikipedia.org/wiki/Wikipedia:External_links))" # noqa: E501
  179. actual_output = howdoi.get_text(paragraph)
  180. self.assertEqual(actual_output, expected_output)
  181. def test_get_text_with_multiple_links_test_two(self):
  182. html = 'For example, if I were to reference <a href="http://www.apple.com/" rel="nofollow noreferrer">apple.com</a> as the subject of a sentence - or to talk about <a href="http://www.apple.com/" rel="nofollow noreferrer">Apple\'s website</a> as the topic of conversation. This being different to perhaps recommendations for reading <a href="https://ux.stackexchange.com/q/14872/6046">our article about Apple\'s website</a>.' # noqa: E501
  183. paragraph = pq(html)
  184. expected_output = "For example, if I were to reference [apple.com](http://www.apple.com/) as the subject of a sentence - or to talk about [Apple's website](http://www.apple.com/) as the topic of conversation. This being different to perhaps recommendations for reading [our article about Apple's website](https://ux.stackexchange.com/q/14872/6046)." # noqa: E501
  185. actual_output = howdoi.get_text(paragraph)
  186. self.assertEqual(actual_output, expected_output)
  187. def test_get_text_with_link_but_with_copy_duplicating_the_href(self):
  188. html = '<a href="https://github.com/jquery/jquery/blob/56136897f241db22560b58c3518578ca1453d5c7/src/manipulation.js#L451" rel="nofollow noreferrer">https://github.com/jquery/jquery/blob/56136897f241db22560b58c3518578ca1453d5c7/src/manipulation.js#L451</a>' # noqa: E501
  189. paragraph = pq(html)
  190. expected_output = 'https://github.com/jquery/jquery/blob/56136897f241db22560b58c3518578ca1453d5c7/src/manipulation.js#L451' # noqa: E501
  191. actual_output = howdoi.get_text(paragraph)
  192. self.assertEqual(actual_output, expected_output)
  193. def test_get_text_with_a_link_but_copy_is_within_nested_div(self):
  194. html = 'If the function is from a source file available on the filesystem, then <a href="https://docs.python.org/3/library/inspect.html#inspect.getsource" rel="noreferrer"><code>inspect.getsource(foo)</code></a> might be of help:' # noqa: E501
  195. paragraph = pq(html)
  196. expected_output = 'If the function is from a source file available on the filesystem, then [inspect.getsource(foo)](https://docs.python.org/3/library/inspect.html#inspect.getsource) might be of help:' # noqa: E501
  197. actual_output = howdoi.get_text(paragraph)
  198. self.assertEqual(actual_output, expected_output)
  199. # pylint: enable=line-too-long
  200. def test_get_questions(self):
  201. links = ['https://stackoverflow.com/questions/tagged/cat',
  202. 'http://rads.stackoverflow.com/amzn/click/B007KAZ166',
  203. 'https://stackoverflow.com/questions/40108569/how-to-get-the-last-line-of-a-file-using-cat-command']
  204. expected_output = [
  205. 'https://stackoverflow.com/questions/40108569/how-to-get-the-last-line-of-a-file-using-cat-command']
  206. actual_output = howdoi._get_questions(links)
  207. self.assertSequenceEqual(actual_output, expected_output)
  208. def test_help_queries(self):
  209. help_queries = self.help_queries
  210. for query in help_queries:
  211. output = howdoi.howdoi(query)
  212. self.assertTrue(output)
  213. self.assertIn('few popular howdoi commands', output)
  214. self.assertIn('retrieve n number of answers', output)
  215. self.assertIn(
  216. 'Specify the search engine you want to use e.g google,bing',
  217. output
  218. )
  219. def test_missing_pre_or_code_query(self):
  220. output = howdoi.howdoi(self.query_without_code_or_pre_block)
  221. self.assertTrue(output)
  222. self.assertIn('XML elements present in a XML', output)
  223. def test_format_url_to_filename(self):
  224. url = 'https://stackoverflow.com/questions/tagged/cat'
  225. invalid_filename_characters = ['/', '\\', '%']
  226. filename = howdoi._format_url_to_filename(url, 'html')
  227. self.assertTrue(filename)
  228. self.assertTrue(filename.endswith('html'))
  229. for invalid_character in invalid_filename_characters:
  230. self.assertNotIn(invalid_character, filename)
  231. def test_help_queries_are_properly_validated(self):
  232. help_queries = self.help_queries
  233. for query in help_queries:
  234. is_valid_help_query = howdoi._is_help_query(query)
  235. self.assertTrue(is_valid_help_query)
  236. bad_help_queries = [self.queries[0],
  237. self.bad_queries[0], 'use how do i']
  238. for query in bad_help_queries:
  239. self.assertFalse(howdoi._is_help_query(query))
  240. def test_negative_and_high_positive_int_values_rejected(self):
  241. with self.assertRaises(SystemExit):
  242. self._negative_number_query()
  243. with self.assertRaises(SystemExit):
  244. self._negative_position_query()
  245. with self.assertRaises(SystemExit):
  246. self._high_positive_position_query()
  247. with self.assertRaises(SystemExit):
  248. self._high_positive_number_query()
  249. class HowdoiTestCaseEnvProxies(unittest.TestCase):
  250. def setUp(self):
  251. self.temp_get_proxies = howdoi.getproxies
  252. def tearDown(self):
  253. howdoi.getproxies = self.temp_get_proxies
  254. def test_get_proxies1(self):
  255. def getproxies1():
  256. proxies = {'http': 'wwwproxy.company.com',
  257. 'https': 'wwwproxy.company.com',
  258. 'ftp': 'ftpproxy.company.com'}
  259. return proxies
  260. howdoi.getproxies = getproxies1
  261. filtered_proxies = howdoi.get_proxies()
  262. self.assertTrue('http://' in filtered_proxies['http'])
  263. self.assertTrue('http://' in filtered_proxies['https'])
  264. self.assertTrue('ftp' not in filtered_proxies.keys())
  265. if __name__ == '__main__':
  266. unittest.main()