Esempio n. 1
0
    def test_out_list_valid_array_complex(self):
        output_producer = OutputProducer(formatter=format_list, file=self.io)
        output_producer.out(
            CommandResultItem([{
                'active': True,
                'id': '783yesdf'
            }, {
                'active': False,
                'id': '3hjnme32'
            }, {
                'active': False,
                'id': '23hiujbs'
            }]))
        self.assertEqual(
            util.normalize_newlines(self.io.getvalue()),
            util.normalize_newlines("""Active : True
Id     : 783yesdf

Active : False
Id     : 3hjnme32

Active : False
Id     : 23hiujbs


"""))
Esempio n. 2
0
    def execute(self, unexpanded_argv):
        argv = Application._expand_file_prefixed_files(unexpanded_argv)
        command_table = self.configuration.get_command_table()
        self.raise_event(self.COMMAND_TABLE_LOADED,
                         command_table=command_table)
        self.parser.load_command_table(command_table)
        self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser)

        if len(argv) == 0:
            az_subparser = self.parser.subparsers[tuple()]
            _help.show_welcome(az_subparser)
            log_telemetry('welcome')
            return None

        if argv[0].lower() == 'help':
            argv[0] = '--help'

        args = self.parser.parse_args(argv)
        self.raise_event(self.COMMAND_PARSER_PARSED,
                         command=args.command,
                         args=args)
        results = []
        for expanded_arg in _explode_list_args(args):
            self.session['command'] = expanded_arg.command
            try:
                _validate_arguments(expanded_arg)
            except:  # pylint: disable=bare-except
                err = sys.exc_info()[1]
                getattr(expanded_arg, '_parser',
                        self.parser).validation_error(str(err))

            # Consider - we are using any args that start with an underscore (_) as 'private'
            # arguments and remove them from the arguments that we pass to the actual function.
            # This does not feel quite right.
            params = dict([(key, value)
                           for key, value in expanded_arg.__dict__.items()
                           if not key.startswith('_')])
            params.pop('subcommand', None)
            params.pop('func', None)
            params.pop('command', None)
            log_telemetry(
                expanded_arg.command,
                log_type='pageview',
                output_type=self.configuration.output_format,
                parameters=[p for p in unexpanded_argv if p.startswith('-')])

            result = expanded_arg.func(params)
            result = todict(result)
            results.append(result)

        if len(results) == 1:
            results = results[0]

        event_data = {'result': results}
        self.raise_event(self.TRANSFORM_RESULT, event_data=event_data)
        self.raise_event(self.FILTER_RESULT, event_data=event_data)
        return CommandResultItem(
            event_data['result'],
            table_transformer=command_table[args.command].table_transformer,
            is_query_active=self.session['query_active'])
Esempio n. 3
0
    def test_out_json_byte_empty(self):
        output_producer = OutputProducer(formatter=format_json, file=self.io)
        output_producer.out(CommandResultItem({'active': True, 'contents': b''}))
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """{
  "active": true,
  "contents": ""
}
"""))
Esempio n. 4
0
    def test_out_table_list_of_lists(self):
        output_producer = OutputProducer(formatter=format_table, file=self.io)
        obj = [['a', 'b'], ['c', 'd']]
        output_producer.out(CommandResultItem(obj))
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """Column1    Column2
---------  ---------
a          b
c          d
"""))
Esempio n. 5
0
    def test_output_format_ordereddict_list_not_sorted(self):
        obj1 = OrderedDict()
        obj1['B'] = 1
        obj1['A'] = 2

        obj2 = OrderedDict()
        obj2['A'] = 3
        obj2['B'] = 4
        result = format_tsv(CommandResultItem([obj1, obj2]))
        self.assertEqual(result, '1\t2\n3\t4\n')
Esempio n. 6
0
    def test_out_table_no_query_no_transformer_order(self):
        output_producer = OutputProducer(formatter=format_table, file=self.io)
        obj = {'name': 'qwerty', 'val': '0b1f6472qwerty', 'active': True, 'sub': '0b1f6472'}
        result_item = CommandResultItem(obj, table_transformer=None, is_query_active=False)
        output_producer.out(result_item)
        # Should be alphabetical order as no table transformer and query is not active.
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """Active    Name    Sub       Val
--------  ------  --------  --------------
True      qwerty  0b1f6472  0b1f6472qwerty
"""))
Esempio n. 7
0
    def test_out_table(self):
        output_producer = OutputProducer(formatter=format_table, file=self.io)
        obj = OrderedDict()
        obj['active'] = True
        obj['val'] = '0b1f6472'
        output_producer.out(CommandResultItem(obj))
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """Active    Val
--------  --------
True      0b1f6472
"""))
Esempio n. 8
0
    def test_out_json_from_ordered_dict(self):
        """
        The JSON output when the input is OrderedDict should be serialized to JSON
        """
        output_producer = OutputProducer(formatter=format_json, file=self.io)
        output_producer.out(CommandResultItem(OrderedDict({'active': True, 'id': '0b1f6472'})))
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """{
  "active": true,
  "id": "0b1f6472"
}
"""))
Esempio n. 9
0
    def test_out_table_no_query_yes_jmespath_table_transformer(self):
        output_producer = OutputProducer(formatter=format_table, file=self.io)
        obj = {'name': 'qwerty', 'val': '0b1f6472qwerty', 'active': True, 'sub': '0b1f6472'}

        result_item = CommandResultItem(obj, table_transformer='{Name:name, Val:val, Active:active}', is_query_active=False)
        output_producer.out(result_item)
        # Should be table transformer order
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """Name    Val             Active
------  --------------  --------
qwerty  0b1f6472qwerty  True
"""))
Esempio n. 10
0
    def test_out_table_complex_obj(self):
        output_producer = OutputProducer(formatter=format_table, file=self.io)
        obj = OrderedDict()
        obj['name'] = 'qwerty'
        obj['val'] = '0b1f6472qwerty'
        obj['sub'] = {'1'}
        result_item = CommandResultItem(obj)
        output_producer.out(result_item)
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """Name    Val
------  --------------
qwerty  0b1f6472qwerty
"""))
Esempio n. 11
0
    def test_out_list_valid_none_val(self):
        output_producer = OutputProducer(formatter=format_list, file=self.io)
        output_producer.out(
            CommandResultItem({
                'active': None,
                'id': '0b1f6472'
            }))
        self.assertEqual(
            util.normalize_newlines(self.io.getvalue()),
            util.normalize_newlines("""Active : None
Id     : 0b1f6472


"""))
Esempio n. 12
0
    def test_out_list_valid_caps(self):
        output_producer = OutputProducer(formatter=format_list, file=self.io)
        output_producer.out(
            CommandResultItem({
                'active': True,
                'TESTStuff': 'blah'
            }))
        self.assertEqual(
            util.normalize_newlines(self.io.getvalue()),
            util.normalize_newlines("""Test Stuff : blah
Active     : True


"""))
Esempio n. 13
0
    def test_out_table_no_query_yes_transformer_order(self):
        output_producer = OutputProducer(formatter=format_table, file=self.io)
        obj = {'name': 'qwerty', 'val': '0b1f6472qwerty', 'active': True, 'sub': '0b1f6472'}

        def transformer(r):
            return OrderedDict([('Name', r['name']), ('Val', r['val']),
                                ('Active', r['active']), ('Sub', r['sub'])])

        result_item = CommandResultItem(obj, table_transformer=transformer, is_query_active=False)
        output_producer.out(result_item)
        # Should be table transformer order
        self.assertEqual(util.normalize_newlines(self.io.getvalue()), util.normalize_newlines(
            """Name    Val             Active    Sub
------  --------------  --------  --------
qwerty  0b1f6472qwerty  True      0b1f6472
"""))
Esempio n. 14
0
    def test_out_list_valid_str_array(self):
        output_producer = OutputProducer(formatter=format_list, file=self.io)
        output_producer.out(
            CommandResultItem(['location', 'id', 'host', 'server']))
        self.assertEqual(
            util.normalize_newlines(self.io.getvalue()),
            util.normalize_newlines("""location

id

host

server


"""))
Esempio n. 15
0
    def test_out_list_valid_complex_array(self):
        output_producer = OutputProducer(formatter=format_list, file=self.io)
        output_producer.out(
            CommandResultItem({
                'active': True,
                'id': '0b1f6472',
                'myarray': ['1', '2', '3', '4']
            }))
        self.assertEqual(
            util.normalize_newlines(self.io.getvalue()),
            util.normalize_newlines("""Active  : True
Id      : 0b1f6472
Myarray :
   1
   2
   3
   4


"""))
Esempio n. 16
0
    def execute(self, unexpanded_argv):  # pylint: disable=too-many-statements
        argv = Application._expand_file_prefixed_files(unexpanded_argv)
        command_table = self.configuration.get_command_table(argv)
        self.raise_event(self.COMMAND_TABLE_LOADED, command_table=command_table)
        self.parser.load_command_table(command_table)
        self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser)

        if not argv:
            enable_autocomplete(self.parser)
            az_subparser = self.parser.subparsers[tuple()]
            _help.show_welcome(az_subparser)

            # TODO: Question, is this needed?
            telemetry.set_command_details('az')
            telemetry.set_success(summary='welcome')

            return None

        if argv[0].lower() == 'help':
            argv[0] = '--help'

        # Rudimentary parsing to get the command
        nouns = []
        for i, current in enumerate(argv):
            try:
                if current[0] == '-':
                    break
            except IndexError:
                pass
            argv[i] = current.lower()
            nouns.append(argv[i])

        command = ' '.join(nouns)

        if argv[-1] in ('--help', '-h') or command in command_table:
            self.configuration.load_params(command)
            self.raise_event(self.COMMAND_TABLE_PARAMS_LOADED, command_table=command_table)
            self.parser.load_command_table(command_table)

        if self.session['completer_active']:
            enable_autocomplete(self.parser)

        self.raise_event(self.COMMAND_PARSER_PARSING, argv=argv)
        args = self.parser.parse_args(argv)

        self.raise_event(self.COMMAND_PARSER_PARSED, command=args.command, args=args)
        results = []
        for expanded_arg in _explode_list_args(args):
            self.session['command'] = expanded_arg.command
            try:
                _validate_arguments(expanded_arg)
            except CLIError:
                raise
            except:  # pylint: disable=bare-except
                err = sys.exc_info()[1]
                getattr(expanded_arg, '_parser', self.parser).validation_error(str(err))

            # Consider - we are using any args that start with an underscore (_) as 'private'
            # arguments and remove them from the arguments that we pass to the actual function.
            # This does not feel quite right.
            params = dict([(key, value)
                           for key, value in expanded_arg.__dict__.items()
                           if not key.startswith('_')])
            params.pop('subcommand', None)
            params.pop('func', None)
            params.pop('command', None)

            telemetry.set_command_details(expanded_arg.command,
                                          self.configuration.output_format,
                                          [p for p in unexpanded_argv if p.startswith('-')])

            result = expanded_arg.func(params)
            result = todict(result)
            results.append(result)

        if len(results) == 1:
            results = results[0]

        event_data = {'result': results}
        self.raise_event(self.TRANSFORM_RESULT, event_data=event_data)
        self.raise_event(self.FILTER_RESULT, event_data=event_data)

        return CommandResultItem(event_data['result'],
                                 table_transformer=command_table[args.command].table_transformer,
                                 is_query_active=self.session['query_active'])
Esempio n. 17
0
 def test_out_boolean_valid(self):
     output_producer = OutputProducer(formatter=format_list, file=self.io)
     output_producer.out(CommandResultItem(True))
     self.assertEqual(util.normalize_newlines(self.io.getvalue()),
                      util.normalize_newlines("""True\n\n\n"""))
Esempio n. 18
0
 def test_output_format_ordereddict_not_sorted(self):
     obj = OrderedDict()
     obj['B'] = 1
     obj['A'] = 2
     result = format_tsv(CommandResultItem(obj))
     self.assertEqual(result, '1\t2\n')
Esempio n. 19
0
 def test_output_format_dict_sort(self):
     obj = {}
     obj['B'] = 1
     obj['A'] = 2
     result = format_tsv(CommandResultItem(obj))
     self.assertEqual(result, '2\t1\n')