コード例 #1
0
ファイル: test_cli_scenarios.py プロジェクト: samedder/knack
class TestCLIScenarios(unittest.TestCase):

    def setUp(self):
        self.mock_ctx = MockContext()

    def test_list_value_parameter(self):
        handler_args = {}
        def handler(args):
            handler_args.update(args)

        command = CLICommand(self.mock_ctx, 'test command', handler)
        command.add_argument('hello', '--hello', nargs='+')
        command.add_argument('something', '--something')
        cmd_table = {'test command': command}
        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            self.mock_ctx.invoke('test command --hello world sir --something else'.split())
        self.assertEqual(handler_args['something'], 'else')
        self.assertEqual(handler_args['hello'][0], 'world')
        self.assertEqual(handler_args['hello'][1], 'sir')

    def test_case_insensitive_command_path(self):
        def handler(_):
            return 'PASSED'

        command = CLICommand(self.mock_ctx, 'test command', handler)
        command.add_argument('var', '--var', '-v')
        cmd_table = {'test command': command}

        def _test(cmd_line):
            with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
                ci = CommandInvoker(cli_ctx=self.mock_ctx)
                self.mock_ctx.invocation = ci
                return ci.execute(cmd_line.split())

        # case insensitive command paths
        result = _test('TEST command --var blah')
        self.assertEqual(result.result, 'PASSED')

        result = _test('test COMMAND --var blah')
        self.assertEqual(result.result, 'PASSED')

        result = _test('test command -v blah')
        self.assertEqual(result.result, 'PASSED')

        # verify that long and short options remain case sensitive
        with mock.patch('sys.stderr', new_callable=StringIO):
            with self.assertRaises(SystemExit):
                _test('test command --vAR blah')

            with self.assertRaises(SystemExit):
                _test('test command -V blah')

    def test_cli_exapp1(self):
        def a_test_command_handler(_):
            return [{'a': 1, 'b': 1234}, {'a': 3, 'b': 4}]

        class MyCommandsLoader(CLICommandsLoader):
            def load_command_table(self, args):
                self.command_table['abc xyz'] = CLICommand(self.cli_ctx, 'abc xyz', a_test_command_handler)
                self.command_table['abc list'] = CLICommand(self.cli_ctx, 'abc list', a_test_command_handler)
                return OrderedDict(self.command_table)

        mycli = CLI(cli_name='exapp1', config_dir=os.path.join('~', '.exapp1'), commands_loader_cls=MyCommandsLoader)

        expected_output = """[
  {
    "a": 1,
    "b": 1234
  },
  {
    "a": 3,
    "b": 4
  }
]
"""
        mock_stdout = StringIO()
        exit_code = mycli.invoke(['abc', 'xyz'], out_file=mock_stdout)
        self.assertEqual(expected_output, mock_stdout.getvalue())
        self.assertEqual(0, exit_code)

        mock_stdout = StringIO()
        mycli.invoke(['abc', 'list'], out_file=mock_stdout)
        self.assertEqual(expected_output, mock_stdout.getvalue())
        self.assertEqual(0, exit_code)

        expected_output = """{
  "a": 1,
  "b": 1234
}
"""
        mock_stdout = StringIO()
        mycli.invoke(['abc', 'list', '--query', '[0]'], out_file=mock_stdout)
        self.assertEqual(expected_output, mock_stdout.getvalue())
        self.assertEqual(0, exit_code)

        expected_output = "1\n"
        mock_stdout = StringIO()
        mycli.invoke(['abc', 'list', '--query', '[0].a'], out_file=mock_stdout)
        self.assertEqual(expected_output, mock_stdout.getvalue())
        self.assertEqual(0, exit_code)
コード例 #2
0
ファイル: test_help.py プロジェクト: samedder/knack
class TestHelp(unittest.TestCase):

    def setUp(self):
        self.mock_ctx = MockContext()
        self.cliname = self.mock_ctx.name

    @redirect_io
    def test_choice_list_with_ints(self):
        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('arg', '--arg', '-a', required=False, choices=[1, 2, 3])
        command.add_argument('b', '-b', required=False, choices=['a', 'b', 'c'])
        cmd_table = {'n1': command}
        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())

    @redirect_io
    def test_help_param(self):
        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())

            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 --help'.split())

    @redirect_io
    def test_help_plain_short_description(self):
        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler, description='the description')
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())
            self.assertTrue('n1: The description.' in io.getvalue())

    @redirect_io
    def test_help_plain_long_description(self):
        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        command.help = 'long description'
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())
            self.assertTrue(io.getvalue().startswith('\nCommand\n    {} n1\n        Long description.'.format(self.cliname)))

    @redirect_io
    def test_help_long_description_and_short_description(self):
        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler, description='short description')
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        command.help = 'long description'
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())
            self.assertTrue(io.getvalue().startswith('\nCommand\n    {} n1: Short description.\n        Long description.'.format(self.cliname)))  # pylint: disable=line-too-long

    @redirect_io
    def test_help_docstring_description_overrides_short_description(self):
        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler, description='short description')
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        command.help = 'short-summary: docstring summary'
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())
            self.assertTrue('n1: Docstring summary.' in io.getvalue())

    @redirect_io
    def test_help_long_description_multi_line(self):
        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        command.help = """
            long-summary: |
                line1
                line2
            """
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())

            self.assertTrue(io.getvalue().startswith('\nCommand\n    {} n1\n        Line1\n        line2.'.format(self.cliname)))  # pylint: disable=line-too-long

    @redirect_io
    @mock.patch('knack.cli.CLI.register_event')
    def test_help_params_documentations(self, _):
        def test_handler():
            pass

        self.mock_ctx = MockContext()
        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('foobar', '--foobar', '-fb', required=False)
        command.add_argument('foobar2', '--foobar2', '-fb2', required=True)
        command.add_argument('foobar3', '--foobar3', '-fb3', required=False, help='the foobar3')
        command.help = """
            parameters:
                - name: --foobar -fb
                  type: string
                  required: false
                  short-summary: one line partial sentence
                  long-summary: text, markdown, etc.
                  populator-commands:
                    - mycli abc xyz
                    - default
                - name: --foobar2 -fb2
                  type: string
                  required: true
                  short-summary: one line partial sentence
                  long-summary: paragraph(s)
            """
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())
        s = """
Command
    {} n1

Arguments
    --foobar2 -fb2 [Required]: One line partial sentence.
        Paragraph(s).
    --foobar -fb             : One line partial sentence.  Values from: mycli abc xyz, default.
        Text, markdown, etc.
    --foobar3 -fb3           : The foobar3.

Global Arguments
    --help -h                : Show this help message and exit.
"""
        self.assertEqual(s.format(self.cliname), io.getvalue())

    @redirect_io
    @mock.patch('knack.cli.CLI.register_event')
    def test_help_full_documentations(self, _):
        def test_handler():
            pass

        self.mock_ctx = MockContext()
        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('foobar', '--foobar', '-fb', required=False)
        command.add_argument('foobar2', '--foobar2', '-fb2', required=True)
        command.help = """
                short-summary: this module does xyz one-line or so
                long-summary: |
                    this module.... kjsdflkj... klsfkj paragraph1
                    this module.... kjsdflkj... klsfkj paragraph2
                parameters:
                    - name: --foobar -fb
                      type: string
                      required: false
                      short-summary: one line partial sentence
                      long-summary: text, markdown, etc.
                      populator-commands:
                        - mycli abc xyz
                        - default
                    - name: --foobar2 -fb2
                      type: string
                      required: true
                      short-summary: one line partial sentence
                      long-summary: paragraph(s)
                examples:
                    - name: foo example
                      text: example details
            """
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())
        s = """
Command
    {} n1: This module does xyz one-line or so.
        This module.... kjsdflkj... klsfkj paragraph1
        this module.... kjsdflkj... klsfkj paragraph2.

Arguments
    --foobar2 -fb2 [Required]: One line partial sentence.
        Paragraph(s).
    --foobar -fb             : One line partial sentence.  Values from: mycli abc xyz, default.
        Text, markdown, etc.

Global Arguments
    --help -h                : Show this help message and exit.

Examples
    foo example
        example details

"""
        self.assertEqual(s.format(self.cliname), io.getvalue())

    @redirect_io
    @mock.patch('knack.cli.CLI.register_event')
    def test_help_with_param_specified(self, _):
        def test_handler():
            pass

        self.mock_ctx = MockContext()
        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 --arg foo -h'.split())

        s = """
Command
    {} n1

Arguments
    --arg -a
    -b

Global Arguments
    --help -h: Show this help message and exit.
"""

        self.assertEqual(s.format(self.cliname), io.getvalue())

    @redirect_io
    def test_help_group_children(self):
        def test_handler():
            pass

        def test_handler2():
            pass

        command = CLICommand(self.mock_ctx, 'group1 group3 n1', test_handler)
        command.add_argument('foobar', '--foobar', '-fb', required=False)
        command.add_argument('foobar2', '--foobar2', '-fb2', required=True)

        command2 = CLICommand(self.mock_ctx, 'group1 group2 n1', test_handler2)
        command2.add_argument('foobar', '--foobar', '-fb', required=False)
        command2.add_argument('foobar2', '--foobar2', '-fb2', required=True)

        cmd_table = {'group1 group3 n1': command, 'group1 group2 n1': command2}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('group1 -h'.split())
            s = '\nGroup\n    {} group1\n\nSubgroups:\n    group2\n    group3\n\n'.format(self.cliname)
            self.assertEqual(s, io.getvalue())

    @redirect_io
    def test_help_extra_missing_params(self):
        def test_handler(foobar2, foobar=None):  # pylint: disable=unused-argument
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('foobar', '--foobar', '-fb', required=False)
        command.add_argument('foobar2', '--foobar2', '-fb2', required=True)
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            # work around an argparse behavior where output is not printed and SystemExit
            # is not raised on Python 2.7.9
            if sys.version_info < (2, 7, 10):
                try:
                    self.mock_ctx.invoke('n1 -fb a --foobar value'.split())
                except SystemExit:
                    pass

                try:
                    self.mock_ctx.invoke('n1 -fb a --foobar2 value --foobar3 extra'.split())
                except SystemExit:
                    pass
            else:
                with self.assertRaises(SystemExit):
                    self.mock_ctx.invoke('n1 -fb a --foobar value'.split())
                with self.assertRaises(SystemExit):
                    self.mock_ctx.invoke('n1 -fb a --foobar2 value --foobar3 extra'.split())

                self.assertTrue('required' in io.getvalue() and
                                '--foobar/-fb' not in io.getvalue() and
                                '--foobar2/-fb2' in io.getvalue() and
                                'unrecognized arguments: --foobar3 extra' in io.getvalue())

    @redirect_io
    def test_help_group_help(self):
        def test_handler():
            pass
        from knack.help_files import helps
        helps['test_group1 test_group2'] = """
            type: group
            short-summary: this module does xyz one-line or so
            long-summary: |
                this module.... kjsdflkj... klsfkj paragraph1
                this module.... kjsdflkj... klsfkj paragraph2
            examples:
                - name: foo example
                  text: example details
            """

        command = CLICommand(self.mock_ctx, 'test_group1 test_group2 n1', test_handler)
        command.add_argument('foobar', '--foobar', '-fb', required=False)
        command.add_argument('foobar2', '--foobar2', '-fb2', required=True)
        command.help = """
            short-summary: this module does xyz one-line or so
            long-summary: |
                this module.... kjsdflkj... klsfkj paragraph1
                this module.... kjsdflkj... klsfkj paragraph2
            parameters:
                - name: --foobar -fb
                  type: string
                  required: false
                  short-summary: one line partial sentence
                  long-summary: text, markdown, etc.
                  populator-commands:
                    - mycli abc xyz
                    - default
                - name: --foobar2 -fb2
                  type: string
                  required: true
                  short-summary: one line partial sentence
                  long-summary: paragraph(s)
            examples:
                - name: foo example
                  text: example details
        """
        cmd_table = {'test_group1 test_group2 n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('test_group1 test_group2 --help'.split())
        s = """
Group
    {} test_group1 test_group2: This module does xyz one-line or so.
        This module.... kjsdflkj... klsfkj paragraph1
        this module.... kjsdflkj... klsfkj paragraph2.

Commands:
    n1: This module does xyz one-line or so.


Examples
    foo example
        example details

"""
        self.assertEqual(s.format(self.cliname), io.getvalue())
        del helps['test_group1 test_group2']

    @redirect_io
    @mock.patch('knack.cli.CLI.register_event')
    def test_help_global_params(self, _):

        def register_globals(_, **kwargs):
            arg_group = kwargs.get('arg_group')
            arg_group.add_argument('--exampl',
                                   help='This is a new global argument.')

        self.mock_ctx = MockContext()
        self.mock_ctx._event_handlers[EVENT_PARSER_GLOBAL_CREATE].append(register_globals)  # pylint: disable=protected-access

        def test_handler():
            pass

        command = CLICommand(self.mock_ctx, 'n1', test_handler)
        command.add_argument('arg', '--arg', '-a', required=False)
        command.add_argument('b', '-b', required=False)
        command.help = """
            long-summary: |
                line1
                line2
        """
        cmd_table = {'n1': command}

        with mock.patch.object(CLICommandsLoader, 'load_command_table', return_value=cmd_table):
            with self.assertRaises(SystemExit):
                self.mock_ctx.invoke('n1 -h'.split())

        s = """
Command
    {} n1
        Line1
        line2.

Arguments
    --arg -a
    -b

Global Arguments
    --exampl : This is a new global argument.
    --help -h: Show this help message and exit.
"""
        self.assertEqual(s.format(self.cliname), io.getvalue())