예제 #1
0
    def test_help_group_children(self):
        app = Application(Configuration([]))
        def test_handler():
            pass
        def test_handler2():
            pass

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

        command2 = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('group1 -h'.split())
        s = '\nGroup\n    az group1\n\nSubgroups:\n    group2\n    group3\n\n'
        self.assertEqual(s, io.getvalue())
예제 #2
0
    def test_help_with_param_specified(self, _):
        app = Application(Configuration([]))
        def test_handler():
            pass

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

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 --arg foo -h'.split())

        s = """
Command
    az n1

Arguments
    --arg -a
    -b

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

        self.assertEqual(s, io.getvalue())
예제 #3
0
    def test_help_with_param_specified(self, _):
        app = Application(Configuration([]))

        def test_handler():
            pass

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

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 --arg foo -h'.split())

        s = """
Command
    az n1

Arguments
    --arg -a
    -b

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

        self.assertEqual(s, io.getvalue())
예제 #4
0
    def test_list_value_parameter(self):
        hellos = []

        def handler(args):
            hellos.append(args)

        command = CliCommand('test command', handler)
        command.add_argument('hello',
                             '--hello',
                             nargs='+',
                             action=IterateAction)
        command.add_argument('something', '--something')
        cmd_table = {'test command': command}

        argv = 'az test command --hello world sir --something else'.split()
        config = Configuration(argv)
        config.get_command_table = lambda: cmd_table
        application = Application(config)
        application.execute(argv[1:])

        self.assertEqual(2, len(hellos))
        self.assertEqual(hellos[0]['hello'], 'world')
        self.assertEqual(hellos[0]['something'], 'else')
        self.assertEqual(hellos[1]['hello'], 'sir')
        self.assertEqual(hellos[1]['something'], 'else')
예제 #5
0
    def test_help_group_children(self):
        app = Application(Configuration([]))

        def test_handler():
            pass

        def test_handler2():
            pass

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

        command2 = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('group1 -h'.split())
        s = '\nGroup\n    az group1\n\nSubgroups:\n    group2\n    group3\n\n'
        self.assertEqual(s, io.getvalue())
예제 #6
0
    def test_help_params_documentations(self, _):
        app = Application(Configuration([]))

        def test_handler():
            pass

        command = CliCommand('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: 
                    - az vm list
                    - default
                - name: --foobar2 -fb2
                  type: string
                  required: true
                  short-summary: one line partial sentence
                  long-summary: paragraph(s)
            """
        cmd_table = {'n1': command}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        s = """
Command
    az n1

Arguments
    --foobar2 -fb2 [Required]: One line partial sentence.
        Paragraph(s).

    --foobar -fb             : One line partial sentence.
        Text, markdown, etc.
        Values from: az vm list, default.

    --foobar3 -fb3           : The foobar3.

Global Arguments
    --help -h                : Show this help message and exit.
"""
        self.assertEqual(s, io.getvalue())
예제 #7
0
    def test_help_params_documentations(self, _):
        app = Application(Configuration([]))
        def test_handler():
            pass

        command = CliCommand('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: 
                    - az vm list
                    - default
                - name: --foobar2 -fb2
                  type: string
                  required: true
                  short-summary: one line partial sentence
                  long-summary: paragraph(s)
            """
        cmd_table = {'n1': command}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        s = """
Command
    az n1

Arguments
    --foobar2 -fb2 [Required]: One line partial sentence.
        Paragraph(s).

    --foobar -fb             : One line partial sentence.
        Text, markdown, etc.
        Values from: az vm list, default.

    --foobar3 -fb3           : The foobar3.

Global Arguments
    --help -h                : Show this help message and exit.
"""
        self.assertEqual(s, io.getvalue())
예제 #8
0
    def test_help_global_params(self, mock_register_extensions, _):
        def register_globals(global_group):
            global_group.add_argument(
                '--query2',
                dest='_jmespath_query',
                metavar='JMESPATH',
                help='JMESPath query string. See http://jmespath.org/ '
                'for more information and examples.')

        mock_register_extensions.return_value = None
        mock_register_extensions.side_effect = lambda app: \
            app._event_handlers[app.GLOBAL_PARSER_CREATED].append(register_globals) # pylint: disable=protected-access

        def test_handler():
            pass

        command = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())

        s = """
Command
    az n1
        Line1
        line2.

Arguments
    --arg -a
    -b

Global Arguments
    --help -h: Show this help message and exit.
    --query2 : JMESPath query string. See http://jmespath.org/ for more information and examples.
"""

        self.assertEqual(s, io.getvalue())
예제 #9
0
    def test_help_plain_short_description(self):
        def test_handler():
            pass

        command = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        self.assertEqual(True, 'n1: The description.' in io.getvalue())
예제 #10
0
    def test_generic_update_errors(self):
        my_obj = {
            'prop': 'val',
            'list': [
                'a',
                'b',
                ['c', {'d': 'e'}]
                ]
            }

        def my_get(a1, a2): #pylint: disable=unused-argument
            return my_obj

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_obj

        config = Configuration([])
        app = Application(config)

        register_generic_update('gencommand', my_get, my_set)

        def _execute_with_error(command, error, message):
            try:
                app.execute(command.split())
            except CLIError as err:
                self.assertEqual(error in str(err), True, message)
            else:
                raise AssertionError('exception not thrown')

        missing_remove_message = """Couldn't find "doesntExist" in "".""" + \
                                 """  Available options: ['list', 'prop']"""
        _execute_with_error('gencommand --a1 1 --a2 2 --remove doesnt_exist',
                            missing_remove_message,
                            'remove non-existent property by name')
        _execute_with_error('gencommand --a1 1 --a2 2 --remove doesntExist 2',
                            missing_remove_message,
                            'remove non-existent property by index')

        remove_prop_message = """Couldn't find "doesntExist" in "list.doesntExist".""" + \
                              """  Available options: [['c', {'d': 'e'}], 'a', 'b']"""
        _execute_with_error('gencommand --a1 1 --a2 2 --remove list.doesnt_exist.missing 2',
                            remove_prop_message,
                            'remove non-existent sub-property by index')

        _execute_with_error('gencommand --a1 1 --a2 2 --remove list 20',
                            "index 20 doesn't exist on list",
                            'remove out-of-range index')

        set_on_list_message = """Couldn't find "doesntExist" in "list".""" + \
                              """  Available options: [['c', {'d': 'e'}], 'a', 'b']"""
        _execute_with_error('gencommand --a1 1 --a2 2 --set list.doesnt_exist=foo',
                            set_on_list_message,
                            'set shouldn\'t work on a list')
        _execute_with_error('gencommand --a1 1 --a2 2 --set list.doesnt_exist.doesnt_exist2=foo',
                            set_on_list_message,
                            'set shouldn\'t work on a list')

        _execute_with_error('gencommand --a1 1 --a2 2 --set list[2][3].doesnt_exist=foo',
                            "index 3 doesn't exist on [2]",
                            'index out of range in path')
예제 #11
0
    def test_help_plain_short_description(self):
        def test_handler():
            pass

        command = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        self.assertEqual(True, 'n1: The description.' in io.getvalue())
예제 #12
0
def main(args, file=sys.stdout):  #pylint: disable=redefined-builtin
    _logging.configure_logging(args)

    if len(args) > 0 and args[0] == '--version':
        show_version_info_exit(file)

    azure_folder = os.path.expanduser('~/.azure')
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = Configuration(args)
    APPLICATION.initialize(config)

    try:
        cmd_result = APPLICATION.execute(args)
        # Commands can return a dictionary/list of results
        # If they do, we print the results.
        if cmd_result and cmd_result.result:
            formatter = OutputProducer.get_formatter(
                APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=file).out(cmd_result)
    except Exception as ex:  # pylint: disable=broad-except
        error_code = _handle_exception(ex)
        return error_code
예제 #13
0
    def test_application_register_and_call_handlers(self):
        handler_called = [False]

        def handler(**kwargs):
            kwargs['args'][0] = True

        def other_handler(**kwargs):  # pylint: disable=unused-variable
            self.assertEqual(kwargs['args'], 'secret sauce')

        config = Configuration([])
        app = Application(config)

        app.raise_event('was_handler_called', args=handler_called)
        self.assertFalse(
            handler_called[0],
            "Raising event with no handlers registered somehow failed...")

        app.register('was_handler_called', handler)
        self.assertFalse(handler_called[0])

        # Registered handler won't get called if event with different name
        # is raised...
        app.raise_event('other_handler_called', args=handler_called)
        self.assertFalse(handler_called[0], 'Wrong handler called!')

        app.raise_event('was_handler_called', args=handler_called)
        self.assertTrue(handler_called[0], "Handler didn't get called")

        app.raise_event('other_handler_called', args='secret sauce')
예제 #14
0
    def test_help_plain_long_description(self):
        def test_handler():
            pass

        command = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        self.assertEqual(True, io.getvalue().startswith('\nCommand\n    az n1\n        Long description.'))  # pylint: disable=line-too-long
예제 #15
0
    def test_help_global_params(self, mock_register_extensions, _):
        def register_globals(global_group):
            global_group.add_argument('--query2', dest='_jmespath_query', metavar='JMESPATH',
                                      help='JMESPath query string. See http://jmespath.org/ '
                                      'for more information and examples.')

        mock_register_extensions.return_value = None
        mock_register_extensions.side_effect = lambda app: \
            app._event_handlers[app.GLOBAL_PARSER_CREATED].append(register_globals) # pylint: disable=protected-access

        def test_handler():
            pass

        command = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())

        s = """
Command
    az n1
        Line1
        line2.

Arguments
    --arg -a
    -b

Global Arguments
    --help -h: Show this help message and exit.
    --query2 : JMESPath query string. See http://jmespath.org/ for more information and examples.
"""

        self.assertEqual(s, io.getvalue())
예제 #16
0
    def test_help_long_description_and_short_description(self):
        def test_handler():
            pass

        command = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        self.assertEqual(True, io.getvalue().startswith('\nCommand\n    az n1: Short description.\n        Long description.')) # pylint: disable=line-too-long
예제 #17
0
    def test_help_param(self):
        def test_handler():
            pass

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

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application()
        app.initialize(config)
        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())

        with self.assertRaises(SystemExit):
            app.execute('n1 --help'.split())
예제 #18
0
    def test_help_param(self):
        def test_handler():
            pass

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

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application()
        app.initialize(config)
        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())

        with self.assertRaises(SystemExit):
            app.execute('n1 --help'.split())
예제 #19
0
def mock_echo_args(command_name, parameters):
    try:
        argv = ' '.join((command_name, parameters)).split()
        APPLICATION.initialize(Configuration(argv))
        command_table = APPLICATION.configuration.get_command_table()
        prefunc = command_table[command_name].handler
        command_table[command_name].handler = lambda args: args
        parsed_namespace = APPLICATION.execute(argv)
        return parsed_namespace
    finally:
        command_table[command_name].handler = prefunc
예제 #20
0
    def test_help_long_description_multi_line(self):
        def test_handler():
            pass

        command = CliCommand('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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())

        self.assertEqual(True, io.getvalue().startswith('\nCommand\n    az n1\n        Line1\n        line2.')) # pylint: disable=line-too-long
예제 #21
0
    def test_list_value_parameter(self):
        hellos = []

        def handler(args):
            hellos.append(args)

        command = CliCommand('test command', handler)
        command.add_argument('hello', '--hello', nargs='+', action=IterateAction)
        command.add_argument('something', '--something')
        cmd_table = {'test command': command}

        argv = 'az test command --hello world sir --something else'.split()
        config = Configuration(argv)
        config.get_command_table = lambda: cmd_table
        application = Application(config)
        application.execute(argv[1:])

        self.assertEqual(2, len(hellos))
        self.assertEqual(hellos[0]['hello'], 'world')
        self.assertEqual(hellos[0]['something'], 'else')
        self.assertEqual(hellos[1]['hello'], 'sir')
        self.assertEqual(hellos[1]['something'], 'else')
예제 #22
0
    def test_help_extra_missing_params(self):
        app = Application(Configuration([]))

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

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

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        # 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:
                app.execute('n1 -fb a --foobar value'.split())
            except SystemExit:
                pass

            try:
                app.execute('n1 -fb a --foobar2 value --foobar3 extra'.split())
            except SystemExit:
                pass
        else:
            with self.assertRaises(SystemExit):
                app.execute('n1 -fb a --foobar value'.split())
            with self.assertRaises(SystemExit):
                app.execute('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())
예제 #23
0
    def test_help_extra_missing_params(self):
        app = Application(Configuration([]))
        def test_handler(foobar2, foobar=None): # pylint: disable=unused-argument
            pass

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

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        # 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:
                app.execute('n1 -fb a --foobar value'.split())
            except SystemExit:
                pass

            try:
                app.execute('n1 -fb a --foobar2 value --foobar3 extra'.split())
            except SystemExit:
                pass
        else:
            with self.assertRaises(SystemExit):
                app.execute('n1 -fb a --foobar value'.split())
            with self.assertRaises(SystemExit):
                app.execute('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())
예제 #24
0
    def test_generic_update_ids(self):
        my_objs = [
            {
                'prop': 'val',
                'list': [
                    'a',
                    'b',
                    ['c', {'d': 'e'}]
                    ]
            },
            {
                'prop': 'val',
                'list': [
                    'a',
                    'b',
                    ['c', {'d': 'e'}]
                    ]
            }]

        def my_get(name, resource_group): #pylint:disable=unused-argument
            # name is None when tests are run in a batch on Python <=2.7.9
            if sys.version_info < (2, 7, 10):
                return my_objs[0]
            return my_objs[int(name)]

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_objs

        register_cli_argument('gencommand', 'name', CliArgumentType(options_list=('--name', '-n'),
                                                                    metavar='NAME', id_part='name'))
        register_generic_update('gencommand', my_get, my_set)

        config = Configuration([])
        APPLICATION.initialize(config)

        id_str = ('/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rg/'
                  'providers/Microsoft.Compute/virtualMachines/')

        APPLICATION.execute('gencommand --ids {0}0 {0}1 --resource-group bar --set prop=newval'
                            .format(id_str).split())
        self.assertEqual(my_objs[0]['prop'], 'newval', 'first object updated')
        # name is None when tests are run in a batch on Python <=2.7.9
        if not sys.version_info < (2, 7, 10):
            self.assertEqual(my_objs[1]['prop'], 'newval', 'second object updated')
예제 #25
0
    def test_command_consistency(self):
        argv = ['vm']
        APPLICATION.initialize(Configuration(argv))
        command_table = APPLICATION.configuration.get_command_table()
        vm_commands = ((vm_command, metadata)
                       for vm_command, metadata in command_table.items()
                       if vm_command.startswith('vm'))

        for command_name, command_metadata in vm_commands:
            for argument_name, expected_options_list in self.consistent_arguments.items(
            ):
                try:
                    actual_options_list = command_metadata.arguments[
                        argument_name].options_list
                    self.assertEqual(
                        actual_options_list, expected_options_list,
                        'Argument {} of command {} has inconsistent flags'.
                        format(argument_name, command_name))
                except KeyError:
                    pass
예제 #26
0
    def test_generic_update_empty_nodes(self):
        my_obj = {
            'prop': None,
            'list': [],
            'dict': {
                'dict2': None
                },
            'dict3': {}
            }

        def my_get():
            return my_obj

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_obj

        config = Configuration([])
        app = Application(config)

        register_generic_update('gencommand', my_get, my_set)

        # add to prop
        app.execute('gencommand --add prop a=b'.split())
        self.assertEqual(my_obj['prop'][0]['a'], 'b', 'verify object added to null list')
        self.assertEqual(len(my_obj['prop'][0]), 1, 'verify only one object added to null list')

        #add to list
        app.execute('gencommand --add list c=d'.split())
        self.assertEqual(my_obj['list'][0]['c'], 'd', 'verify object added to empty list')
        self.assertEqual(len(my_obj['list']), 1, 'verify only one object added to empty list')

        # set dict2
        app.execute('gencommand --set dict.dict2.e=f'.split())
        self.assertEqual(my_obj['dict']['dict2']['e'], 'f', 'verify object added to null dict')
        self.assertEqual(len(my_obj['dict']['dict2']), 1,
                         'verify only one object added to null dict')

        #set dict3
        app.execute('gencommand --set dict3.g=h'.split())
        self.assertEqual(my_obj['dict3']['g'], 'h', 'verify object added to empty dict')
        self.assertEqual(len(my_obj['dict3']), 1, 'verify only one object added to empty dict')
예제 #27
0
#---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------------------------------

import argparse
from docutils import nodes
from docutils.statemachine import ViewList
from sphinx.util.compat import Directive
from sphinx.util.nodes import nested_parse_with_titles

from azure.cli.application import Application, Configuration
import azure.cli._help as _help

app = Application(Configuration([]))
try:
    app.execute(['-h'])
except:
    pass

class AzHelpGenDirective(Directive):
    def make_rst(self):
        INDENT = '   '
        DOUBLEINDENT = INDENT * 2
        parser_dict = {}
        _store_parsers(app.parser, parser_dict)
        parser_dict.pop('')

        help_files = []
        for cmd, parser in parser_dict.items():
            help_file = _help.GroupHelpFile(cmd, parser) if _is_group(parser) else _help.CommandHelpFile(cmd, parser) 
예제 #28
0
    def test_help_full_documentations(self, _):
        app = Application(Configuration([]))

        def test_handler():
            pass

        command = CliCommand('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: 
                        - az vm list
                        - 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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        s = """
Command
    az 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.
        Text, markdown, etc.
        Values from: az vm list, default.


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

Examples
    foo example
        example details
"""
        self.assertEqual(s, io.getvalue())
예제 #29
0
    def test_help_group_help(self):
        app = Application(Configuration([]))

        def test_handler():
            pass

        azure.cli.help_files.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('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: 
                    - az vm list
                    - 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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('test_group1 test_group2 --help'.split())
        s = """
Group
    az 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, io.getvalue())
예제 #30
0
    def test_help_group_help(self):
        app = Application(Configuration([]))
        def test_handler():
            pass

        azure.cli.help_files.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('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: 
                    - az vm list
                    - 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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('test_group1 test_group2 --help'.split())
        s = """
Group
    az 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, io.getvalue())

        del azure.cli.help_files.helps['test_group1 test_group2']
예제 #31
0
            dict_.pop(key)


def _dashed_to_camel(string):
    return string.replace('-', '_')


parser = argparse.ArgumentParser(description='Command Table Parser')
parser.add_argument('--commands',
                    metavar='N',
                    nargs='+',
                    help='Filter by first level command (OR)')
parser.add_argument('--params',
                    metavar='N',
                    nargs='+',
                    help='Filter by parameters (OR)')
parser.add_argument('--hide-nulls',
                    action='store_true',
                    default=False,
                    help='Show null entries')
args = parser.parse_args()
cmd_set_names = args.commands
param_names = [_dashed_to_camel(x) for x in args.params or []]
hide_nulls = args.hide_nulls

PRIMITIVES = (str, int, bool, float)
IGNORE_ARGS = ['help', 'help_file', 'base_type']

APPLICATION = Application(Configuration([]))
APPLICATION.register(Application.COMMAND_TABLE_LOADED, _dump_command_table)
APPLICATION.execute([''])
    def default(self, o):#pylint: disable=method-hidden
        try:
            return super(Exporter, self).default(o)
        except TypeError:
            return str(o)

parser = argparse.ArgumentParser(description='Command Table Parser')
parser.add_argument('--commands', metavar='N', nargs='+', help='Filter by first level command (OR)')
parser.add_argument('--params', metavar='N', nargs='+', help='Filter by parameters (OR)')
args = parser.parse_args()
cmd_set_names = args.commands
param_names = args.params

# ignore the params passed in now so they aren't used by the cli
sys.argv = sys.argv[:1]
config = Configuration([])
cmd_table = config.get_command_table()
cmd_list = [cmd_name for cmd_name in cmd_table.keys() if cmd_set_names is None or cmd_name.split()[0] in cmd_set_names]
results = []

if param_names:
    for name in cmd_list:
        cmd_name = [x for x in cmd_table.keys() if name == x][0]
        cmd_args = cmd_table[cmd_name]['arguments']
        match = False
        for arg in cmd_args:
            if match:
                break
            arg_name = re.sub('--','', arg['name']).split(' ')[0]
            if arg_name in param_names:
                results.append(name)
예제 #33
0
    def test_help_full_documentations(self, _):
        app = Application(Configuration([]))
        def test_handler():
            pass

        command = CliCommand('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: 
                        - az vm list
                        - 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}

        config = Configuration([])
        config.get_command_table = lambda: cmd_table
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('n1 -h'.split())
        s = """
Command
    az 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.
        Text, markdown, etc.
        Values from: az vm list, default.


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

Examples
    foo example
        example details
"""
        self.assertEqual(s, io.getvalue())
예제 #34
0
parser = argparse.ArgumentParser(description='Command Table Parser')
parser.add_argument('--commands',
                    metavar='N',
                    nargs='+',
                    help='Filter by first level command (OR)')
parser.add_argument('--params',
                    metavar='N',
                    nargs='+',
                    help='Filter by parameters (OR)')
args = parser.parse_args()
cmd_set_names = args.commands
param_names = args.params

# ignore the params passed in now so they aren't used by the cli
sys.argv = sys.argv[:1]
config = Configuration([])
cmd_table = config.get_command_table()
cmd_list = [
    cmd_name for cmd_name in cmd_table.keys()
    if cmd_set_names is None or cmd_name.split()[0] in cmd_set_names
]
results = []

if param_names:
    for name in cmd_list:
        cmd_name = [x for x in cmd_table.keys() if name == x][0]
        cmd_args = cmd_table[cmd_name]['arguments']
        match = False
        for arg in cmd_args:
            if match:
                break
예제 #35
0
    def test_generic_update(self):
        my_obj = {
            'prop': 'val',
            'list': [
                'a',
                'b',
                ['c', {'d': 'e'}]
                ]
            }

        def my_get():
            return my_obj

        def my_set(**kwargs): #pylint:disable=unused-argument
            return my_obj

        config = Configuration([])
        app = Application(config)

        register_generic_update('gencommand', my_get, my_set)

        app.execute('gencommand --set prop=val2'.split())
        self.assertEqual(my_obj['prop'], 'val2', 'set simple property')

        app.execute('gencommand --set prop=val3'.split())
        self.assertEqual(my_obj['prop'], 'val3', 'set simple property again')

        app.execute('gencommand --set list[0]=f'.split())
        self.assertEqual(my_obj['list'][0], 'f', 'set simple list element')

        app.execute('gencommand --set list[2][0]=g'.split())
        self.assertEqual(my_obj['list'][2][0], 'g', 'set nested list element')

        app.execute('gencommand --set list[2][1].d=h'.split())
        self.assertEqual(my_obj['list'][2][1]['d'], 'h', 'set nested dict element')

        app.execute('gencommand --set list[0]={} list[0].foo=bar'.split())
        self.assertEqual(my_obj['list'][0]['foo'], 'bar', 'replace nested scalar with new dict')

        app.execute('gencommand --set list[1]=[] --add list[1] key1=value1'
                    ' --set list[1][0].key2=value2'.split())
        self.assertEqual(my_obj['list'][1][0]['key1'], 'value1',
                         'replace nested scalar with new list with one value')
        self.assertEqual(my_obj['list'][1][0]['key2'], 'value2',
                         'add a second value to the new list')

        app.execute('gencommand --add list i=j k=l'.split())
        self.assertEqual(my_obj['list'][-1]['k'], 'l',
                         'add multiple values to a list at once (verify last element)')
        self.assertEqual(my_obj['list'][-1]['i'], 'j',
                         'add multiple values to a list at once (verify first element)')

        app.execute('gencommand --add list[-2] prop2=val2'.split())
        self.assertEqual(my_obj['list'][-2][-1]['prop2'], 'val2', 'add to list')
        app.execute('gencommand --add list[-2] prop3=val3'.split())
        self.assertEqual(my_obj['list'][-2][-1]['prop3'], 'val3',
                         'add to list again, should make seperate list elements')

        self.assertEqual(len(my_obj['list']), 4, 'pre-verify length of list')
        app.execute('gencommand --remove list -2'.split())
        self.assertEqual(len(my_obj['list']), 3, 'verify one item removed')
        app.execute('gencommand --remove list -1'.split())
        self.assertEqual(len(my_obj['list']), 2, 'verify another item removed')

        self.assertEqual('key1' in my_obj['list'][1][0], True, 'verify dict item')
        app.execute('gencommand --remove list[1][0].key1'.split())
        self.assertEqual('key1' not in my_obj['list'][1][0], True,
                         'verify dict item can be removed')