def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        if parsed_args.version:
            data = client.plugins.get_version_details(
                parsed_args.plugin, parsed_args.version).to_dict()

            processes = data.pop('node_processes')
            for k, v in processes.items():
                processes[k] = osc_utils.format_list(v)
            data['required_image_tags'] = osc_utils.format_list(
                data['required_image_tags'])

            data = utils.prepare_data(
                data, ['required_image_tags', 'name', 'description', 'title'])

            data = zip(*sorted(data.items()) + [('', ''), (
                'Service:', 'Available processes:'), ('', '')] + sorted(
                processes.items()))
        else:
            data = client.plugins.get(parsed_args.plugin).to_dict()
            data['versions'] = osc_utils.format_list(data['versions'])
            data = utils.prepare_data(
                data, ['versions', 'name', 'description', 'title'])
            data = self.dict2columns(data)

        return data
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        if parsed_args.plugin_version:
            data = client.plugins.get_version_details(
                parsed_args.plugin, parsed_args.plugin_version).to_dict()

            processes = data.pop('node_processes')
            for k, v in processes.items():
                processes[k] = osc_utils.format_list(v)
            data['required_image_tags'] = osc_utils.format_list(
                data['required_image_tags'])

            data = utils.prepare_data(
                data, ['required_image_tags', 'name', 'description', 'title'])

            data = zip(
                *sorted(data.items()) +
                [('', ''), ('Service:', 'Available processes:'), ('', '')] +
                sorted(processes.items()))
        else:
            data = client.plugins.get(parsed_args.plugin).to_dict()
            data['versions'] = osc_utils.format_list(data['versions'])
            data = utils.prepare_data(
                data, ['versions', 'name', 'description', 'title'])
            data = self.dict2columns(data)

        return data
Exemple #3
0
class TestServerGroup(compute_fakes.TestComputev2):

    fake_server_group = compute_fakes.FakeServerGroup.create_one_server_group()

    columns = (
        'id',
        'members',
        'name',
        'policies',
        'project_id',
        'user_id',
    )

    data = (
        fake_server_group.id,
        utils.format_list(fake_server_group.members),
        fake_server_group.name,
        utils.format_list(fake_server_group.policies),
        fake_server_group.project_id,
        fake_server_group.user_id,
    )

    def setUp(self):
        super(TestServerGroup, self).setUp()

        # Get a shortcut to the ServerGroupsManager Mock
        self.server_groups_mock = self.app.client_manager.compute.server_groups
        self.server_groups_mock.reset_mock()
Exemple #4
0
def _format_image(image):
    """Format an image to make it more consistent with OSC operations. """

    info = {}
    properties = {}

    # the only fields we're not including is "links", "tags" and the properties
    fields_to_show = ['status', 'name', 'container_format', 'created_at',
                      'size', 'disk_format', 'updated_at', 'visibility',
                      'min_disk', 'protected', 'id', 'file', 'checksum',
                      'owner', 'virtual_size', 'min_ram', 'schema']

    # split out the usual key and the properties which are top-level
    for key in six.iterkeys(image):
        if key in fields_to_show:
            info[key] = image.get(key)
        elif key == 'tags':
            continue  # handle this later
        else:
            properties[key] = image.get(key)

    # format the tags if they are there
    info['tags'] = utils.format_list(image.get('tags'))

    # add properties back into the dictionary as a top-level key
    if properties:
        info['properties'] = utils.format_dict(properties)

    return info
def _format_image(image):
    """Format an image to make it more consistent with OSC operations. """

    info = {}
    properties = {}

    # the only fields we're not including is "links", "tags" and the properties
    fields_to_show = ['status', 'name', 'container_format', 'created_at',
                      'size', 'disk_format', 'updated_at', 'visibility',
                      'min_disk', 'protected', 'id', 'file', 'checksum',
                      'owner', 'virtual_size', 'min_ram', 'schema']

    # split out the usual key and the properties which are top-level
    for key in six.iterkeys(image):
        if key in fields_to_show:
            info[key] = image.get(key)
        elif key == 'tags':
            continue  # handle this later
        else:
            properties[key] = image.get(key)

    # format the tags if they are there
    info['tags'] = utils.format_list(image.get('tags'))

    # add properties back into the dictionary as a top-level key
    if properties:
        info['properties'] = utils.format_dict(properties)

    return info
Exemple #6
0
class TestShowNetwork(TestNetwork):

    # The network to set.
    _network = network_fakes.FakeNetwork.create_one_network()

    columns = (
        'admin_state_up',
        'id',
        'name',
        'project_id',
        'router_external',
        'status',
        'subnets',
    )

    data = (
        network._format_admin_state(_network.admin_state_up),
        _network.id,
        _network.name,
        _network.project_id,
        network._format_router_external(_network.router_external),
        _network.status,
        utils.format_list(_network.subnets),
    )

    def setUp(self):
        super(TestShowNetwork, self).setUp()

        self.network.find_network = mock.Mock(return_value=self._network)

        # Get the command object to test
        self.cmd = network.ShowNetwork(self.app, self.namespace)

    def test_show_no_options(self):
        arglist = []
        verifylist = []

        try:
            # Missing required args should bail here
            self.check_parser(self.cmd, arglist, verifylist)
        except tests_utils.ParserException:
            pass

    def test_show_all_options(self):
        arglist = [
            self._network.name,
        ]
        verifylist = [
            ('identifier', self._network.name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.find_network.assert_called_with(self._network.name,
                                                     ignore_missing=False)

        self.assertEqual(tuple(self.columns), columns)
        self.assertEqual(list(self.data), list(data))
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        data = client.plugins.get(parsed_args.plugin).to_dict()
        data["versions"] = osc_utils.format_list(data["versions"])

        return self.dict2columns(data)
Exemple #8
0
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        data = client.plugins.get(parsed_args.plugin).to_dict()
        data['versions'] = utils.format_list(data['versions'])

        return self.dict2columns(data)
def _format_ngt_output(data):
    data['node_processes'] = osc_utils.format_list(data['node_processes'])
    data['version'] = data.pop('hadoop_version')
    if data['volumes_per_node'] == 0:
        del data['volume_local_to_instance']
        del data['volume_mount_prefix']
        del data['volume_type'],
        del data['volumes_availability_zone']
        del data['volumes_size']
def _format_ngt_output(data):
    data['node_processes'] = osc_utils.format_list(data['node_processes'])
    data['version'] = data.pop('hadoop_version')
    if data['volumes_per_node'] == 0:
        del data['volume_local_to_instance']
        del data['volume_mount_prefix']
        del data['volume_type'],
        del data['volumes_availability_zone']
        del data['volumes_size']
Exemple #11
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity
        idp = utils.find_resource(
            identity_client.federation.identity_providers,
            parsed_args.identity_provider)

        idp._info.pop('links', None)
        remote_ids = utils.format_list(idp._info.pop('remote_ids', []))
        idp._info['remote_ids'] = remote_ids
        return zip(*sorted(six.iteritems(idp._info)))
Exemple #12
0
class TestShowIPAvailability(TestIPAvailability):

    _ip_availability = \
        network_fakes.FakeIPAvailability.create_one_ip_availability()

    columns = (
        'network_id',
        'network_name',
        'project_id',
        'subnet_ip_availability',
        'total_ips',
        'used_ips',
    )
    data = (
        _ip_availability.network_id,
        _ip_availability.network_name,
        _ip_availability.tenant_id,
        osc_utils.format_list(
            _ip_availability.subnet_ip_availability),
        _ip_availability.total_ips,
        _ip_availability.used_ips,
    )

    def setUp(self):
        super(TestShowIPAvailability, self).setUp()

        self.network.find_network_ip_availability = mock.Mock(
            return_value=self._ip_availability)

        # Get the command object to test
        self.cmd = ip_availability.ShowIPAvailability(
            self.app, self.namespace)

    def test_show_no_option(self):
        arglist = []
        verifylist = []

        self.assertRaises(tests_utils.ParserException,
                          self.check_parser, self.cmd, arglist, verifylist)

    def test_show_all_options(self):
        arglist = [
            self._ip_availability.network_name,
        ]
        verifylist = [
            ('network', self._ip_availability.network_name)
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)
        self.network.find_network_ip_availability.assert_called_once_with(
            self._ip_availability.network_name,
            ignore_missing=False)

        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        data = utils.get_resource(
            client.images, parsed_args.image).to_dict()
        data['tags'] = osc_utils.format_list(data['tags'])

        data = utils.prepare_data(data, IMAGE_FIELDS)

        return self.dict2columns(data)
    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume
        qos_spec = utils.find_resource(volume_client.qos_specs, parsed_args.qos_spec)

        qos_associations = volume_client.qos_specs.get_associations(qos_spec)
        if qos_associations:
            associations = [association.name for association in qos_associations]
            qos_spec._info.update({"associations": utils.format_list(associations)})
        qos_spec._info.update({"specs": utils.format_dict(qos_spec.specs)})

        return zip(*sorted(six.iteritems(qos_spec._info)))
Exemple #15
0
 def image_data(self, image):
     datalist = (
         image['id'],
         image['name'],
         image['owner'],
         image['protected'],
         'active',
         common_utils.format_list(image.get('tags')),
         image['visibility'],
     )
     return datalist
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        data = utils.get_resource(
            client.images, parsed_args.image).to_dict()
        data['tags'] = osc_utils.format_list(data['tags'])

        fields = ['name', 'id', 'username', 'tags', 'status', 'description']
        data = utils.prepare_data(data, fields)

        return self.dict2columns(data)
    def _get_common_cols_data(self, fake_port):
        columns = (
            'admin_state_up',
            'allowed_address_pairs',
            'binding_host_id',
            'binding_profile',
            'binding_vif_details',
            'binding_vif_type',
            'binding_vnic_type',
            'device_id',
            'device_owner',
            'dns_assignment',
            'dns_name',
            'extra_dhcp_opts',
            'fixed_ips',
            'id',
            'mac_address',
            'name',
            'network_id',
            'port_security_enabled',
            'project_id',
            'security_groups',
            'status',
        )

        data = (
            port._format_admin_state(fake_port.admin_state_up),
            utils.format_list_of_dicts(fake_port.allowed_address_pairs),
            fake_port.binding_host_id,
            utils.format_dict(fake_port.binding_profile),
            utils.format_dict(fake_port.binding_vif_details),
            fake_port.binding_vif_type,
            fake_port.binding_vnic_type,
            fake_port.device_id,
            fake_port.device_owner,
            utils.format_list_of_dicts(fake_port.dns_assignment),
            fake_port.dns_name,
            utils.format_list_of_dicts(fake_port.extra_dhcp_opts),
            utils.format_list_of_dicts(fake_port.fixed_ips),
            fake_port.id,
            fake_port.mac_address,
            fake_port.name,
            fake_port.network_id,
            fake_port.port_security_enabled,
            fake_port.project_id,
            utils.format_list(fake_port.security_groups),
            fake_port.status,
        )

        return columns, data
    def _get_common_cols_data(self, fake_port):
        columns = (
            'admin_state_up',
            'allowed_address_pairs',
            'binding_host_id',
            'binding_profile',
            'binding_vif_details',
            'binding_vif_type',
            'binding_vnic_type',
            'device_id',
            'device_owner',
            'dns_assignment',
            'dns_name',
            'extra_dhcp_opts',
            'fixed_ips',
            'id',
            'mac_address',
            'name',
            'network_id',
            'port_security_enabled',
            'project_id',
            'security_groups',
            'status',
        )

        data = (
            port._format_admin_state(fake_port.admin_state_up),
            utils.format_list_of_dicts(fake_port.allowed_address_pairs),
            fake_port.binding_host_id,
            utils.format_dict(fake_port.binding_profile),
            utils.format_dict(fake_port.binding_vif_details),
            fake_port.binding_vif_type,
            fake_port.binding_vnic_type,
            fake_port.device_id,
            fake_port.device_owner,
            utils.format_list_of_dicts(fake_port.dns_assignment),
            fake_port.dns_name,
            utils.format_list_of_dicts(fake_port.extra_dhcp_opts),
            utils.format_list_of_dicts(fake_port.fixed_ips),
            fake_port.id,
            fake_port.mac_address,
            fake_port.name,
            fake_port.network_id,
            fake_port.port_security_enabled,
            fake_port.project_id,
            utils.format_list(fake_port.security_groups),
            fake_port.status,
        )

        return columns, data
def _prep_network_detail(net):
    """Prepare network object for output"""

    if 'subnets' in net:
        net['subnets'] = utils.format_list(net['subnets'])
    if 'admin_state_up' in net:
        net['state'] = 'UP' if net['admin_state_up'] else 'DOWN'
        net.pop('admin_state_up')
    if 'router:external' in net:
        net['router_type'] = 'External' if net['router:external'] \
            else 'Internal'
        net.pop('router:external')
    if 'tenant_id' in net:
        net['project_id'] = net.pop('tenant_id')
    return net
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        description = parsed_args.description or ''
        data = client.images.update_image(
            parsed_args.image, user_name=parsed_args.username,
            desc=description).to_dict()

        data['tags'] = osc_utils.format_list(data['tags'])

        fields = ['name', 'id', 'username', 'tags', 'status', 'description']
        data = utils.prepare_data(data, fields)

        return self.dict2columns(data)
    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume
        qos_spec = utils.find_resource(volume_client.qos_specs,
                                       parsed_args.qos_spec)

        qos_associations = volume_client.qos_specs.get_associations(qos_spec)
        if qos_associations:
            associations = [
                association.name for association in qos_associations
            ]
            qos_spec._info.update(
                {'associations': utils.format_list(associations)})
        qos_spec._info.update({'specs': utils.format_dict(qos_spec.specs)})

        return zip(*sorted(six.iteritems(qos_spec._info)))
Exemple #22
0
def _prep_network_detail(net):
    """Prepare network object for output"""

    if 'subnets' in net:
        net['subnets'] = utils.format_list(net['subnets'])
    if 'admin_state_up' in net:
        net['state'] = 'UP' if net['admin_state_up'] else 'DOWN'
        net.pop('admin_state_up')
    if 'router:external' in net:
        net['router_type'] = 'External' if net['router:external'] \
            else 'Internal'
        net.pop('router:external')
    if 'tenant_id' in net:
        net['project_id'] = net.pop('tenant_id')
    return net
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)
        volume_client = self.app.client_manager.volume
        qos_specs = utils.find_resource(volume_client.qos_specs,
                                        parsed_args.qos_specs)

        qos_associations = volume_client.qos_specs.get_associations(qos_specs)
        if qos_associations:
            associations = [association.name
                            for association in qos_associations]
            qos_specs._info.update({
                'associations': utils.format_list(associations)
            })
        qos_specs._info.update({'specs': utils.format_dict(qos_specs.specs)})

        return zip(*sorted(six.iteritems(qos_specs._info)))
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing
        image_client = self.app.client_manager.image

        image_id = osc_utils.find_resource(
            image_client.images, parsed_args.image).id

        data = client.images.update_image(
            image_id, user_name=parsed_args.username,
            desc=parsed_args.description).image

        data['tags'] = osc_utils.format_list(data['tags'])

        data = utils.prepare_data(data, IMAGE_FIELDS)

        return self.dict2columns(data)
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing

        image = utils.get_resource(client.images, parsed_args.image)

        if parsed_args.all:
            data = client.images.update_tags(image.id, []).to_dict()
        else:
            parsed_args.tags = parsed_args.tags or []
            new_tags = list(set(image.tags) - set(parsed_args.tags))
            data = client.images.update_tags(image.id, new_tags).to_dict()

        data['tags'] = osc_utils.format_list(data['tags'])

        data = utils.prepare_data(data, IMAGE_FIELDS)

        return self.dict2columns(data)
 def get_parser(self, prog_name):
     parser = super(CreateQos, self).get_parser(prog_name)
     parser.add_argument("name", metavar="<name>", help="New QoS specification name")
     consumer_choices = ["front-end", "back-end", "both"]
     parser.add_argument(
         "--consumer",
         metavar="<consumer>",
         choices=consumer_choices,
         default="both",
         help="Consumer of the QoS. Valid consumers: %s "
         "(defaults to 'both')" % utils.format_list(consumer_choices),
     )
     parser.add_argument(
         "--property",
         metavar="<key=value>",
         action=parseractions.KeyValueAction,
         help="Set a QoS specification property " "(repeat option to set multiple properties)",
     )
     return parser
    def get_image_data(image=None):
        """Get the image data from a faked image object.

        :param image:
            A FakeResource objects faking image
        :return
            A tuple which may include the following values:
            ('image-123', 'image-foo', 'admin', False, 'public', 'bar, baz')
        """
        data_list = []
        if image is not None:
            for x in sorted(FakeImage.get_image_info(image).keys()):
                if x == 'tags':
                    # The 'tags' should be format_list
                    data_list.append(
                        common_utils.format_list(getattr(image, x)))
                else:
                    data_list.append(getattr(image, x))
        return tuple(data_list)
    def get_image_data(image=None):
        """Get the image data from a faked image object.

        :param image:
            A FakeResource objects faking image
        :return
            A tuple which may include the following values:
            ('image-123', 'image-foo', 'admin', False, 'public', 'bar, baz')
        """
        data_list = []
        if image is not None:
            for x in sorted(FakeImage.get_image_info(image).keys()):
                if x == 'tags':
                    # The 'tags' should be format_list
                    data_list.append(
                        common_utils.format_list(getattr(image, x)))
                else:
                    data_list.append(getattr(image, x))
        return tuple(data_list)
Exemple #29
0
    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute
        info = {}
        info.update(
            utils.find_resource(
                compute_client.security_groups,
                parsed_args.group,
            )._info)
        rules = []
        for r in info['rules']:
            rules.append(utils.format_dict(_xform_security_group_rule(r)))

        # Format rules into a list of strings
        info.update({'rules': utils.format_list(rules, separator='\n')})
        # Map 'tenant_id' column to 'project_id'
        info.update({'project_id': info.pop('tenant_id')})

        return zip(*sorted(six.iteritems(info)))
    def test_image_list_long_option(self):
        arglist = [
            '--long',
        ]
        verifylist = [
            ('long', True),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # In base command class Lister in cliff, abstract method take_action()
        # returns a tuple containing the column names and an iterable
        # containing the data to be listed.
        columns, data = self.cmd.take_action(parsed_args)
        self.api_mock.image_list.assert_called_with()

        collist = (
            'ID',
            'Name',
            'Disk Format',
            'Container Format',
            'Size',
            'Status',
            'Visibility',
            'Protected',
            'Project',
            'Tags',
        )

        self.assertEqual(collist, columns)
        datalist = ((
            self._image.id,
            self._image.name,
            '',
            '',
            '',
            '',
            self._image.visibility,
            self._image.protected,
            self._image.owner,
            common_utils.format_list(self._image.tags),
        ), )
        self.assertEqual(datalist, tuple(data))
Exemple #31
0
    def test_image_list_long_option(self):
        arglist = [
            '--long',
        ]
        verifylist = [
            ('long', True),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # In base command class Lister in cliff, abstract method take_action()
        # returns a tuple containing the column names and an iterable
        # containing the data to be listed.
        columns, data = self.cmd.take_action(parsed_args)
        self.api_mock.image_list.assert_called_with()

        collist = (
            'ID',
            'Name',
            'Disk Format',
            'Container Format',
            'Size',
            'Status',
            'Visibility',
            'Protected',
            'Project',
            'Tags',
        )

        self.assertEqual(collist, columns)
        datalist = ((
            self._image.id,
            self._image.name,
            '',
            '',
            '',
            '',
            self._image.visibility,
            self._image.protected,
            self._image.owner,
            common_utils.format_list(self._image.tags),
        ), )
        self.assertEqual(datalist, tuple(data))
Exemple #32
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity
        if parsed_args.remote_id_file:
            file_content = utils.read_blob_file_contents(
                parsed_args.remote_id_file)
            remote_ids = file_content.splitlines()
            remote_ids = list(map(str.strip, remote_ids))
        else:
            remote_ids = (parsed_args.remote_id
                          if parsed_args.remote_id else None)
        idp = identity_client.federation.identity_providers.create(
            id=parsed_args.identity_provider_id,
            remote_ids=remote_ids,
            description=parsed_args.description,
            enabled=parsed_args.enabled)

        idp._info.pop('links', None)
        remote_ids = utils.format_list(idp._info.pop('remote_ids', []))
        idp._info['remote_ids'] = remote_ids
        return zip(*sorted(six.iteritems(idp._info)))
    def get_volume_data(volume=None):
        """Get the volume data from a faked volume object.

        :param volume:
            A FakeResource objects faking volume
        :return
            A tuple which may include the following values:
            ('ce26708d', 'fake_volume', 'fake description', 'available',
             20, 'fake_lvmdriver-1', "Alpha='a', Beta='b', Gamma='g'",
             1, 'nova', [{'device': '/dev/ice', 'server_id': '1233'}])
        """
        data_list = []
        if volume is not None:
            for x in sorted(volume.keys()):
                if x == 'tags':
                    # The 'tags' should be format_list
                    data_list.append(
                        common_utils.format_list(volume.info.get(x)))
                else:
                    data_list.append(volume.info.get(x))
        return tuple(data_list)
    def take_action(self, parsed_args):
        cm = self.app.command_manager
        groups = cm.get_command_groups()
        groups = sorted(groups)
        columns = ('Command Group', 'Commands')

        commands = []
        for group in groups:
            command_names = cm.get_command_names(group)
            command_names = sorted(command_names)

            if command_names != []:

                # TODO(bapalm): Fix this when cliff properly supports
                # handling the detection rather than using the hard-code below.
                if parsed_args.formatter == 'table':
                    command_names = utils.format_list(command_names, "\n")

                commands.append((group, command_names))

        return (columns, commands)
Exemple #35
0
    def take_action(self, parsed_args):
        cm = self.app.command_manager
        groups = cm.get_command_groups()
        groups = sorted(groups)
        columns = ('Command Group', 'Commands')

        commands = []
        for group in groups:
            command_names = cm.get_command_names(group)
            command_names = sorted(command_names)

            if command_names != []:

                # TODO(bapalm): Fix this when cliff properly supports
                # handling the detection rather than using the hard-code below.
                if parsed_args.formatter == 'table':
                    command_names = utils.format_list(command_names, "\n")

                commands.append((group, command_names))

        return (columns, commands)
    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute
        info = {}
        info.update(utils.find_resource(
            compute_client.security_groups,
            parsed_args.group,
        )._info)
        rules = []
        for r in info['rules']:
            rules.append(utils.format_dict(_xform_security_group_rule(r)))

        # Format rules into a list of strings
        info.update(
            {'rules': utils.format_list(rules, separator='\n')}
        )
        # Map 'tenant_id' column to 'project_id'
        info.update(
            {'project_id': info.pop('tenant_id')}
        )

        return zip(*sorted(six.iteritems(info)))
 def get_parser(self, prog_name):
     parser = super(CreateQos, self).get_parser(prog_name)
     parser.add_argument(
         'name',
         metavar='<name>',
         help='New QoS specification name',
     )
     consumer_choices = ['front-end', 'back-end', 'both']
     parser.add_argument('--consumer',
                         metavar='<consumer>',
                         choices=consumer_choices,
                         default='both',
                         help='Consumer of the QoS. Valid consumers: %s '
                         "(defaults to 'both')" %
                         utils.format_list(consumer_choices))
     parser.add_argument(
         '--property',
         metavar='<key=value>',
         action=parseractions.KeyValueAction,
         help='Set a QoS specification property '
         '(repeat option to set multiple properties)',
     )
     return parser
 def get_parser(self, prog_name):
     parser = super(CreateQos, self).get_parser(prog_name)
     parser.add_argument(
         'name',
         metavar='<name>',
         help='New QoS specification name',
     )
     consumer_choices = ['front-end', 'back-end', 'both']
     parser.add_argument(
         '--consumer',
         metavar='<consumer>',
         choices=consumer_choices,
         default='both',
         help='Consumer of the QoS. Valid consumers: %s '
              "(defaults to 'both')" % utils.format_list(consumer_choices)
     )
     parser.add_argument(
         '--property',
         metavar='<key=value>',
         action=parseractions.KeyValueAction,
         help='Set a QoS specification property '
              '(repeat option to set multiple properties)',
     )
     return parser
Exemple #39
0
class TestCreateNetworkIdentityV3(TestNetwork):

    # The new network created.
    _network = network_fakes.FakeNetwork.create_one_network(
        attrs={'tenant_id': identity_fakes_v3.project_id})

    columns = (
        'admin_state_up',
        'id',
        'name',
        'project_id',
        'router_external',
        'status',
        'subnets',
    )

    data = (
        network._format_admin_state(_network.admin_state_up),
        _network.id,
        _network.name,
        _network.project_id,
        network._format_router_external(_network.router_external),
        _network.status,
        utils.format_list(_network.subnets),
    )

    def setUp(self):
        super(TestCreateNetworkIdentityV3, self).setUp()

        self.network.create_network = mock.Mock(return_value=self._network)

        # Get the command object to test
        self.cmd = network.CreateNetwork(self.app, self.namespace)

        # Set identity client v3. And get a shortcut to Identity client.
        identity_client = identity_fakes_v3.FakeIdentityv3Client(
            endpoint=fakes.AUTH_URL,
            token=fakes.AUTH_TOKEN,
        )
        self.app.client_manager.identity = identity_client
        self.identity = self.app.client_manager.identity

        # Get a shortcut to the ProjectManager Mock
        self.projects_mock = self.identity.projects
        self.projects_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.PROJECT),
            loaded=True,
        )

        # Get a shortcut to the DomainManager Mock
        self.domains_mock = self.identity.domains
        self.domains_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.DOMAIN),
            loaded=True,
        )

    def test_create_no_options(self):
        arglist = []
        verifylist = []

        try:
            # Missing required args should bail here
            self.check_parser(self.cmd, arglist, verifylist)
        except tests_utils.ParserException:
            pass

    def test_create_default_options(self):
        arglist = [
            self._network.name,
        ]
        verifylist = [
            ('name', self._network.name),
            ('admin_state', True),
            ('shared', None),
            ('project', None),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.create_network.assert_called_with(
            **{
                'admin_state_up': True,
                'name': self._network.name,
            })
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)

    def test_create_all_options(self):
        arglist = [
            "--disable",
            "--share",
            "--project",
            identity_fakes_v3.project_name,
            "--project-domain",
            identity_fakes_v3.domain_name,
            self._network.name,
        ]
        verifylist = [
            ('admin_state', False),
            ('shared', True),
            ('project', identity_fakes_v3.project_name),
            ('project_domain', identity_fakes_v3.domain_name),
            ('name', self._network.name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = (self.cmd.take_action(parsed_args))

        self.network.create_network.assert_called_with(
            **{
                'admin_state_up': False,
                'name': self._network.name,
                'shared': True,
                'tenant_id': identity_fakes_v3.project_id,
            })
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)

    def test_create_other_options(self):
        arglist = [
            "--enable",
            "--no-share",
            self._network.name,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', False),
            ('name', self._network.name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.create_network.assert_called_with(**{
            'admin_state_up': True,
            'name': self._network.name,
            'shared': False,
        })
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)
 def test_format_list(self):
     expected = "a, b, c"
     self.assertEqual(expected, utils.format_list(["a", "b", "c"]))
     self.assertEqual(expected, utils.format_list(["c", "b", "a"]))
def filters(data):
    if 'subnets' in data:
        data['subnets'] = utils.format_list(data['subnets'])
    return data
def _format_compute_security_group_rules(sg_rules):
    rules = []
    for sg_rule in sg_rules:
        rules.append(_format_compute_security_group_rule(sg_rule))
    return utils.format_list(rules, separator='\n')
Exemple #43
0
class TestServerGroupList(TestServerGroup):

    list_columns = (
        'ID',
        'Name',
        'Policies',
    )

    list_columns_long = (
        'ID',
        'Name',
        'Policies',
        'Members',
        'Project Id',
        'User Id',
    )

    list_data = ((
        TestServerGroup.fake_server_group.id,
        TestServerGroup.fake_server_group.name,
        utils.format_list(TestServerGroup.fake_server_group.policies),
    ),)

    list_data_long = ((
        TestServerGroup.fake_server_group.id,
        TestServerGroup.fake_server_group.name,
        utils.format_list(TestServerGroup.fake_server_group.policies),
        utils.format_list(TestServerGroup.fake_server_group.members),
        TestServerGroup.fake_server_group.project_id,
        TestServerGroup.fake_server_group.user_id,
    ),)

    def setUp(self):
        super(TestServerGroupList, self).setUp()

        self.server_groups_mock.list.return_value = [self.fake_server_group]
        self.cmd = server_group.ListServerGroup(self.app, None)

    def test_server_group_list(self):
        arglist = []
        verifylist = [
            ('all_projects', False),
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)
        self.server_groups_mock.list.assert_called_once_with(False)

        self.assertEqual(self.list_columns, columns)
        self.assertEqual(self.list_data, tuple(data))

    def test_server_group_list_with_all_projects_and_long(self):
        arglist = [
            '--all-projects',
            '--long',
        ]
        verifylist = [
            ('all_projects', True),
            ('long', True),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)
        self.server_groups_mock.list.assert_called_once_with(True)

        self.assertEqual(self.list_columns_long, columns)
        self.assertEqual(self.list_data_long, tuple(data))
def _format_ct_output(data):
    data['version'] = data.pop('hadoop_version')
    data['node_groups'] = _format_node_groups_list(data['node_groups'])
    data['anti_affinity'] = osc_utils.format_list(data['anti_affinity'])
Exemple #45
0
class TestShowSubnet(TestSubnet):
    # The subnets to be shown
    _subnet = network_fakes.FakeSubnet.create_one_subnet()

    columns = (
        'allocation_pools',
        'cidr',
        'dns_nameservers',
        'enable_dhcp',
        'gateway_ip',
        'host_routes',
        'id',
        'ip_version',
        'ipv6_address_mode',
        'ipv6_ra_mode',
        'name',
        'network_id',
        'project_id',
        'subnetpool_id',
    )

    data = (
        subnet_v2._format_allocation_pools(_subnet.allocation_pools),
        _subnet.cidr,
        utils.format_list(_subnet.dns_nameservers),
        _subnet.enable_dhcp,
        _subnet.gateway_ip,
        utils.format_list(_subnet.host_routes),
        _subnet.id,
        _subnet.ip_version,
        _subnet.ipv6_address_mode,
        _subnet.ipv6_ra_mode,
        _subnet.name,
        _subnet.network_id,
        _subnet.tenant_id,
        _subnet.subnetpool_id,
    )

    def setUp(self):
        super(TestShowSubnet, self).setUp()

        # Get the command object to test
        self.cmd = subnet_v2.ShowSubnet(self.app, self.namespace)

        self.network.find_subnet = mock.Mock(return_value=self._subnet)

    def test_show_no_options(self):
        arglist = []
        verifylist = []

        # Testing that a call without the required argument will fail and
        # throw a "ParserExecption"
        self.assertRaises(tests_utils.ParserException,
                          self.check_parser, self.cmd, arglist, verifylist)

    def test_show_all_options(self):
        arglist = [
            self._subnet.name,
        ]
        verifylist = [
            ('subnet', self._subnet.name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.find_subnet.assert_called_with(self._subnet.name,
                                                    ignore_missing=False)

        self.assertEqual(self.columns, columns)
        self.assertEqual(list(self.data), list(data))
 def test_format_list(self):
     expected = 'a, b, c'
     self.assertEqual(expected, utils.format_list(['a', 'b', 'c']))
     self.assertEqual(expected, utils.format_list(['c', 'b', 'a']))
Exemple #47
0
class TestListNetwork(TestNetwork):

    # The networks going to be listed up.
    _network = network_fakes.FakeNetwork.create_networks(count=3)

    columns = (
        'ID',
        'Name',
        'Subnets',
    )
    columns_long = (
        'ID',
        'Name',
        'Status',
        'Project',
        'State',
        'Shared',
        'Subnets',
        'Network Type',
        'Router Type',
    )

    data = []
    for net in _network:
        data.append((
            net.id,
            net.name,
            utils.format_list(net.subnets),
        ))

    data_long = []
    for net in _network:
        data_long.append((
            net.id,
            net.name,
            net.status,
            net.project_id,
            network._format_admin_state(net.admin_state_up),
            net.shared,
            utils.format_list(net.subnets),
            net.provider_network_type,
            network._format_router_external(net.router_external),
        ))

    def setUp(self):
        super(TestListNetwork, self).setUp()

        # Get the command object to test
        self.cmd = network.ListNetwork(self.app, self.namespace)

        self.network.networks = mock.Mock(return_value=self._network)

    def test_network_list_no_options(self):
        arglist = []
        verifylist = [
            ('external', False),
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        self.network.networks.assert_called_with()
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, list(data))

    def test_list_external(self):
        arglist = [
            '--external',
        ]
        verifylist = [
            ('external', True),
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        self.network.networks.assert_called_with(**{'router:external': True})
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, list(data))

    def test_network_list_long(self):
        arglist = [
            '--long',
        ]
        verifylist = [
            ('long', True),
            ('external', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # DisplayCommandBase.take_action() returns two tuples
        columns, data = self.cmd.take_action(parsed_args)

        self.network.networks.assert_called_with()
        self.assertEqual(self.columns_long, columns)
        self.assertEqual(self.data_long, list(data))
Exemple #48
0
class TestListSubnet(TestSubnet):
    # The subnets going to be listed up.
    _subnet = network_fakes.FakeSubnet.create_subnets(count=3)

    columns = (
        'ID',
        'Name',
        'Network',
        'Subnet',
    )
    columns_long = columns + (
        'Project',
        'DHCP',
        'Name Servers',
        'Allocation Pools',
        'Host Routes',
        'IP Version',
        'Gateway',
    )

    data = []
    for subnet in _subnet:
        data.append((
            subnet.id,
            subnet.name,
            subnet.network_id,
            subnet.cidr,
        ))

    data_long = []
    for subnet in _subnet:
        data_long.append((
            subnet.id,
            subnet.name,
            subnet.network_id,
            subnet.cidr,
            subnet.tenant_id,
            subnet.enable_dhcp,
            utils.format_list(subnet.dns_nameservers),
            subnet_v2._format_allocation_pools(subnet.allocation_pools),
            utils.format_list(subnet.host_routes),
            subnet.ip_version,
            subnet.gateway_ip,
        ))

    def setUp(self):
        super(TestListSubnet, self).setUp()

        # Get the command object to test
        self.cmd = subnet_v2.ListSubnet(self.app, self.namespace)

        self.network.subnets = mock.Mock(return_value=self._subnet)

    def test_subnet_list_no_options(self):
        arglist = []
        verifylist = [
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        columns, data = self.cmd.take_action(parsed_args)

        self.network.subnets.assert_called_with()
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, list(data))

    def test_subnet_list_long(self):
        arglist = [
            '--long',
        ]
        verifylist = [
            ('long', True),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        columns, data = self.cmd.take_action(parsed_args)

        self.network.subnets.assert_called_with()
        self.assertEqual(self.columns_long, columns)
        self.assertEqual(self.data_long, list(data))
class TestShowRouter(TestRouter):

    # The router to set.
    _router = network_fakes.FakeRouter.create_one_router()

    columns = (
        'admin_state_up',
        'availability_zone_hints',
        'availability_zones',
        'distributed',
        'external_gateway_info',
        'ha',
        'id',
        'name',
        'project_id',
        'routes',
        'status',
    )
    data = (
        router._format_admin_state(_router.admin_state_up),
        osc_utils.format_list(_router.availability_zone_hints),
        osc_utils.format_list(_router.availability_zones),
        _router.distributed,
        router._format_external_gateway_info(_router.external_gateway_info),
        _router.ha,
        _router.id,
        _router.name,
        _router.tenant_id,
        _router.routes,
        _router.status,
    )

    def setUp(self):
        super(TestShowRouter, self).setUp()

        self.network.find_router = mock.Mock(return_value=self._router)

        # Get the command object to test
        self.cmd = router.ShowRouter(self.app, self.namespace)

    def test_show_no_options(self):
        arglist = []
        verifylist = []

        # Missing required args should bail here
        self.assertRaises(tests_utils.ParserException, self.check_parser,
                          self.cmd, arglist, verifylist)

    def test_show_all_options(self):
        arglist = [
            self._router.name,
        ]
        verifylist = [
            ('router', self._router.name),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        columns, data = self.cmd.take_action(parsed_args)

        self.network.find_router.assert_called_once_with(
            self._router.name, ignore_missing=False)
        self.assertEqual(tuple(self.columns), columns)
        self.assertEqual(self.data, data)
def _format_compute_security_group_rules(sg_rules):
    rules = []
    for sg_rule in sg_rules:
        rules.append(_format_compute_security_group_rule(sg_rule))
    return utils.format_list(rules, separator='\n')
def _format_cluster_output(data):
    data['version'] = data.pop('hadoop_version')
    data['image'] = data.pop('default_image_id')
    data['node_groups'] = _format_node_groups_list(data['node_groups'])
    data['anti_affinity'] = osc_utils.format_list(data['anti_affinity'])
 def test_format_list_separator(self):
     expected = 'a\nb\nc'
     actual_pre_sorted = utils.format_list(['a', 'b', 'c'], separator='\n')
     actual_unsorted = utils.format_list(['c', 'b', 'a'], separator='\n')
     self.assertEqual(expected, actual_pre_sorted)
     self.assertEqual(expected, actual_unsorted)
class TestListRouter(TestRouter):

    # The routers going to be listed up.
    routers = network_fakes.FakeRouter.create_routers(count=3)

    columns = (
        'ID',
        'Name',
        'Status',
        'State',
        'Distributed',
        'HA',
        'Project',
    )
    columns_long = columns + (
        'Routes',
        'External gateway info',
        'Availability zones'
    )

    data = []
    for r in routers:
        data.append((
            r.id,
            r.name,
            r.status,
            router._format_admin_state(r.admin_state_up),
            r.distributed,
            r.ha,
            r.tenant_id,
        ))
    data_long = []
    for i in range(0, len(routers)):
        r = routers[i]
        data_long.append(
            data[i] + (
                r.routes,
                router._format_external_gateway_info(r.external_gateway_info),
                osc_utils.format_list(r.availability_zones),
            )
        )

    def setUp(self):
        super(TestListRouter, self).setUp()

        # Get the command object to test
        self.cmd = router.ListRouter(self.app, self.namespace)

        self.network.routers = mock.Mock(return_value=self.routers)

    def test_router_list_no_options(self):
        arglist = []
        verifylist = [
            ('long', False),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # In base command class Lister in cliff, abstract method take_action()
        # returns a tuple containing the column names and an iterable
        # containing the data to be listed.
        columns, data = self.cmd.take_action(parsed_args)

        self.network.routers.assert_called_once_with()
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, list(data))

    def test_router_list_long(self):
        arglist = [
            '--long',
        ]
        verifylist = [
            ('long', True),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # In base command class Lister in cliff, abstract method take_action()
        # returns a tuple containing the column names and an iterable
        # containing the data to be listed.
        columns, data = self.cmd.take_action(parsed_args)

        self.network.routers.assert_called_once_with()
        self.assertEqual(self.columns_long, columns)
        self.assertEqual(self.data_long, list(data))
 def test_format_list_separator(self):
     expected = "a\nb\nc"
     actual_pre_sorted = utils.format_list(["a", "b", "c"], separator="\n")
     actual_unsorted = utils.format_list(["c", "b", "a"], separator="\n")
     self.assertEqual(expected, actual_pre_sorted)
     self.assertEqual(expected, actual_unsorted)
Exemple #55
0
class TestCreateSubnet(TestSubnet):

    # An IPv4 subnet to be created with mostly default values
    _subnet = network_fakes.FakeSubnet.create_one_subnet(
        attrs={
            'tenant_id': identity_fakes_v3.project_id,
        }
    )

    # Subnet pool to be used to create a subnet from a pool
    _subnet_pool = network_fakes.FakeSubnetPool.create_one_subnet_pool()

    # An IPv4 subnet to be created using a specific subnet pool
    _subnet_from_pool = network_fakes.FakeSubnet.create_one_subnet(
        attrs={
            'tenant_id': identity_fakes_v3.project_id,
            'subnetpool_id': _subnet_pool.id,
            'dns_nameservers': ['8.8.8.8',
                                '8.8.4.4'],
            'host_routes': [{'destination': '10.20.20.0/24',
                             'nexthop': '10.20.20.1'},
                            {'destination': '10.30.30.0/24',
                             'nexthop': '10.30.30.1'}],
        }
    )

    # An IPv6 subnet to be created with most options specified
    _subnet_ipv6 = network_fakes.FakeSubnet.create_one_subnet(
        attrs={
            'tenant_id': identity_fakes_v3.project_id,
            'cidr': 'fe80:0:0:a00a::/64',
            'enable_dhcp': True,
            'dns_nameservers': ['fe80:27ff:a00a:f00f::ffff',
                                'fe80:37ff:a00a:f00f::ffff'],
            'allocation_pools': [{'start': 'fe80::a00a:0:c0de:0:100',
                                  'end': 'fe80::a00a:0:c0de:0:f000'},
                                 {'start': 'fe80::a00a:0:c0de:1:100',
                                  'end': 'fe80::a00a:0:c0de:1:f000'}],
            'host_routes': [{'destination': 'fe80:27ff:a00a:f00f::/64',
                             'nexthop': 'fe80:27ff:a00a:f00f::1'},
                            {'destination': 'fe80:37ff:a00a:f00f::/64',
                             'nexthop': 'fe80:37ff:a00a:f00f::1'}],
            'ip_version': 6,
            'gateway_ip': 'fe80::a00a:0:c0de:0:1',
            'ipv6_address_mode': 'slaac',
            'ipv6_ra_mode': 'slaac',
            'subnetpool_id': 'None',
        }
    )

    # The network to be returned from find_network
    _network = network_fakes.FakeNetwork.create_one_network(
        attrs={
            'id': _subnet.network_id,
        }
    )

    columns = (
        'allocation_pools',
        'cidr',
        'dns_nameservers',
        'enable_dhcp',
        'gateway_ip',
        'host_routes',
        'id',
        'ip_version',
        'ipv6_address_mode',
        'ipv6_ra_mode',
        'name',
        'network_id',
        'project_id',
        'subnetpool_id',
    )

    data = (
        subnet_v2._format_allocation_pools(_subnet.allocation_pools),
        _subnet.cidr,
        utils.format_list(_subnet.dns_nameservers),
        _subnet.enable_dhcp,
        _subnet.gateway_ip,
        subnet_v2._format_host_routes(_subnet.host_routes),
        _subnet.id,
        _subnet.ip_version,
        _subnet.ipv6_address_mode,
        _subnet.ipv6_ra_mode,
        _subnet.name,
        _subnet.network_id,
        _subnet.project_id,
        _subnet.subnetpool_id,
    )

    data_subnet_pool = (
        subnet_v2._format_allocation_pools(_subnet_from_pool.allocation_pools),
        _subnet_from_pool.cidr,
        utils.format_list(_subnet_from_pool.dns_nameservers),
        _subnet_from_pool.enable_dhcp,
        _subnet_from_pool.gateway_ip,
        subnet_v2._format_host_routes(_subnet_from_pool.host_routes),
        _subnet_from_pool.id,
        _subnet_from_pool.ip_version,
        _subnet_from_pool.ipv6_address_mode,
        _subnet_from_pool.ipv6_ra_mode,
        _subnet_from_pool.name,
        _subnet_from_pool.network_id,
        _subnet_from_pool.project_id,
        _subnet_from_pool.subnetpool_id,
    )

    data_ipv6 = (
        subnet_v2._format_allocation_pools(_subnet_ipv6.allocation_pools),
        _subnet_ipv6.cidr,
        utils.format_list(_subnet_ipv6.dns_nameservers),
        _subnet_ipv6.enable_dhcp,
        _subnet_ipv6.gateway_ip,
        subnet_v2._format_host_routes(_subnet_ipv6.host_routes),
        _subnet_ipv6.id,
        _subnet_ipv6.ip_version,
        _subnet_ipv6.ipv6_address_mode,
        _subnet_ipv6.ipv6_ra_mode,
        _subnet_ipv6.name,
        _subnet_ipv6.network_id,
        _subnet_ipv6.project_id,
        _subnet_ipv6.subnetpool_id,
    )

    def setUp(self):
        super(TestCreateSubnet, self).setUp()

        # Get the command object to test
        self.cmd = subnet_v2.CreateSubnet(self.app, self.namespace)

        # Set identity client v3. And get a shortcut to Identity client.
        identity_client = identity_fakes_v3.FakeIdentityv3Client(
            endpoint=fakes.AUTH_URL,
            token=fakes.AUTH_TOKEN,
        )
        self.app.client_manager.identity = identity_client
        self.identity = self.app.client_manager.identity

        # Get a shortcut to the ProjectManager Mock
        self.projects_mock = self.identity.projects
        self.projects_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.PROJECT),
            loaded=True,
        )

        # Get a shortcut to the DomainManager Mock
        self.domains_mock = self.identity.domains
        self.domains_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v3.DOMAIN),
            loaded=True,
        )

    def test_create_no_options(self):
        arglist = []
        verifylist = []

        # Testing that a call without the required argument will fail and
        # throw a "ParserExecption"
        self.assertRaises(tests_utils.ParserException,
                          self.check_parser, self.cmd, arglist, verifylist)

    def test_create_default_options(self):
        # Mock create_subnet and find_network sdk calls to return the
        # values we want for this test
        self.network.create_subnet = mock.Mock(return_value=self._subnet)
        self._network.id = self._subnet.network_id
        self.network.find_network = mock.Mock(return_value=self._network)

        arglist = [
            self._subnet.name,
            "--subnet-range", self._subnet.cidr,
            "--network", self._subnet.network_id,
        ]
        verifylist = [
            ('name', self._subnet.name),
            ('subnet_range', self._subnet.cidr),
            ('network', self._subnet.network_id),
            ('ip_version', self._subnet.ip_version),
            ('gateway', 'auto'),

        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.create_subnet.assert_called_with(**{
            'cidr': self._subnet.cidr,
            'enable_dhcp': self._subnet.enable_dhcp,
            'ip_version': self._subnet.ip_version,
            'name': self._subnet.name,
            'network_id': self._subnet.network_id,
        })
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)

    def test_create_from_subnet_pool_options(self):
        # Mock create_subnet, find_subnet_pool, and find_network sdk calls
        # to return the values we want for this test
        self.network.create_subnet = \
            mock.Mock(return_value=self._subnet_from_pool)
        self._network.id = self._subnet_from_pool.network_id
        self.network.find_network = mock.Mock(return_value=self._network)
        self.network.find_subnet_pool = \
            mock.Mock(return_value=self._subnet_pool)

        arglist = [
            self._subnet_from_pool.name,
            "--subnet-pool", self._subnet_from_pool.subnetpool_id,
            "--prefix-length", '24',
            "--network", self._subnet_from_pool.network_id,
            "--ip-version", str(self._subnet_from_pool.ip_version),
            "--gateway", self._subnet_from_pool.gateway_ip,
            "--dhcp",
        ]

        for dns_addr in self._subnet_from_pool.dns_nameservers:
            arglist.append('--dns-nameserver')
            arglist.append(dns_addr)

        for host_route in self._subnet_from_pool.host_routes:
            arglist.append('--host-route')
            value = 'gateway=' + host_route.get('nexthop', '') + \
                    ',destination=' + host_route.get('destination', '')
            arglist.append(value)

        verifylist = [
            ('name', self._subnet_from_pool.name),
            ('prefix_length', '24'),
            ('network', self._subnet_from_pool.network_id),
            ('ip_version', self._subnet_from_pool.ip_version),
            ('gateway', self._subnet_from_pool.gateway_ip),
            ('dns_nameservers', self._subnet_from_pool.dns_nameservers),
            ('enable_dhcp', self._subnet_from_pool.enable_dhcp),
            ('host_routes', subnet_v2.convert_entries_to_gateway(
                self._subnet_from_pool.host_routes)),
            ('subnet_pool', self._subnet_from_pool.subnetpool_id),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.create_subnet.assert_called_with(**{
            'dns_nameservers': self._subnet_from_pool.dns_nameservers,
            'enable_dhcp': self._subnet_from_pool.enable_dhcp,
            'gateway_ip': self._subnet_from_pool.gateway_ip,
            'host_routes': self._subnet_from_pool.host_routes,
            'ip_version': self._subnet_from_pool.ip_version,
            'name': self._subnet_from_pool.name,
            'network_id': self._subnet_from_pool.network_id,
            'prefixlen': '24',
            'subnetpool_id': self._subnet_from_pool.subnetpool_id,
        })
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data_subnet_pool, data)

    def test_create_options_subnet_range_ipv6(self):
        # Mock create_subnet and find_network sdk calls to return the
        # values we want for this test
        self.network.create_subnet = mock.Mock(return_value=self._subnet_ipv6)
        self._network.id = self._subnet_ipv6.network_id
        self.network.find_network = mock.Mock(return_value=self._network)

        arglist = [
            self._subnet_ipv6.name,
            "--subnet-range", self._subnet_ipv6.cidr,
            "--network", self._subnet_ipv6.network_id,
            "--ip-version", str(self._subnet_ipv6.ip_version),
            "--ipv6-ra-mode", self._subnet_ipv6.ipv6_ra_mode,
            "--ipv6-address-mode", self._subnet_ipv6.ipv6_address_mode,
            "--gateway", self._subnet_ipv6.gateway_ip,
            "--dhcp",
        ]

        for dns_addr in self._subnet_ipv6.dns_nameservers:
            arglist.append('--dns-nameserver')
            arglist.append(dns_addr)

        for host_route in self._subnet_ipv6.host_routes:
            arglist.append('--host-route')
            value = 'gateway=' + host_route.get('nexthop', '') + \
                    ',destination=' + host_route.get('destination', '')
            arglist.append(value)

        for pool in self._subnet_ipv6.allocation_pools:
            arglist.append('--allocation-pool')
            value = 'start=' + pool.get('start', '') + \
                    ',end=' + pool.get('end', '')
            arglist.append(value)

        verifylist = [
            ('name', self._subnet_ipv6.name),
            ('subnet_range', self._subnet_ipv6.cidr),
            ('network', self._subnet_ipv6.network_id),
            ('ip_version', self._subnet_ipv6.ip_version),
            ('ipv6_ra_mode', self._subnet_ipv6.ipv6_ra_mode),
            ('ipv6_address_mode', self._subnet_ipv6.ipv6_address_mode),
            ('gateway', self._subnet_ipv6.gateway_ip),
            ('dns_nameservers', self._subnet_ipv6.dns_nameservers),
            ('enable_dhcp', self._subnet_ipv6.enable_dhcp),
            ('host_routes', subnet_v2.convert_entries_to_gateway(
                self._subnet_ipv6.host_routes)),
            ('allocation_pools', self._subnet_ipv6.allocation_pools),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.create_subnet.assert_called_with(**{
            'cidr': self._subnet_ipv6.cidr,
            'dns_nameservers': self._subnet_ipv6.dns_nameservers,
            'enable_dhcp': self._subnet_ipv6.enable_dhcp,
            'gateway_ip': self._subnet_ipv6.gateway_ip,
            'host_routes': self._subnet_ipv6.host_routes,
            'ip_version': self._subnet_ipv6.ip_version,
            'ipv6_address_mode': self._subnet_ipv6.ipv6_address_mode,
            'ipv6_ra_mode': self._subnet_ipv6.ipv6_ra_mode,
            'name': self._subnet_ipv6.name,
            'network_id': self._subnet_ipv6.network_id,
            'allocation_pools': self._subnet_ipv6.allocation_pools,
        })
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data_ipv6, data)
def _format_job_template_output(data):
    data['mains'] = osc_utils.format_list(
        ['%s:%s' % (m['name'], m['id']) for m in data['mains']])
    data['libs'] = osc_utils.format_list(
        ['%s:%s' % (l['name'], l['id']) for l in data['libs']])
Exemple #57
0
class TestCreateNetworkIdentityV2(TestNetwork):

    # The new network created.
    _network = network_fakes.FakeNetwork.create_one_network(
        attrs={'tenant_id': identity_fakes_v2.project_id})

    columns = (
        'admin_state_up',
        'id',
        'name',
        'project_id',
        'router_external',
        'status',
        'subnets',
    )

    data = (
        network._format_admin_state(_network.admin_state_up),
        _network.id,
        _network.name,
        _network.project_id,
        network._format_router_external(_network.router_external),
        _network.status,
        utils.format_list(_network.subnets),
    )

    def setUp(self):
        super(TestCreateNetworkIdentityV2, self).setUp()

        self.network.create_network = mock.Mock(return_value=self._network)

        # Get the command object to test
        self.cmd = network.CreateNetwork(self.app, self.namespace)

        # Set identity client v2. And get a shortcut to Identity client.
        identity_client = identity_fakes_v2.FakeIdentityv2Client(
            endpoint=fakes.AUTH_URL,
            token=fakes.AUTH_TOKEN,
        )
        self.app.client_manager.identity = identity_client
        self.identity = self.app.client_manager.identity

        # Get a shortcut to the ProjectManager Mock
        self.projects_mock = self.identity.tenants
        self.projects_mock.get.return_value = fakes.FakeResource(
            None,
            copy.deepcopy(identity_fakes_v2.PROJECT),
            loaded=True,
        )

        # There is no DomainManager Mock in fake identity v2.

    def test_create_with_project_identityv2(self):
        arglist = [
            "--project",
            identity_fakes_v2.project_name,
            self._network.name,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', None),
            ('name', self._network.name),
            ('project', identity_fakes_v2.project_name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        self.network.create_network.assert_called_with(
            **{
                'admin_state_up': True,
                'name': self._network.name,
                'tenant_id': identity_fakes_v2.project_id,
            })
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)

    def test_create_with_domain_identityv2(self):
        arglist = [
            "--project",
            identity_fakes_v3.project_name,
            "--project-domain",
            identity_fakes_v3.domain_name,
            self._network.name,
        ]
        verifylist = [
            ('admin_state', True),
            ('shared', None),
            ('project', identity_fakes_v3.project_name),
            ('project_domain', identity_fakes_v3.domain_name),
            ('name', self._network.name),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        self.assertRaises(
            AttributeError,
            self.cmd.take_action,
            parsed_args,
        )