test_cli.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import json
  2. import os
  3. import sys
  4. import unittest
  5. from click.testing import CliRunner
  6. from mock import patch, DEFAULT
  7. from requests.models import Response
  8. from .base import TempAppDirTestCase
  9. from http_prompt import xdg
  10. from http_prompt.context import Context
  11. from http_prompt.cli import cli, execute, ExecutionListener
  12. def run_and_exit(cli_args=None, prompt_commands=None):
  13. """Run http-prompt executable, execute some prompt commands, and exit."""
  14. if cli_args is None:
  15. cli_args = []
  16. # Make sure last command is 'exit'
  17. if prompt_commands is None:
  18. prompt_commands = ['exit']
  19. else:
  20. prompt_commands += ['exit']
  21. # Fool cli() so that it believes we're running from CLI instead of pytest.
  22. # We will restore it at the end of the function.
  23. orig_argv = sys.argv
  24. sys.argv = ['http-prompt'] + cli_args
  25. try:
  26. with patch.multiple('http_prompt.cli',
  27. prompt=DEFAULT, execute=DEFAULT) as mocks:
  28. mocks['execute'].side_effect = execute
  29. # prompt() is mocked to return the command in 'prompt_commands' in
  30. # sequence, i.e., prompt() returns prompt_commands[i-1] when it is
  31. # called for the ith time
  32. mocks['prompt'].side_effect = prompt_commands
  33. result = CliRunner().invoke(cli, cli_args)
  34. context = mocks['execute'].call_args[0][1]
  35. return result, context
  36. finally:
  37. sys.argv = orig_argv
  38. class TestCli(TempAppDirTestCase):
  39. def test_without_args(self):
  40. result, context = run_and_exit(['http://localhost'])
  41. self.assertEqual(result.exit_code, 0)
  42. self.assertEqual(context.url, 'http://localhost')
  43. self.assertEqual(context.options, {})
  44. self.assertEqual(context.body_params, {})
  45. self.assertEqual(context.headers, {})
  46. self.assertEqual(context.querystring_params, {})
  47. def test_incomplete_url1(self):
  48. result, context = run_and_exit(['://example.com'])
  49. self.assertEqual(result.exit_code, 0)
  50. self.assertEqual(context.url, 'http://example.com')
  51. self.assertEqual(context.options, {})
  52. self.assertEqual(context.body_params, {})
  53. self.assertEqual(context.headers, {})
  54. self.assertEqual(context.querystring_params, {})
  55. def test_incomplete_url2(self):
  56. result, context = run_and_exit(['//example.com'])
  57. self.assertEqual(result.exit_code, 0)
  58. self.assertEqual(context.url, 'http://example.com')
  59. self.assertEqual(context.options, {})
  60. self.assertEqual(context.body_params, {})
  61. self.assertEqual(context.headers, {})
  62. self.assertEqual(context.querystring_params, {})
  63. def test_incomplete_url3(self):
  64. result, context = run_and_exit(['example.com'])
  65. self.assertEqual(result.exit_code, 0)
  66. self.assertEqual(context.url, 'http://example.com')
  67. self.assertEqual(context.options, {})
  68. self.assertEqual(context.body_params, {})
  69. self.assertEqual(context.headers, {})
  70. self.assertEqual(context.querystring_params, {})
  71. def test_httpie_oprions(self):
  72. url = 'http://example.com'
  73. custom_args = '--auth value: name=foo'
  74. result, context = run_and_exit([url] + custom_args.split())
  75. self.assertEqual(result.exit_code, 0)
  76. self.assertEqual(context.url, 'http://example.com')
  77. self.assertEqual(context.options, {'--auth': 'value:'})
  78. self.assertEqual(context.body_params, {'name': 'foo'})
  79. self.assertEqual(context.headers, {})
  80. self.assertEqual(context.querystring_params, {})
  81. def test_persistent_context(self):
  82. result, context = run_and_exit(['//example.com', 'name=bob', 'id==10'])
  83. self.assertEqual(result.exit_code, 0)
  84. self.assertEqual(context.url, 'http://example.com')
  85. self.assertEqual(context.options, {})
  86. self.assertEqual(context.body_params, {'name': 'bob'})
  87. self.assertEqual(context.headers, {})
  88. self.assertEqual(context.querystring_params, {'id': ['10']})
  89. result, context = run_and_exit()
  90. self.assertEqual(result.exit_code, 0)
  91. self.assertEqual(context.url, 'http://example.com')
  92. self.assertEqual(context.options, {})
  93. self.assertEqual(context.body_params, {'name': 'bob'})
  94. self.assertEqual(context.headers, {})
  95. self.assertEqual(context.querystring_params, {'id': ['10']})
  96. def test_cli_args_bypasses_persistent_context(self):
  97. result, context = run_and_exit(['//example.com', 'name=bob', 'id==10'])
  98. self.assertEqual(result.exit_code, 0)
  99. self.assertEqual(context.url, 'http://example.com')
  100. self.assertEqual(context.options, {})
  101. self.assertEqual(context.body_params, {'name': 'bob'})
  102. self.assertEqual(context.headers, {})
  103. self.assertEqual(context.querystring_params, {'id': ['10']})
  104. result, context = run_and_exit(['//example.com', 'sex=M'])
  105. self.assertEqual(result.exit_code, 0)
  106. self.assertEqual(context.url, 'http://example.com')
  107. self.assertEqual(context.options, {})
  108. self.assertEqual(context.body_params, {'sex': 'M'})
  109. self.assertEqual(context.headers, {})
  110. def test_config_file(self):
  111. # Config file is not there at the beginning
  112. config_path = os.path.join(xdg.get_config_dir(), 'config.py')
  113. self.assertFalse(os.path.exists(config_path))
  114. # After user runs it for the first time, a default config file should
  115. # be created
  116. result, context = run_and_exit(['//example.com'])
  117. self.assertEqual(result.exit_code, 0)
  118. self.assertTrue(os.path.exists(config_path))
  119. def test_cli_arguments_with_spaces(self):
  120. result, context = run_and_exit(['example.com', "name=John Doe",
  121. "Authorization:Bearer API KEY"])
  122. self.assertEqual(result.exit_code, 0)
  123. self.assertEqual(context.url, 'http://example.com')
  124. self.assertEqual(context.options, {})
  125. self.assertEqual(context.querystring_params, {})
  126. self.assertEqual(context.body_params, {'name': 'John Doe'})
  127. self.assertEqual(context.headers, {'Authorization': 'Bearer API KEY'})
  128. def test_spec_from_local(self):
  129. spec_filepath = self.make_tempfile(json.dumps({
  130. 'paths': {
  131. '/users': {},
  132. '/orgs': {}
  133. }
  134. }))
  135. result, context = run_and_exit(['example.com', "--spec",
  136. spec_filepath])
  137. self.assertEqual(result.exit_code, 0)
  138. self.assertEqual(context.url, 'http://example.com')
  139. self.assertEqual(set([n.name for n in context.root.children]),
  140. set(['users', 'orgs']))
  141. def test_spec_basePath(self):
  142. spec_filepath = self.make_tempfile(json.dumps({
  143. 'basePath': '/api/v1',
  144. 'paths': {
  145. '/users': {},
  146. '/orgs': {}
  147. }
  148. }))
  149. result, context = run_and_exit(['example.com', "--spec",
  150. spec_filepath])
  151. self.assertEqual(result.exit_code, 0)
  152. self.assertEqual(context.url, 'http://example.com')
  153. lv1_names = set([node.name for node in context.root.ls()])
  154. lv2_names = set([node.name for node in context.root.ls('api')])
  155. lv3_names = set([node.name for node in context.root.ls('api', 'v1')])
  156. self.assertEqual(lv1_names, set(['api']))
  157. self.assertEqual(lv2_names, set(['v1']))
  158. self.assertEqual(lv3_names, set(['users', 'orgs']))
  159. def test_spec_from_http(self):
  160. spec_url = 'https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json'
  161. result, context = run_and_exit(['https://api.github.com', '--spec',
  162. spec_url])
  163. self.assertEqual(result.exit_code, 0)
  164. self.assertEqual(context.url, 'https://api.github.com')
  165. top_level_paths = set([n.name for n in context.root.children])
  166. self.assertIn('repos', top_level_paths)
  167. self.assertIn('users', top_level_paths)
  168. def test_spec_from_http_only(self):
  169. spec_url = (
  170. 'https://api.apis.guru/v2/specs/medium.com/1.0.0/swagger.json')
  171. result, context = run_and_exit(['--spec', spec_url])
  172. self.assertEqual(result.exit_code, 0)
  173. self.assertEqual(context.url, 'https://api.medium.com/v1')
  174. lv1_names = set([node.name for node in context.root.ls()])
  175. lv2_names = set([node.name for node in context.root.ls('v1')])
  176. self.assertEqual(lv1_names, set(['v1']))
  177. self.assertEqual(lv2_names, set(['me', 'publications', 'users']))
  178. def test_spec_with_trailing_slash(self):
  179. spec_filepath = self.make_tempfile(json.dumps({
  180. 'basePath': '/api',
  181. 'paths': {
  182. '/': {},
  183. '/users/': {}
  184. }
  185. }))
  186. result, context = run_and_exit(['example.com', "--spec",
  187. spec_filepath])
  188. self.assertEqual(result.exit_code, 0)
  189. self.assertEqual(context.url, 'http://example.com')
  190. lv1_names = set([node.name for node in context.root.ls()])
  191. lv2_names = set([node.name for node in context.root.ls('api')])
  192. self.assertEqual(lv1_names, set(['api']))
  193. self.assertEqual(lv2_names, set(['/', 'users/']))
  194. def test_env_only(self):
  195. env_filepath = self.make_tempfile(
  196. "cd http://example.com\nname=bob\nid==10")
  197. result, context = run_and_exit(["--env", env_filepath])
  198. self.assertEqual(result.exit_code, 0)
  199. self.assertEqual(context.url, 'http://example.com')
  200. self.assertEqual(context.options, {})
  201. self.assertEqual(context.body_params, {'name': 'bob'})
  202. self.assertEqual(context.headers, {})
  203. self.assertEqual(context.querystring_params, {'id': ['10']})
  204. def test_env_with_url(self):
  205. env_filepath = self.make_tempfile(
  206. "cd http://example.com\nname=bob\nid==10")
  207. result, context = run_and_exit(["--env", env_filepath,
  208. 'other_example.com'])
  209. self.assertEqual(result.exit_code, 0)
  210. self.assertEqual(context.url, 'http://other_example.com')
  211. self.assertEqual(context.options, {})
  212. self.assertEqual(context.body_params, {'name': 'bob'})
  213. self.assertEqual(context.headers, {})
  214. self.assertEqual(context.querystring_params, {'id': ['10']})
  215. def test_env_with_options(self):
  216. env_filepath = self.make_tempfile(
  217. "cd http://example.com\nname=bob\nid==10")
  218. result, context = run_and_exit(["--env", env_filepath,
  219. 'other_example.com', 'name=alice'])
  220. self.assertEqual(result.exit_code, 0)
  221. self.assertEqual(context.url, 'http://other_example.com')
  222. self.assertEqual(context.options, {})
  223. self.assertEqual(context.body_params, {'name': 'alice'})
  224. self.assertEqual(context.headers, {})
  225. self.assertEqual(context.querystring_params, {'id': ['10']})
  226. @patch('http_prompt.cli.prompt')
  227. @patch('http_prompt.cli.execute')
  228. def test_press_ctrl_d(self, execute_mock, prompt_mock):
  229. prompt_mock.side_effect = EOFError
  230. execute_mock.side_effect = execute
  231. result = CliRunner().invoke(cli, [])
  232. self.assertEqual(result.exit_code, 0)
  233. class TestExecutionListenerSetCookies(unittest.TestCase):
  234. def setUp(self):
  235. self.listener = ExecutionListener({})
  236. self.response = Response()
  237. self.response.cookies.update({
  238. 'username': 'john',
  239. 'sessionid': 'abcd'
  240. })
  241. self.context = Context('http://localhost')
  242. self.context.headers['Cookie'] = 'name="John Doe"; sessionid=xyz'
  243. def test_auto(self):
  244. self.listener.cfg['set_cookies'] = 'auto'
  245. self.listener.response_returned(self.context, self.response)
  246. self.assertEqual(self.context.headers['Cookie'],
  247. 'name="John Doe"; sessionid=abcd; username=john')
  248. @patch('http_prompt.cli.click.confirm')
  249. def test_ask_and_yes(self, confirm_mock):
  250. confirm_mock.return_value = True
  251. self.listener.cfg['set_cookies'] = 'ask'
  252. self.listener.response_returned(self.context, self.response)
  253. self.assertEqual(self.context.headers['Cookie'],
  254. 'name="John Doe"; sessionid=abcd; username=john')
  255. @patch('http_prompt.cli.click.confirm')
  256. def test_ask_and_no(self, confirm_mock):
  257. confirm_mock.return_value = False
  258. self.listener.cfg['set_cookies'] = 'ask'
  259. self.listener.response_returned(self.context, self.response)
  260. self.assertEqual(self.context.headers['Cookie'],
  261. 'name="John Doe"; sessionid=xyz')
  262. def test_off(self):
  263. self.listener.cfg['set_cookies'] = 'off'
  264. self.listener.response_returned(self.context, self.response)
  265. self.assertEqual(self.context.headers['Cookie'],
  266. 'name="John Doe"; sessionid=xyz')