test_howdoi.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 cachelib import NullCache
  10. from pyquery import PyQuery as pq
  11. # pylint: disable=no-name-in-module
  12. from howdoi import howdoi
  13. # pylint: disable=protected-access
  14. class HowdoiTestCase(unittest.TestCase): # pylint: disable=too-many-public-methods
  15. def _get_result_mock(self, url):
  16. file_name = howdoi._format_url_to_filename(url, 'html.gz')
  17. # pylint: disable=no-member
  18. file_path = Path.joinpath(Path(howdoi.HTML_CACHE_PATH), Path(file_name)).resolve()
  19. try:
  20. with gzip.open(file_path, 'rb') as f:
  21. cached_page_content = str(f.read(), encoding='utf-8')
  22. return cached_page_content
  23. except FileNotFoundError:
  24. page_content = self.original_get_result(url)
  25. with gzip.open(file_path, 'wb') as f:
  26. f.write(bytes(page_content, encoding='utf-8'))
  27. return page_content
  28. def _negative_number_query(self):
  29. query = self.queries[0]
  30. howdoi.howdoi(query + ' -n -1')
  31. def _high_positive_number_query(self):
  32. query = self.queries[0]
  33. howdoi.howdoi(query + ' -n 21')
  34. def _negative_position_query(self):
  35. query = self.queries[0]
  36. howdoi.howdoi(query + ' -p -2')
  37. def _high_positive_position_query(self):
  38. query = self.queries[0]
  39. howdoi.howdoi(query + ' -p 40')
  40. def setUp(self):
  41. self.original_get_result = howdoi._get_result
  42. howdoi._get_result = self._get_result_mock
  43. # ensure no cache is used during testing.
  44. howdoi.cache = NullCache()
  45. self.queries = ['format date bash',
  46. 'print stack trace python',
  47. 'convert mp4 to animated gif',
  48. 'create tar archive',
  49. 'cat']
  50. self.help_queries = howdoi.SUPPORTED_HELP_QUERIES
  51. self.pt_queries = ['abrir arquivo em python',
  52. 'enviar email em django',
  53. 'hello world em c']
  54. self.bad_queries = ['moe',
  55. 'mel']
  56. self.query_without_code_or_pre_block = 'Difference between element node and Text Node'
  57. def assertValidResponse(self, res): # pylint: disable=invalid-name
  58. self.assertTrue(len(res) > 0)
  59. def tearDown(self):
  60. keys_to_remove = ['HOWDOI_URL', 'HOWDO_SEARCH_ENGINE']
  61. for key in keys_to_remove:
  62. if key in os.environ:
  63. del os.environ[key]
  64. def test_get_link_at_pos(self):
  65. self.assertEqual(howdoi.get_link_at_pos(['/questions/42/'], 1),
  66. '/questions/42/')
  67. self.assertEqual(howdoi.get_link_at_pos(['/questions/42/'], 2),
  68. '/questions/42/')
  69. self.assertEqual(howdoi.get_link_at_pos(['/howdoi', '/questions/42/'], 1),
  70. '/howdoi')
  71. self.assertEqual(howdoi.get_link_at_pos(['/howdoi', '/questions/42/'], 2),
  72. '/questions/42/')
  73. self.assertEqual(howdoi.get_link_at_pos(['/questions/42/', '/questions/142/'], 1),
  74. '/questions/42/')
  75. def test_answers(self):
  76. for query in self.queries:
  77. self.assertValidResponse(howdoi.howdoi(query))
  78. for query in self.bad_queries:
  79. self.assertValidResponse(howdoi.howdoi(query))
  80. os.environ['HOWDOI_URL'] = 'pt.stackoverflow.com'
  81. for query in self.pt_queries:
  82. self.assertValidResponse(howdoi.howdoi(query))
  83. def test_answers_bing(self):
  84. os.environ['HOWDOI_SEARCH_ENGINE'] = 'bing'
  85. for query in self.queries:
  86. self.assertValidResponse(howdoi.howdoi(query))
  87. for query in self.bad_queries:
  88. self.assertValidResponse(howdoi.howdoi(query))
  89. os.environ['HOWDOI_URL'] = 'pt.stackoverflow.com'
  90. for query in self.pt_queries:
  91. self.assertValidResponse(howdoi.howdoi(query))
  92. os.environ['HOWDOI_SEARCH_ENGINE'] = ''
  93. # commenting out duckduckgo test, re-enable when issue #404 (duckduckgo blocking requests) is resolved
  94. # def test_answers_duckduckgo(self):
  95. # os.environ['HOWDOI_SEARCH_ENGINE'] = 'duckduckgo'
  96. # for query in self.queries:
  97. # self.assertValidResponse(howdoi.howdoi(query))
  98. # for query in self.bad_queries:
  99. # self.assertValidResponse(howdoi.howdoi(query))
  100. # os.environ['HOWDOI_URL'] = 'pt.stackoverflow.com'
  101. # for query in self.pt_queries:
  102. # self.assertValidResponse(howdoi.howdoi(query))
  103. # os.environ['HOWDOI_SEARCH_ENGINE'] = ''
  104. def test_answer_links_using_l_option(self):
  105. for query in self.queries:
  106. response = howdoi.howdoi(query + ' -l')
  107. self.assertNotEqual(re.match(r'http.?://.*questions/\d.*', response, re.DOTALL), None)
  108. def test_answer_links_using_all_option(self):
  109. for query in self.queries:
  110. response = howdoi.howdoi(query + ' -a')
  111. self.assertNotEqual(re.match(r'.*http.?://.*questions/\d.*', response, re.DOTALL), None)
  112. def test_position(self):
  113. query = self.queries[0]
  114. first_answer = howdoi.howdoi(query)
  115. not_first_answer = howdoi.howdoi(query + ' -p5')
  116. self.assertNotEqual(first_answer, not_first_answer)
  117. def test_all_text(self):
  118. query = self.queries[0]
  119. first_answer = howdoi.howdoi(query)
  120. second_answer = howdoi.howdoi(query + ' -a')
  121. self.assertNotEqual(first_answer, second_answer)
  122. self.assertNotEqual(re.match('.*Answer from http.?://.*', second_answer, re.DOTALL), None)
  123. def test_json_output(self):
  124. query = self.queries[0]
  125. txt_answer = howdoi.howdoi(query)
  126. json_answer = howdoi.howdoi(query + ' -j')
  127. link_answer = howdoi.howdoi(query + ' -l')
  128. json_answer = json.loads(json_answer)[0]
  129. self.assertEqual(json_answer["answer"], txt_answer)
  130. self.assertEqual(json_answer["link"], link_answer)
  131. self.assertEqual(json_answer["position"], 1)
  132. def test_multiple_answers(self):
  133. query = self.queries[0]
  134. first_answer = howdoi.howdoi(query)
  135. second_answer = howdoi.howdoi(query + ' -n3')
  136. self.assertNotEqual(first_answer, second_answer)
  137. def test_unicode_answer(self): # pylint: disable=no-self-use
  138. assert howdoi.howdoi('make a log scale d3')
  139. assert howdoi.howdoi('python unittest -n3')
  140. assert howdoi.howdoi('parse html regex -a')
  141. assert howdoi.howdoi('delete remote git branch -a')
  142. def test_colorize(self):
  143. query = self.queries[0]
  144. normal = howdoi.howdoi(query)
  145. colorized = howdoi.howdoi('-c ' + query)
  146. self.assertTrue(normal.find('[39;') == -1)
  147. self.assertTrue(colorized.find('[39;') != -1)
  148. # pylint: disable=line-too-long
  149. def test_get_text_without_links(self):
  150. 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
  151. paragraph = pq(html)
  152. 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
  153. actual_output = howdoi.get_text(paragraph)
  154. self.assertEqual(actual_output, expected_output)
  155. def test_get_text_with_one_link(self):
  156. 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
  157. paragraph = pq(html)
  158. 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
  159. actual_output = howdoi.get_text(paragraph)
  160. self.assertEqual(actual_output, expected_output)
  161. def test_get_text_with_multiple_links_test_one(self):
  162. 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
  163. paragraph = pq(html)
  164. 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
  165. actual_output = howdoi.get_text(paragraph)
  166. self.assertEqual(actual_output, expected_output)
  167. def test_get_text_with_multiple_links_test_two(self):
  168. 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
  169. paragraph = pq(html)
  170. 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
  171. actual_output = howdoi.get_text(paragraph)
  172. self.assertEqual(actual_output, expected_output)
  173. def test_get_text_with_link_but_with_copy_duplicating_the_href(self):
  174. 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
  175. paragraph = pq(html)
  176. expected_output = 'https://github.com/jquery/jquery/blob/56136897f241db22560b58c3518578ca1453d5c7/src/manipulation.js#L451' # noqa: E501
  177. actual_output = howdoi.get_text(paragraph)
  178. self.assertEqual(actual_output, expected_output)
  179. def test_get_text_with_a_link_but_copy_is_within_nested_div(self):
  180. 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
  181. paragraph = pq(html)
  182. 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
  183. actual_output = howdoi.get_text(paragraph)
  184. self.assertEqual(actual_output, expected_output)
  185. # pylint: enable=line-too-long
  186. def test_get_questions(self):
  187. links = ['https://stackoverflow.com/questions/tagged/cat',
  188. 'http://rads.stackoverflow.com/amzn/click/B007KAZ166',
  189. 'https://stackoverflow.com/questions/40108569/how-to-get-the-last-line-of-a-file-using-cat-command']
  190. expected_output = [
  191. 'https://stackoverflow.com/questions/40108569/how-to-get-the-last-line-of-a-file-using-cat-command']
  192. actual_output = howdoi._get_questions(links)
  193. self.assertSequenceEqual(actual_output, expected_output)
  194. def test_help_queries(self):
  195. help_queries = self.help_queries
  196. for query in help_queries:
  197. output = howdoi.howdoi(query)
  198. self.assertTrue(output)
  199. self.assertIn('few popular howdoi commands', output)
  200. self.assertIn('retrieve n number of answers', output)
  201. self.assertIn(
  202. 'Specify the search engine you want to use e.g google,bing',
  203. output
  204. )
  205. def test_missing_pre_or_code_query(self):
  206. output = howdoi.howdoi(self.query_without_code_or_pre_block)
  207. self.assertTrue(output)
  208. self.assertIn('XML elements present in a XML', output)
  209. def test_format_url_to_filename(self):
  210. url = 'https://stackoverflow.com/questions/tagged/cat'
  211. invalid_filename_characters = ['/', '\\', '%']
  212. filename = howdoi._format_url_to_filename(url, 'html')
  213. self.assertTrue(filename)
  214. self.assertTrue(filename.endswith('html'))
  215. for invalid_character in invalid_filename_characters:
  216. self.assertNotIn(invalid_character, filename)
  217. def test_help_queries_are_properly_validated(self):
  218. help_queries = self.help_queries
  219. for query in help_queries:
  220. is_valid_help_query = howdoi._is_help_query(query)
  221. self.assertTrue(is_valid_help_query)
  222. bad_help_queries = [self.queries[0],
  223. self.bad_queries[0], 'use how do i']
  224. for query in bad_help_queries:
  225. self.assertFalse(howdoi._is_help_query(query))
  226. def test_negative_and_high_positive_int_values_rejected(self):
  227. with self.assertRaises(SystemExit):
  228. self._negative_number_query()
  229. with self.assertRaises(SystemExit):
  230. self._negative_position_query()
  231. with self.assertRaises(SystemExit):
  232. self._high_positive_position_query()
  233. with self.assertRaises(SystemExit):
  234. self._high_positive_number_query()
  235. class HowdoiTestCaseEnvProxies(unittest.TestCase):
  236. def setUp(self):
  237. self.temp_get_proxies = howdoi.getproxies
  238. def tearDown(self):
  239. howdoi.getproxies = self.temp_get_proxies
  240. def test_get_proxies1(self):
  241. def getproxies1():
  242. proxies = {'http': 'wwwproxy.company.com',
  243. 'https': 'wwwproxy.company.com',
  244. 'ftp': 'ftpproxy.company.com'}
  245. return proxies
  246. howdoi.getproxies = getproxies1
  247. filtered_proxies = howdoi.get_proxies()
  248. self.assertTrue('http://' in filtered_proxies['http'])
  249. self.assertTrue('http://' in filtered_proxies['https'])
  250. self.assertTrue('ftp' not in filtered_proxies.keys())
  251. if __name__ == '__main__':
  252. unittest.main()