"Fossies" - the Fresh Open Source Software Archive

Member "http-prompt-2.1.0/tests/test_cli.py" (5 Mar 2021, 13249 Bytes) of package /linux/www/http-prompt-2.1.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "test_cli.py": 1.0.0_vs_2.1.0.

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