Esempio n. 1
0
    def setUpClass(cls):
        cls.config = config.TempestConfig()
        cls.isolated_creds = []

        if cls.config.compute.allow_tenant_isolation:
            creds = cls._get_isolated_creds()
            username, tenant_name, password = creds
            os = openstack.Manager(username=username,
                                   password=password,
                                   tenant_name=tenant_name)
        else:
            os = openstack.Manager()

        cls.os = os
        cls.volumes_client = os.volumes_client
        cls.servers_client = os.servers_client
        cls.image_ref = cls.config.compute.image_ref
        cls.flavor_ref = cls.config.compute.flavor_ref
        cls.build_interval = cls.config.volume.build_interval
        cls.build_timeout = cls.config.volume.build_timeout
        cls.volumes = {}

        skip_msg = ("%s skipped as Cinder endpoint is not available" %
                    cls.__name__)
        try:
            cls.volumes_client.keystone_auth(cls.os.username, cls.os.password,
                                             cls.os.auth_url,
                                             cls.volumes_client.service,
                                             cls.os.tenant_name)
        except exceptions.EndpointNotFound:
            cls.clear_isolated_creds()
            raise nose.SkipTest(skip_msg)
Esempio n. 2
0
    def status_timeout(self, things, thing_id, expected_status):
        """
        Given a thing and an expected status, do a loop, sleeping
        for a configurable amount of time, checking for the
        expected status to show. At any time, if the returned
        status of the thing is ERROR, fail out.
        """
        def check_status():
            # python-novaclient has resources available to its client
            # that all implement a get() method taking an identifier
            # for the singular resource to retrieve.
            thing = things.get(thing_id)
            new_status = thing.status
            if new_status == 'ERROR':
                self.fail("%s failed to get to expected status."
                          "In ERROR state." % thing)
            elif new_status == expected_status:
                return True  # All good.
            LOG.debug(
                "Waiting for %s to get to %s status. "
                "Currently in %s status", thing, expected_status, new_status)

        conf = config.TempestConfig()
        if not call_until_true(check_status, conf.compute.build_timeout,
                               conf.compute.build_interval):
            self.fail("Timed out waiting for thing %s to become %s" %
                      (thing_id, expected_status))
Esempio n. 3
0
 def __init__(self, interface='json'):
     conf = config.TempestConfig()
     base = super(ComputeAdminManager, self)
     base.__init__(conf.compute_admin.username,
                   conf.compute_admin.password,
                   conf.compute_admin.tenant_name,
                   interface=interface)
Esempio n. 4
0
class AuthTokenTestJSON(base.BaseV2ComputeTest):
    _interface = 'json'

    @classmethod
    def setUpClass(cls):
        super(AuthTokenTestJSON, cls).setUpClass()

        cls.servers_v2 = cls.os.servers_client
        cls.servers_v3 = cls.os.servers_client_v3_auth

    def test_v2_token(self):
        # Can get a token using v2 of the identity API and use that to perform
        # an operation on the compute service.

        # Doesn't matter which compute API is used,
        # picking list_servers because it's easy.
        self.servers_v2.list_servers()

    @testtools.skipIf(not config.TempestConfig().identity.uri_v3,
                      'v3 auth client not configured')
    def test_v3_token(self):
        # Can get a token using v3 of the identity API and use that to perform
        # an operation on the compute service.

        # Doesn't matter which compute API is used,
        # picking list_servers because it's easy.
        self.servers_v3.list_servers()
Esempio n. 5
0
    def setUpClass(cls):
        cls.config = config.TempestConfig()
        cls.isolated_creds = []

        if cls.config.compute.allow_tenant_isolation:
            creds = cls._get_isolated_creds()
            username, tenant_name, password = creds
            os = openstack.Manager(username=username,
                                   password=password,
                                   tenant_name=tenant_name,
                                   interface=cls._interface)
        else:
            os = openstack.Manager(interface=cls._interface)

        cls.os = os
        cls.servers_client = os.servers_client
        cls.flavors_client = os.flavors_client
        cls.images_client = os.images_client
        cls.extensions_client = os.extensions_client
        cls.floating_ips_client = os.floating_ips_client
        cls.keypairs_client = os.keypairs_client
        cls.security_groups_client = os.security_groups_client
        cls.console_outputs_client = os.console_outputs_client
        cls.quotas_client = os.quotas_client
        cls.limits_client = os.limits_client
        cls.volumes_extensions_client = os.volumes_extensions_client
        cls.volumes_client = os.volumes_client
        cls.build_interval = cls.config.compute.build_interval
        cls.build_timeout = cls.config.compute.build_timeout
        cls.ssh_user = cls.config.compute.ssh_user
        cls.image_ref = cls.config.compute.image_ref
        cls.image_ref_alt = cls.config.compute.image_ref_alt
        cls.flavor_ref = cls.config.compute.flavor_ref
        cls.flavor_ref_alt = cls.config.compute.flavor_ref_alt
        cls.servers = []
Esempio n. 6
0
    def __init__(self, username=None, password=None, tenant_name=None,
                 interface='json'):
        """
        We allow overriding of the credentials used within the various
        client classes managed by the Manager object. Left as None, the
        standard username/password/tenant_name is used.

        :param username: Override of the username
        :param password: Override of the password
        :param tenant_name: Override of the tenant name
        """
        self.config = config.TempestConfig()

        # If no creds are provided, we fall back on the defaults
        # in the config file for the Compute API.
        self.username = username or self.config.identity.username
        self.password = password or self.config.identity.password
        self.tenant_name = tenant_name or self.config.identity.tenant_name

        if None in (self.username, self.password, self.tenant_name):
            msg = ("Missing required credentials. "
                   "username: %(u)s, password: %(p)s, "
                   "tenant_name: %(t)s" %
                   {'u': username, 'p': password, 't': tenant_name})
            raise exceptions.InvalidConfiguration(msg)

        self.auth_url = self.config.identity.uri

        client_args = (self.config, self.username, self.password,
                       self.auth_url, self.tenant_name)

        # common clients
        self.dynamodb_client = botoclients.APIClientDynamoDB(*client_args)
        self.magnetodb_client = MagnetoDBClientJSON(*client_args)
Esempio n. 7
0
 def __init__(self, interface='json'):
     conf = config.TempestConfig()
     base = super(OrchestrationManager, self)
     base.__init__(conf.identity.admin_username,
                   conf.identity.admin_password,
                   conf.identity.admin_tenant_name,
                   interface=interface)
Esempio n. 8
0
class BaseTestCase(testtools.TestCase, testtools.testcase.WithAttributes,
                   testresources.ResourcedTestCase):

    config = config.TempestConfig()

    @classmethod
    def setUpClass(cls):
        if hasattr(super(BaseTestCase, cls), 'setUpClass'):
            super(BaseTestCase, cls).setUpClass()
Esempio n. 9
0
class FixedIPsTestJson(FixedIPsBase):
    _interface = 'json'

    CONF = config.TempestConfig()

    @testtools.skipIf(CONF.network.quantum_available, "This feature is not" +
                      "implemented by Quantum. See bug: #1194569")
    @attr(type='gate')
    def test_list_fixed_ip_details(self):
        resp, fixed_ip = self.client.get_fixed_ip_details(self.ip)
        self.assertEqual(fixed_ip['address'], self.ip)

    @attr(type=['negative', 'gate'])
    def test_list_fixed_ip_details_with_non_admin_user(self):
        self.assertRaises(exceptions.Unauthorized,
                          self.non_admin_client.get_fixed_ip_details, self.ip)

    @attr(type='gate')
    def test_set_reserve(self):
        body = {"reserve": "None"}
        resp, body = self.client.reserve_fixed_ip(self.ip, body)
        self.assertEqual(resp.status, 202)

    @attr(type='gate')
    def test_set_unreserve(self):
        body = {"unreserve": "None"}
        resp, body = self.client.reserve_fixed_ip(self.ip, body)
        self.assertEqual(resp.status, 202)

    @attr(type=['negative', 'gate'])
    def test_set_reserve_with_non_admin_user(self):
        body = {"reserve": "None"}
        self.assertRaises(exceptions.Unauthorized,
                          self.non_admin_client.reserve_fixed_ip, self.ip,
                          body)

    @attr(type=['negative', 'gate'])
    def test_set_unreserve_with_non_admin_user(self):
        body = {"unreserve": "None"}
        self.assertRaises(exceptions.Unauthorized,
                          self.non_admin_client.reserve_fixed_ip, self.ip,
                          body)

    @attr(type=['negative', 'gate'])
    def test_set_reserve_with_invalid_ip(self):
        # NOTE(maurosr): since this exercises the same code snippet, we do it
        # only for reserve action
        body = {"reserve": "None"}
        self.assertRaises(exceptions.NotFound, self.client.reserve_fixed_ip,
                          "my.invalid.ip", body)

    @attr(type=['negative', 'gate'])
    def test_fixed_ip_with_invalid_action(self):
        body = {"invalid_action": "None"}
        self.assertRaises(exceptions.BadRequest, self.client.reserve_fixed_ip,
                          self.ip, body)
Esempio n. 10
0
 def __init__(self,
              name,
              tempest_client=True,
              interface='json',
              password='******'):
     self.isolated_creds = {}
     self.name = name
     self.config = config.TempestConfig()
     self.tempest_client = tempest_client
     self.interface = interface
     self.password = password
     self.admin_client = self._get_identity_admin_client()
Esempio n. 11
0
    def setUpClass(cls):
        cls.config = config.TempestConfig()
        cls.admin_username = cls.config.compute_admin.username
        cls.admin_password = cls.config.compute_admin.password
        cls.admin_tenant = cls.config.compute_admin.tenant_name

        if not cls.admin_username and cls.admin_password and cls.admin_tenant:
            msg = ("Missing Compute Admin API credentials "
                   "in configuration.")
            raise nose.SkipTest(msg)

        cls.os = openstack.AdminManager(interface=cls._interface)
Esempio n. 12
0
    def __init__(self, username=None, password=None, tenant_name=None,
                 interface='json'):
        """
        We allow overriding of the credentials used within the various
        client classes managed by the Manager object. Left as None, the
        standard username/password/tenant_name is used.

        :param username: Override of the username
        :param password: Override of the password
        :param tenant_name: Override of the tenant name
        """
        self.config = config.TempestConfig()

        # If no creds are provided, we fall back on the defaults
        # in the config file for the Compute API.
        self.username = username or self.config.compute.username
        self.password = password or self.config.compute.password
        self.tenant_name = tenant_name or self.config.compute.tenant_name

        if None in (self.username, self.password, self.tenant_name):
            msg = ("Missing required credentials. "
                   "username: %(username)s, password: %(password)s, "
                   "tenant_name: %(tenant_name)s") % locals()
            raise exceptions.InvalidConfiguration(msg)

        self.auth_url = self.config.identity.auth_url

        if self.config.identity.strategy == 'keystone':
            client_args = (self.config, self.username, self.password,
                           self.auth_url, self.tenant_name)
        else:
            client_args = (self.config, self.username, self.password,
                           self.auth_url)

        try:
            self.servers_client = SERVERS_CLIENTS[interface](*client_args)
            self.limits_client = LIMITS_CLIENTS[interface](*client_args)
            self.keypairs_client = KEYPAIRS_CLIENTS[interface](*client_args)
            self.flavors_client = FLAVORS_CLIENTS[interface](*client_args)
            self.extensions_client = \
                    EXTENSIONS_CLIENTS[interface](*client_args)
            self.volumes_extensions_client = \
                    VOLUMES_EXTENSIONS_CLIENTS[interface](*client_args)
        except KeyError:
            msg = "Unsupported interface type `%s'" % interface
            raise exceptions.InvalidConfiguration(msg)
        self.images_client = ImagesClient(*client_args)
        self.security_groups_client = SecurityGroupsClient(*client_args)
        self.floating_ips_client = FloatingIPsClient(*client_args)
        self.console_outputs_client = ConsoleOutputsClient(*client_args)
        self.network_client = NetworkClient(*client_args)
        self.volumes_client = VolumesClient(*client_args)
Esempio n. 13
0
 def __init__(self,
              name,
              tempest_client=True,
              interface='json',
              password='******'):
     self.isolated_creds = {}
     self.isolated_net_resources = {}
     self.ports = []
     self.name = name
     self.config = config.TempestConfig()
     self.tempest_client = tempest_client
     self.interface = interface
     self.password = password
     self.identity_admin_client, self.network_admin_client = (
         self._get_admin_clients())
Esempio n. 14
0
def log_ip_ns():
    if not config.TempestConfig().debug.enable:
        return
    LOG.info("Host Addr:\n" + commands.ip_addr_raw())
    LOG.info("Host Route:\n" + commands.ip_route_raw())
    for table in ['filter', 'nat', 'mangle']:
        LOG.info('Host %s table:\n%s', table, commands.iptables_raw(table))
    ns_list = commands.ip_ns_list()
    LOG.info("Host ns list" + str(ns_list))
    for ns in ns_list:
        LOG.info("ns(%s) Addr:\n%s", ns, commands.ip_ns_addr(ns))
        LOG.info("ns(%s) Route:\n%s", ns, commands.ip_ns_route(ns))
        for table in ['filter', 'nat', 'mangle']:
            LOG.info('ns(%s) table(%s):\n%s', ns, table,
                     commands.iptables_ns(ns, table))
Esempio n. 15
0
    def __init__(self, username=None, password=None, tenant_name=None):
        """
        We allow overriding of the credentials used within the various
        client classes managed by the Manager object. Left as None, the
        standard username/password/tenant_name is used.

        :param username: Override of the username
        :param password: Override of the password
        :param tenant_name: Override of the tenant name
        """
        self.config = config.TempestConfig()

        # If no creds are provided, we fall back on the defaults
        # in the config file for the Compute API.
        username = username or self.config.compute.username
        password = password or self.config.compute.password
        tenant_name = tenant_name or self.config.compute.tenant_name

        if None in (username, password, tenant_name):
            msg = ("Missing required credentials. "
                   "username: %(username)s, password: %(password)s, "
                   "tenant_name: %(tenant_name)s") % locals()
            raise exceptions.InvalidConfiguration(msg)

        auth_url = self.config.identity.auth_url

        if self.config.identity.strategy == 'keystone':
            client_args = (self.config, username, password, auth_url,
                           tenant_name)
        else:
            client_args = (self.config, username, password, auth_url)

        self.servers_client = ServersClient(*client_args)
        self.flavors_client = FlavorsClient(*client_args)
        self.images_client = ImagesClient(*client_args)
        self.limits_client = LimitsClient(*client_args)
        self.extensions_client = ExtensionsClient(*client_args)
        self.keypairs_client = KeyPairsClient(*client_args)
        self.security_groups_client = SecurityGroupsClient(*client_args)
        self.floating_ips_client = FloatingIPsClient(*client_args)
        self.volumes_client = VolumesClient(*client_args)
        self.console_outputs_client = ConsoleOutputsClient(*client_args)
        self.network_client = NetworkClient(*client_args)
Esempio n. 16
0
class BaseTestCase(testtools.TestCase, testtools.testcase.WithAttributes,
                   testresources.ResourcedTestCase):

    config = config.TempestConfig()

    @classmethod
    def setUpClass(cls):
        if hasattr(super(BaseTestCase, cls), 'setUpClass'):
            super(BaseTestCase, cls).setUpClass()

    def setUp(cls):
        super(BaseTestCase, cls).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            test_timeout = 0
        if test_timeout > 0:
            cls.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        if (os.environ.get('OS_STDOUT_CAPTURE') == 'True'
                or os.environ.get('OS_STDOUT_CAPTURE') == '1'):
            stdout = cls.useFixture(fixtures.StringStream('stdout')).stream
            cls.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if (os.environ.get('OS_STDERR_CAPTURE') == 'True'
                or os.environ.get('OS_STDERR_CAPTURE') == '1'):
            stderr = cls.useFixture(fixtures.StringStream('stderr')).stream
            cls.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

    @classmethod
    def _get_identity_admin_client(cls):
        """
        Returns an instance of the Identity Admin API client
        """
        os = clients.AdminManager(interface=cls._interface)
        admin_client = os.identity_client
        return admin_client

    @classmethod
    def _get_client_args(cls):

        return (cls.config, cls.config.identity.admin_username,
                cls.config.identity.admin_password, cls.config.identity.uri)
class VirtualInterfacesTestJSON(base.BaseComputeTest):
    _interface = 'json'

    CONF = config.TempestConfig()

    @classmethod
    def setUpClass(cls):
        super(VirtualInterfacesTestJSON, cls).setUpClass()
        cls.client = cls.servers_client
        resp, server = cls.create_server(wait_until='ACTIVE')
        cls.server_id = server['id']

    @testtools.skipIf(CONF.service_available.neutron, "This feature is not " +
                      "implemented by Neutron. See bug: #1183436")
    @attr(type='gate')
    def test_list_virtual_interfaces(self):
        # Positive test:Should be able to GET the virtual interfaces list
        # for a given server_id
        resp, output = self.client.list_virtual_interfaces(self.server_id)
        self.assertEqual(200, resp.status)
        self.assertNotEqual(output, None)
        virt_ifaces = output
        self.assertNotEqual(0, len(virt_ifaces['virtual_interfaces']),
                            'Expected virtual interfaces, got 0 interfaces.')
        for virt_iface in virt_ifaces['virtual_interfaces']:
            mac_address = virt_iface['mac_address']
            self.assertTrue(netaddr.valid_mac(mac_address),
                            "Invalid mac address detected.")

    @attr(type=['negative', 'gate'])
    def test_list_virtual_interfaces_invalid_server_id(self):
        # Negative test: Should not be able to GET virtual interfaces
        # for an invalid server_id
        invalid_server_id = rand_name('!@#$%^&*()')
        self.assertRaises(exceptions.NotFound,
                          self.client.list_virtual_interfaces,
                          invalid_server_id)
Esempio n. 18
0
class SecurityGroupsTestJSON(base.BaseComputeTest):
    _interface = 'json'

    @classmethod
    def setUpClass(cls):
        super(SecurityGroupsTestJSON, cls).setUpClass()
        cls.client = cls.security_groups_client

    def _delete_security_group(self, securitygroup_id):
        resp, _ = self.client.delete_security_group(securitygroup_id)
        self.assertEqual(202, resp.status)

    @attr(type='gate')
    def test_security_groups_create_list_delete(self):
        # Positive test:Should return the list of Security Groups
        # Create 3 Security Groups
        security_group_list = list()
        for i in range(3):
            s_name = rand_name('securitygroup-')
            s_description = rand_name('description-')
            resp, securitygroup = \
                self.client.create_security_group(s_name, s_description)
            self.assertEqual(200, resp.status)
            self.addCleanup(self._delete_security_group, securitygroup['id'])
            security_group_list.append(securitygroup)
        # Fetch all Security Groups and verify the list
        # has all created Security Groups
        resp, fetched_list = self.client.list_security_groups()
        self.assertEqual(200, resp.status)
        # Now check if all the created Security Groups are in fetched list
        missing_sgs = \
            [sg for sg in security_group_list if sg not in fetched_list]
        self.assertFalse(
            missing_sgs, "Failed to find Security Group %s in fetched "
            "list" % ', '.join(m_group['name'] for m_group in missing_sgs))

    # TODO(afazekas): scheduled for delete,
    # test_security_group_create_get_delete covers it
    @attr(type='gate')
    def test_security_group_create_delete(self):
        # Security Group should be created, verified and deleted
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = \
            self.client.create_security_group(s_name, s_description)
        self.assertIn('id', securitygroup)
        securitygroup_id = securitygroup['id']
        self.addCleanup(self._delete_security_group, securitygroup_id)
        self.assertEqual(200, resp.status)
        self.assertFalse(securitygroup_id is None)
        self.assertIn('name', securitygroup)
        securitygroup_name = securitygroup['name']
        self.assertEqual(
            securitygroup_name, s_name, "The created Security Group name is "
            "not equal to the requested name")

    @attr(type='gate')
    def test_security_group_create_get_delete(self):
        # Security Group should be created, fetched and deleted
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = \
            self.client.create_security_group(s_name, s_description)
        self.addCleanup(self._delete_security_group, securitygroup['id'])

        self.assertEqual(200, resp.status)
        self.assertIn('name', securitygroup)
        securitygroup_name = securitygroup['name']
        self.assertEqual(
            securitygroup_name, s_name, "The created Security Group name is "
            "not equal to the requested name")
        # Now fetch the created Security Group by its 'id'
        resp, fetched_group = \
            self.client.get_security_group(securitygroup['id'])
        self.assertEqual(200, resp.status)
        self.assertEqual(
            securitygroup, fetched_group,
            "The fetched Security Group is different "
            "from the created Group")

    @attr(type=['negative', 'gate'])
    def test_security_group_get_nonexistant_group(self):
        # Negative test:Should not be able to GET the details
        # of nonexistant Security Group
        security_group_id = []
        resp, body = self.client.list_security_groups()
        for i in range(len(body)):
            security_group_id.append(body[i]['id'])
        # Creating a nonexistant Security Group id
        while True:
            non_exist_id = rand_name('999')
            if non_exist_id not in security_group_id:
                break
        self.assertRaises(exceptions.NotFound, self.client.get_security_group,
                          non_exist_id)

    @attr(type=['negative', 'gate'])
    def test_security_group_create_with_invalid_group_name(self):
        # Negative test: Security Group should not be created with group name
        # as an empty string/with white spaces/chars more than 255
        s_description = rand_name('description-')
        # Create Security Group with empty string as group name
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group, "", s_description)
        # Create Security Group with white space in group name
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group, " ",
                          s_description)
        # Create Security Group with group name longer than 255 chars
        s_name = 'securitygroup-'.ljust(260, '0')
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group, s_name,
                          s_description)

    @attr(type=['negative', 'gate'])
    def test_security_group_create_with_invalid_group_description(self):
        # Negative test:Security Group should not be created with description
        # as an empty string/with white spaces/chars more than 255
        s_name = rand_name('securitygroup-')
        # Create Security Group with empty string as description
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group, s_name, "")
        # Create Security Group with white space in description
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group, s_name, " ")
        # Create Security Group with group description longer than 255 chars
        s_description = 'description-'.ljust(260, '0')
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group, s_name,
                          s_description)

    @testtools.skipIf(config.TempestConfig().service_available.neutron,
                      "Neutron allows duplicate names for security groups")
    @attr(type=['negative', 'gate'])
    def test_security_group_create_with_duplicate_name(self):
        # Negative test:Security Group with duplicate name should not
        # be created
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, security_group =\
            self.client.create_security_group(s_name, s_description)
        self.assertEqual(200, resp.status)

        self.addCleanup(self.client.delete_security_group,
                        security_group['id'])
        # Now try the Security Group with the same 'Name'
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group, s_name,
                          s_description)

    @attr(type=['negative', 'gate'])
    def test_delete_the_default_security_group(self):
        # Negative test:Deletion of the "default" Security Group should Fail
        default_security_group_id = None
        resp, body = self.client.list_security_groups()
        for i in range(len(body)):
            if body[i]['name'] == 'default':
                default_security_group_id = body[i]['id']
                break
        # Deleting the "default" Security Group
        self.assertRaises(exceptions.BadRequest,
                          self.client.delete_security_group,
                          default_security_group_id)

    @attr(type=['negative', 'gate'])
    def test_delete_nonexistant_security_group(self):
        # Negative test:Deletion of a nonexistant Security Group should Fail
        security_group_id = []
        resp, body = self.client.list_security_groups()
        for i in range(len(body)):
            security_group_id.append(body[i]['id'])
        # Creating Non Existant Security Group
        while True:
            non_exist_id = rand_name('999')
            if non_exist_id not in security_group_id:
                break
        self.assertRaises(exceptions.NotFound,
                          self.client.delete_security_group, non_exist_id)

    @attr(type=['negative', 'gate'])
    def test_delete_security_group_without_passing_id(self):
        # Negative test:Deletion of a Security Group with out passing ID
        # should Fail
        self.assertRaises(exceptions.NotFound,
                          self.client.delete_security_group, '')

    @attr(type='gate')
    def test_server_security_groups(self):
        # Checks that security groups may be added and linked to a server
        # and not deleted if the server is active.
        # Create a couple security groups that we will use
        # for the server resource this test creates
        sg_name = rand_name('sg')
        sg_desc = rand_name('sg-desc')
        resp, sg = self.client.create_security_group(sg_name, sg_desc)
        sg_id = sg['id']

        sg2_name = rand_name('sg')
        sg2_desc = rand_name('sg-desc')
        resp, sg2 = self.client.create_security_group(sg2_name, sg2_desc)
        sg2_id = sg2['id']

        # Create server and add the security group created
        # above to the server we just created
        server_name = rand_name('server')
        resp, server = self.servers_client.create_server(
            server_name, self.image_ref, self.flavor_ref)
        server_id = server['id']
        self.servers_client.wait_for_server_status(server_id, 'ACTIVE')
        resp, body = self.servers_client.add_security_group(server_id, sg_name)

        # Check that we are not able to delete the security
        # group since it is in use by an active server
        self.assertRaises(exceptions.BadRequest,
                          self.client.delete_security_group, sg_id)

        # Reboot and add the other security group
        resp, body = self.servers_client.reboot(server_id, 'HARD')
        self.servers_client.wait_for_server_status(server_id, 'ACTIVE')
        resp, body = self.servers_client.add_security_group(
            server_id, sg2_name)

        # Check that we are not able to delete the other security
        # group since it is in use by an active server
        self.assertRaises(exceptions.BadRequest,
                          self.client.delete_security_group, sg2_id)

        # Shutdown the server and then verify we can destroy the
        # security groups, since no active server instance is using them
        self.servers_client.delete_server(server_id)
        self.servers_client.wait_for_server_termination(server_id)

        self.client.delete_security_group(sg_id)
        self.assertEqual(202, resp.status)

        self.client.delete_security_group(sg2_id)
        self.assertEqual(202, resp.status)
Esempio n. 19
0
class ContainerQuotasTest(base.BaseObjectTest):
    """Attemps to test the perfect behavior of quotas in a container."""
    container_quotas_available = \
        config.TempestConfig().object_storage.container_quotas_available

    def setUp(self):
        """Creates and sets a container with quotas.

        Quotas are set by adding meta values to the container,
        and are validated when set:
          - X-Container-Meta-Quota-Bytes:
                     Maximum size of the container, in bytes.
          - X-Container-Meta-Quota-Count:
                     Maximum object count of the container.
        """
        super(ContainerQuotasTest, self).setUp()
        self.container_name = rand_name(name="TestContainer")
        self.container_client.create_container(self.container_name)
        metadata = {
            "quota-bytes": str(QUOTA_BYTES),
            "quota-count": str(QUOTA_COUNT),
        }
        self.container_client.update_container_metadata(
            self.container_name, metadata)

    def tearDown(self):
        """Cleans the container of any object after each test."""
        self.delete_containers([self.container_name])
        super(ContainerQuotasTest, self).tearDown()

    @testtools.skipIf(not container_quotas_available, SKIP_MSG)
    @attr(type="smoke")
    def test_upload_valid_object(self):
        """Attempts to uploads an object smaller than the bytes quota."""
        object_name = rand_name(name="TestObject")
        data = arbitrary_string(QUOTA_BYTES)

        nbefore = self._get_bytes_used()

        resp, _ = self.object_client.create_object(self.container_name,
                                                   object_name, data)
        self.assertIn(int(resp['status']), HTTP_SUCCESS)

        nafter = self._get_bytes_used()
        self.assertEqual(nbefore + len(data), nafter)

    @testtools.skipIf(not container_quotas_available, SKIP_MSG)
    @attr(type="smoke")
    def test_upload_large_object(self):
        """Attempts to upload an object lagger than the bytes quota."""
        object_name = rand_name(name="TestObject")
        data = arbitrary_string(QUOTA_BYTES + 1)

        nbefore = self._get_bytes_used()

        self.assertRaises(exceptions.OverLimit,
                          self.object_client.create_object,
                          self.container_name, object_name, data)

        nafter = self._get_bytes_used()
        self.assertEqual(nbefore, nafter)

    @testtools.skipIf(not container_quotas_available, SKIP_MSG)
    @attr(type="smoke")
    def test_upload_too_many_objects(self):
        """Attempts to upload many objects that exceeds the count limit."""
        for _ in range(QUOTA_COUNT):
            name = rand_name(name="TestObject")
            self.object_client.create_object(self.container_name, name, "")

        nbefore = self._get_object_count()
        self.assertEqual(nbefore, QUOTA_COUNT)

        self.assertRaises(exceptions.OverLimit,
                          self.object_client.create_object,
                          self.container_name, "OverQuotaObject", "")

        nafter = self._get_object_count()
        self.assertEqual(nbefore, nafter)

    def _get_container_metadata(self):
        resp, _ = self.container_client.list_container_metadata(
            self.container_name)
        return resp

    def _get_object_count(self):
        resp = self._get_container_metadata()
        return int(resp["x-container-object-count"])

    def _get_bytes_used(self):
        resp = self._get_container_metadata()
        return int(resp["x-container-bytes-used"])
Esempio n. 20
0
 def __init__(self):
     conf = config.TempestConfig()
     super(AltManager, self).__init__(conf.identity.alt_username,
                                      conf.identity.alt_password,
                                      conf.identity.alt_tenant_name)
Esempio n. 21
0
 def __init__(self, interface='json'):
     conf = config.TempestConfig()
     super(AdminManager, self).__init__(conf.identity.admin_username,
                                        conf.identity.admin_password,
                                        conf.identity.admin_tenant_name,
                                        interface=interface)
class SecurityGroupRulesTestJSON(base.BaseComputeTest):
    _interface = 'json'

    @classmethod
    def setUpClass(cls):
        super(SecurityGroupRulesTestJSON, cls).setUpClass()
        cls.client = cls.security_groups_client

    @attr(type='gate')
    def test_security_group_rules_create(self):
        # Positive test: Creation of Security Group rule
        # should be successfull
        # Creating a Security Group to add rules to it
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = \
            self.client.create_security_group(s_name, s_description)
        securitygroup_id = securitygroup['id']
        self.addCleanup(self.client.delete_security_group, securitygroup_id)
        # Adding rules to the created Security Group
        ip_protocol = 'tcp'
        from_port = 22
        to_port = 22
        resp, rule = \
            self.client.create_security_group_rule(securitygroup_id,
                                                   ip_protocol,
                                                   from_port,
                                                   to_port)
        self.addCleanup(self.client.delete_security_group_rule, rule['id'])
        self.assertEqual(200, resp.status)

    @attr(type='gate')
    def test_security_group_rules_create_with_optional_arguments(self):
        # Positive test: Creation of Security Group rule
        # with optional arguments
        # should be successfull

        secgroup1 = None
        secgroup2 = None
        # Creating a Security Group to add rules to it
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = \
            self.client.create_security_group(s_name, s_description)
        secgroup1 = securitygroup['id']
        self.addCleanup(self.client.delete_security_group, secgroup1)
        # Creating a Security Group so as to assign group_id to the rule
        s_name2 = rand_name('securitygroup-')
        s_description2 = rand_name('description-')
        resp, securitygroup = \
            self.client.create_security_group(s_name2, s_description2)
        secgroup2 = securitygroup['id']
        self.addCleanup(self.client.delete_security_group, secgroup2)
        # Adding rules to the created Security Group with optional arguments
        parent_group_id = secgroup1
        ip_protocol = 'tcp'
        from_port = 22
        to_port = 22
        cidr = '10.2.3.124/24'
        group_id = secgroup2
        resp, rule = \
            self.client.create_security_group_rule(parent_group_id,
                                                   ip_protocol,
                                                   from_port,
                                                   to_port,
                                                   cidr=cidr,
                                                   group_id=group_id)
        self.addCleanup(self.client.delete_security_group_rule, rule['id'])
        self.assertEqual(200, resp.status)

    @testtools.skipIf(config.TempestConfig().service_available.neutron,
                      "Skipped until the Bug #1182384 is resolved")
    @attr(type=['negative', 'gate'])
    def test_security_group_rules_create_with_invalid_id(self):
        # Negative test: Creation of Security Group rule should FAIL
        # with invalid Parent group id
        # Adding rules to the invalid Security Group id
        parent_group_id = rand_name('999')
        ip_protocol = 'tcp'
        from_port = 22
        to_port = 22
        self.assertRaises(exceptions.NotFound,
                          self.client.create_security_group_rule,
                          parent_group_id, ip_protocol, from_port, to_port)

    @attr(type=['negative', 'gate'])
    def test_security_group_rules_create_with_invalid_ip_protocol(self):
        # Negative test: Creation of Security Group rule should FAIL
        # with invalid ip_protocol
        # Creating a Security Group to add rule to it
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = self.client.create_security_group(
            s_name, s_description)
        # Adding rules to the created Security Group
        parent_group_id = securitygroup['id']
        ip_protocol = rand_name('999')
        from_port = 22
        to_port = 22

        self.addCleanup(self.client.delete_security_group, securitygroup['id'])
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group_rule,
                          parent_group_id, ip_protocol, from_port, to_port)

    @attr(type=['negative', 'gate'])
    def test_security_group_rules_create_with_invalid_from_port(self):
        # Negative test: Creation of Security Group rule should FAIL
        # with invalid from_port
        # Creating a Security Group to add rule to it
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = self.client.create_security_group(
            s_name, s_description)
        # Adding rules to the created Security Group
        parent_group_id = securitygroup['id']
        ip_protocol = 'tcp'
        from_port = rand_name('999')
        to_port = 22
        self.addCleanup(self.client.delete_security_group, securitygroup['id'])
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group_rule,
                          parent_group_id, ip_protocol, from_port, to_port)

    @attr(type=['negative', 'gate'])
    def test_security_group_rules_create_with_invalid_to_port(self):
        # Negative test: Creation of Security Group rule should FAIL
        # with invalid from_port
        # Creating a Security Group to add rule to it
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = self.client.create_security_group(
            s_name, s_description)
        # Adding rules to the created Security Group
        parent_group_id = securitygroup['id']
        ip_protocol = 'tcp'
        from_port = 22
        to_port = rand_name('999')
        self.addCleanup(self.client.delete_security_group, securitygroup['id'])
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group_rule,
                          parent_group_id, ip_protocol, from_port, to_port)

    @attr(type=['negative', 'gate'])
    def test_security_group_rules_create_with_invalid_port_range(self):
        # Negative test: Creation of Security Group rule should FAIL
        # with invalid port range.
        # Creating a Security Group to add rule to it.
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = self.client.create_security_group(
            s_name, s_description)
        # Adding a rule to the created Security Group
        secgroup_id = securitygroup['id']
        ip_protocol = 'tcp'
        from_port = 22
        to_port = 21
        self.addCleanup(self.client.delete_security_group, securitygroup['id'])
        self.assertRaises(exceptions.BadRequest,
                          self.client.create_security_group_rule, secgroup_id,
                          ip_protocol, from_port, to_port)

    @testtools.skipIf(config.TempestConfig().service_available.neutron,
                      "Skipped until the Bug #1182384 is resolved")
    @attr(type=['negative', 'gate'])
    def test_security_group_rules_delete_with_invalid_id(self):
        # Negative test: Deletion of Security Group rule should be FAIL
        # with invalid rule id
        self.assertRaises(exceptions.NotFound,
                          self.client.delete_security_group_rule,
                          rand_name('999'))

    @attr(type='gate')
    def test_security_group_rules_list(self):
        # Positive test: Created Security Group rules should be
        # in the list of all rules
        # Creating a Security Group to add rules to it
        s_name = rand_name('securitygroup-')
        s_description = rand_name('description-')
        resp, securitygroup = \
            self.client.create_security_group(s_name, s_description)
        securitygroup_id = securitygroup['id']
        # Delete the Security Group at the end of this method
        self.addCleanup(self.client.delete_security_group, securitygroup_id)

        # Add a first rule to the created Security Group
        ip_protocol1 = 'tcp'
        from_port1 = 22
        to_port1 = 22
        resp, rule = \
            self.client.create_security_group_rule(securitygroup_id,
                                                   ip_protocol1,
                                                   from_port1, to_port1)
        rule1_id = rule['id']
        # Delete the Security Group rule1 at the end of this method
        self.addCleanup(self.client.delete_security_group_rule, rule1_id)

        # Add a second rule to the created Security Group
        ip_protocol2 = 'icmp'
        from_port2 = -1
        to_port2 = -1
        resp, rule = \
            self.client.create_security_group_rule(securitygroup_id,
                                                   ip_protocol2,
                                                   from_port2, to_port2)
        rule2_id = rule['id']
        # Delete the Security Group rule2 at the end of this method
        self.addCleanup(self.client.delete_security_group_rule, rule2_id)

        # Get rules of the created Security Group
        resp, rules = \
            self.client.list_security_group_rules(securitygroup_id)
        self.assertTrue(any([i for i in rules if i['id'] == rule1_id]))
        self.assertTrue(any([i for i in rules if i['id'] == rule2_id]))
Esempio n. 23
0
    def __init__(self,
                 username=None,
                 password=None,
                 tenant_name=None,
                 interface='json'):
        """
        We allow overriding of the credentials used within the various
        client classes managed by the Manager object. Left as None, the
        standard username/password/tenant_name is used.

        :param username: Override of the username
        :param password: Override of the password
        :param tenant_name: Override of the tenant name
        """
        self.config = config.TempestConfig()

        # If no creds are provided, we fall back on the defaults
        # in the config file for the Compute API.
        self.username = username or self.config.identity.username
        self.password = password or self.config.identity.password
        self.tenant_name = tenant_name or self.config.identity.tenant_name

        if None in (self.username, self.password, self.tenant_name):
            msg = ("Missing required credentials. "
                   "username: %(username)s, password: %(password)s, "
                   "tenant_name: %(tenant_name)s") % locals()
            raise exceptions.InvalidConfiguration(msg)

        self.auth_url = self.config.identity.uri
        self.auth_url_v3 = self.config.identity.uri_v3

        if self.config.identity.strategy == 'keystone':
            client_args = (self.config, self.username, self.password,
                           self.auth_url, self.tenant_name)

            if self.auth_url_v3:
                auth_version = 'v3'
                client_args_v3_auth = (self.config, self.username,
                                       self.password, self.auth_url_v3,
                                       self.tenant_name, auth_version)
            else:
                client_args_v3_auth = None

        else:
            client_args = (self.config, self.username, self.password,
                           self.auth_url)

            client_args_v3_auth = None

        try:
            self.servers_client = SERVERS_CLIENTS[interface](*client_args)
            self.limits_client = LIMITS_CLIENTS[interface](*client_args)
            self.images_client = IMAGES_CLIENTS[interface](*client_args)
            self.keypairs_client = KEYPAIRS_CLIENTS[interface](*client_args)
            self.quotas_client = QUOTAS_CLIENTS[interface](*client_args)
            self.flavors_client = FLAVORS_CLIENTS[interface](*client_args)
            ext_cli = EXTENSIONS_CLIENTS[interface](*client_args)
            self.extensions_client = ext_cli
            vol_ext_cli = VOLUMES_EXTENSIONS_CLIENTS[interface](*client_args)
            self.volumes_extensions_client = vol_ext_cli
            self.floating_ips_client = FLOAT_CLIENTS[interface](*client_args)
            self.snapshots_client = SNAPSHOTS_CLIENTS[interface](*client_args)
            self.volumes_client = VOLUMES_CLIENTS[interface](*client_args)
            self.volume_types_client = \
                VOLUME_TYPES_CLIENTS[interface](*client_args)
            self.identity_client = IDENTITY_CLIENT[interface](*client_args)
            self.identity_v3_client = \
                IDENTITY_V3_CLIENT[interface](*client_args)
            self.token_client = TOKEN_CLIENT[interface](self.config)
            self.security_groups_client = \
                SECURITY_GROUPS_CLIENT[interface](*client_args)
            self.interfaces_client = INTERFACES_CLIENT[interface](*client_args)
            self.endpoints_client = ENDPOINT_CLIENT[interface](*client_args)
            self.fixed_ips_client = FIXED_IPS_CLIENT[interface](*client_args)
            self.availability_zone_client = \
                AVAILABILITY_ZONE_CLIENT[interface](*client_args)
            self.service_client = SERVICE_CLIENT[interface](*client_args)
            self.aggregates_client = AGGREGATES_CLIENT[interface](*client_args)
            self.services_client = SERVICES_CLIENT[interface](*client_args)
            self.tenant_usages_client = \
                TENANT_USAGES_CLIENT[interface](*client_args)
            self.policy_client = POLICY_CLIENT[interface](*client_args)

            if client_args_v3_auth:
                self.servers_client_v3_auth = SERVERS_CLIENTS[interface](
                    *client_args_v3_auth)
            else:
                self.servers_client_v3_auth = None

        except KeyError:
            msg = "Unsupported interface type `%s'" % interface
            raise exceptions.InvalidConfiguration(msg)
        self.network_client = NetworkClient(*client_args)
        self.hosts_client = HostsClientJSON(*client_args)
        self.account_client = AccountClient(*client_args)
        self.image_client = ImageClientJSON(*client_args)
        self.image_client_v2 = ImageClientV2JSON(*client_args)
        self.container_client = ContainerClient(*client_args)
        self.object_client = ObjectClient(*client_args)
        self.orchestration_client = OrchestrationClient(*client_args)
        self.ec2api_client = botoclients.APIClientEC2(*client_args)
        self.s3_client = botoclients.ObjectClientS3(*client_args)
        self.custom_object_client = ObjectClientCustomizedHeader(*client_args)
        self.custom_account_client = \
            AccountClientCustomizedHeader(*client_args)
class LiveBlockMigrationTestJSON(base.BaseComputeAdminTest):
    _host_key = 'OS-EXT-SRV-ATTR:host'
    _interface = 'json'

    CONF = config.TempestConfig()

    @classmethod
    def setUpClass(cls):
        super(LiveBlockMigrationTestJSON, cls).setUpClass()

        cls.admin_hosts_client = cls.os_adm.hosts_client
        cls.admin_servers_client = cls.os_adm.servers_client

        cls.created_server_ids = []

    def _get_compute_hostnames(self):
        _resp, body = self.admin_hosts_client.list_hosts()
        return [
            host_record['host_name']
            for host_record in body
            if host_record['service'] == 'compute'
        ]

    def _get_server_details(self, server_id):
        _resp, body = self.admin_servers_client.get_server(server_id)
        return body

    def _get_host_for_server(self, server_id):
        return self._get_server_details(server_id)[self._host_key]

    def _migrate_server_to(self, server_id, dest_host):
        _resp, body = self.admin_servers_client.live_migrate_server(
            server_id, dest_host,
            self.config.compute.use_block_migration_for_live_migration)
        return body

    def _get_host_other_than(self, host):
        for target_host in self._get_compute_hostnames():
            if host != target_host:
                return target_host

    def _get_non_existing_host_name(self):
        random_name = ''.join(
            random.choice(string.ascii_uppercase) for x in range(20))

        self.assertNotIn(random_name, self._get_compute_hostnames())

        return random_name

    def _get_server_status(self, server_id):
        return self._get_server_details(server_id)['status']

    def _get_an_active_server(self):
        for server_id in self.created_server_ids:
            if 'ACTIVE' == self._get_server_status(server_id):
                return server_id
        else:
            _, server = self.create_server(wait_until="ACTIVE")
            server_id = server['id']
            self.password = server['adminPass']
            self.password = '******'
            self.created_server_ids.append(server_id)
            return server_id

    def _volume_clean_up(self, server_id, volume_id):
        resp, body = self.volumes_client.get_volume(volume_id)
        if body['status'] == 'in-use':
            self.servers_client.detach_volume(server_id, volume_id)
            self.volumes_client.wait_for_volume_status(volume_id, 'available')
        self.volumes_client.delete_volume(volume_id)

    @testtools.skipIf(not CONF.compute.live_migration_available,
                      'Live migration not available')
    @attr(type='gate')
    def test_live_block_migration(self):
        # Live block migrate an instance to another host
        if len(self._get_compute_hostnames()) < 2:
            raise self.skipTest(
                "Less than 2 compute nodes, skipping migration test.")
        server_id = self._get_an_active_server()
        actual_host = self._get_host_for_server(server_id)
        target_host = self._get_host_other_than(actual_host)
        self._migrate_server_to(server_id, target_host)
        self.servers_client.wait_for_server_status(server_id, 'ACTIVE')
        self.assertEquals(target_host, self._get_host_for_server(server_id))

    @testtools.skipIf(not CONF.compute.live_migration_available,
                      'Live migration not available')
    @attr(type='gate')
    def test_invalid_host_for_migration(self):
        # Migrating to an invalid host should not change the status
        server_id = self._get_an_active_server()
        target_host = self._get_non_existing_host_name()

        self.assertRaises(exceptions.BadRequest, self._migrate_server_to,
                          server_id, target_host)
        self.assertEquals('ACTIVE', self._get_server_status(server_id))

    @testtools.skipIf(not CONF.compute.live_migration_available or
                      not CONF.compute.use_block_migration_for_live_migration,
                      'Block Live migration not available')
    @testtools.skipIf(not CONF.compute.block_migrate_supports_cinder_iscsi,
                      'Block Live migration not configured for iSCSI')
    @attr(type='gate')
    def test_iscsi_volume(self):
        # Live block migrate an instance to another host
        if len(self._get_compute_hostnames()) < 2:
            raise self.skipTest(
                "Less than 2 compute nodes, skipping migration test.")
        server_id = self._get_an_active_server()
        actual_host = self._get_host_for_server(server_id)
        target_host = self._get_host_other_than(actual_host)

        resp, volume = self.volumes_client.create_volume(1,
                                                         display_name='test')

        self.volumes_client.wait_for_volume_status(volume['id'],
                                                   'available')
        self.addCleanup(self._volume_clean_up, server_id, volume['id'])

        # Attach the volume to the server
        self.servers_client.attach_volume(server_id, volume['id'],
                                          device='/dev/xvdb')
        self.volumes_client.wait_for_volume_status(volume['id'], 'in-use')

        self._migrate_server_to(server_id, target_host)
        self.servers_client.wait_for_server_status(server_id, 'ACTIVE')
        self.assertEquals(target_host, self._get_host_for_server(server_id))

    @classmethod
    def tearDownClass(cls):
        for server_id in cls.created_server_ids:
            cls.servers_client.delete_server(server_id)

        super(LiveBlockMigrationTestJSON, cls).tearDownClass()
Esempio n. 25
0
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging

import nose

from tempest import config
from tempest import openstack

LOG = logging.getLogger(__name__)

CONFIG = config.TempestConfig()
CREATE_IMAGE_ENABLED = CONFIG.compute.create_image_enabled
RESIZE_AVAILABLE = CONFIG.compute.resize_available
DISK_CONFIG_ENABLED = False
FLAVOR_EXTRA_DATA_ENABLED = False
MULTI_USER = False


# All compute tests -- single setup function
def setup_package():
    LOG.debug("Entering tempest.tests.compute.setup_package")

    global MULTI_USER, DISK_CONFIG_ENABLED, FLAVOR_EXTRA_DATA_ENABLED
    os = openstack.Manager()
    images_client = os.images_client
    flavors_client = os.flavors_client
Esempio n. 26
0
 def __init__(self):
     self.config = config.TempestConfig()
     self.services = {}
     self.services['image'] = image_service.Service(self.config)
     self.images = self.services['image']
Esempio n. 27
0
 def __init__(self, interface='json'):
     conf = config.TempestConfig()
     super(IdentityManager,
           self).__init__(conf.identity_admin.username,
                          conf.identity_admin.password,
                          conf.identity_admin.tenant_name, interface)
Esempio n. 28
0
class VolumeMultiBackendTest(base.BaseVolumeAdminTest):
    _interface = "json"

    multi_backend_enabled = config.TempestConfig().volume.multi_backend_enabled
    backend1_name = config.TempestConfig().volume.backend1_name
    backend2_name = config.TempestConfig().volume.backend2_name
    backend_names_equal = False
    if (backend1_name == backend2_name):
        backend_names_equal = True

    @classmethod
    @testtools.skipIf(not multi_backend_enabled,
                      "Cinder multi-backend feature is not available")
    def setUpClass(cls):
        super(VolumeMultiBackendTest, cls).setUpClass()

        adm_user = cls.config.identity.admin_username
        adm_pass = cls.config.identity.admin_password
        adm_tenant = cls.config.identity.admin_tenant_name
        auth_url = cls.config.identity.uri

        cls.client = volumes_client.VolumesClientJSON(cls.config, adm_user,
                                                      adm_pass, auth_url,
                                                      adm_tenant)
        cls.client2 = volume_types_client.VolumeTypesClientJSON(
            cls.config, adm_user, adm_pass, auth_url, adm_tenant)

        ## variables initialization
        type_name1 = rand_name('type-')
        type_name2 = rand_name('type-')
        cls.volume_type_list = []

        vol_name1 = rand_name('Volume-')
        vol_name2 = rand_name('Volume-')
        cls.volume_id_list = []

        try:
            ## Volume types creation
            extra_specs1 = {"volume_backend_name": cls.backend1_name}
            resp, cls.body1 = cls.client2.create_volume_type(
                type_name1, extra_specs=extra_specs1)
            cls.volume_type_list.append(cls.body1)

            extra_specs2 = {"volume_backend_name": cls.backend2_name}
            resp, cls.body2 = cls.client2.create_volume_type(
                type_name2, extra_specs=extra_specs2)
            cls.volume_type_list.append(cls.body2)

            ## Volumes creation
            resp, cls.volume1 = cls.client.create_volume(
                size=1, display_name=vol_name1, volume_type=type_name1)
            cls.client.wait_for_volume_status(cls.volume1['id'], 'available')
            cls.volume_id_list.append(cls.volume1['id'])

            resp, cls.volume2 = cls.client.create_volume(
                size=1, display_name=vol_name2, volume_type=type_name2)
            cls.client.wait_for_volume_status(cls.volume2['id'], 'available')
            cls.volume_id_list.append(cls.volume2['id'])
        except Exception:
            LOG.exception("setup failed")
            cls.tearDownClass()
            raise

    @classmethod
    def tearDownClass(cls):
        ## volumes deletion
        for volume_id in cls.volume_id_list:
            cls.client.delete_volume(volume_id)
            cls.client.wait_for_resource_deletion(volume_id)

        ## volume types deletion
        for volume_type in cls.volume_type_list:
            cls.client2.delete_volume_type(volume_type)

        super(VolumeMultiBackendTest, cls).tearDownClass()

    @attr(type=['smoke'])
    def test_multi_backend_enabled(self):
        # this test checks that multi backend is enabled for at least the
        # computes where the volumes created in setUp were made
        # if multi-backend is enabled: os-vol-attr:host should be like:
        # host@backend_name
        # this test fails if:
        # - multi backend is not enabled
        resp, fetched_volume = self.client.get_volume(self.volume1['id'])
        self.assertEqual(200, resp.status)

        volume_host1 = fetched_volume['os-vol-host-attr:host']
        msg = ("Multi-backend is not available for at least host "
               "%(volume_host1)s") % locals()
        self.assertTrue(len(volume_host1.split("@")) > 1, msg)

        resp, fetched_volume = self.client.get_volume(self.volume2['id'])
        self.assertEqual(200, resp.status)

        volume_host2 = fetched_volume['os-vol-host-attr:host']
        msg = ("Multi-backend is not available for at least host "
               "%(volume_host2)s") % locals()
        self.assertTrue(len(volume_host2.split("@")) > 1, msg)

    @attr(type='gate')
    def test_backend_name_distinction(self):
        # this test checks that the two volumes created at setUp doesn't
        # belong to the same backend (if they are in the same backend, that
        # means, volume_backend_name distinction is not working properly)
        # this test fails if:
        # - tempest.conf is not well configured
        # - the two volumes belongs to the same backend

        # checks tempest.conf
        msg = ("tempest.conf is not well configured, "
               "backend1_name and backend2_name are equal")
        self.assertEqual(self.backend_names_equal, False, msg)

        # checks the two volumes belongs to different backend
        resp, fetched_volume = self.client.get_volume(self.volume1['id'])
        volume_host1 = fetched_volume['os-vol-host-attr:host']

        resp, fetched_volume = self.client.get_volume(self.volume2['id'])
        volume_host2 = fetched_volume['os-vol-host-attr:host']

        msg = ("volume2 was created in the same backend as volume1: "
               "%(volume_host2)s.") % locals()
        self.assertNotEqual(volume_host2, volume_host1, msg)
Esempio n. 29
0
 def __init__(self, interface='json'):
     conf = config.TempestConfig()
     super(IdentityNaManager,
           self).__init__(conf.compute.username, conf.compute.password,
                          conf.compute.tenant_name, interface)
Esempio n. 30
0
class ListServerFiltersTestJSON(base.BaseV2ComputeTest):
    _interface = 'json'

    @classmethod
    def setUpClass(cls):
        super(ListServerFiltersTestJSON, cls).setUpClass()
        cls.client = cls.servers_client

        # Check to see if the alternate image ref actually exists...
        images_client = cls.images_client
        resp, images = images_client.list_images()

        if cls.image_ref != cls.image_ref_alt and \
            any([image for image in images
                 if image['id'] == cls.image_ref_alt]):
            cls.multiple_images = True
        else:
            cls.image_ref_alt = cls.image_ref

        # Do some sanity checks here. If one of the images does
        # not exist, fail early since the tests won't work...
        try:
            cls.images_client.get_image(cls.image_ref)
        except exceptions.NotFound:
            raise RuntimeError("Image %s (image_ref) was not found!" %
                               cls.image_ref)

        try:
            cls.images_client.get_image(cls.image_ref_alt)
        except exceptions.NotFound:
            raise RuntimeError("Image %s (image_ref_alt) was not found!" %
                               cls.image_ref_alt)

        cls.s1_name = rand_name(cls.__name__ + '-instance')
        resp, cls.s1 = cls.create_server(name=cls.s1_name,
                                         image_id=cls.image_ref,
                                         flavor=cls.flavor_ref,
                                         wait_until='ACTIVE')

        cls.s2_name = rand_name(cls.__name__ + '-instance')
        resp, cls.s2 = cls.create_server(name=cls.s2_name,
                                         image_id=cls.image_ref_alt,
                                         flavor=cls.flavor_ref,
                                         wait_until='ACTIVE')

        cls.s3_name = rand_name(cls.__name__ + '-instance')
        resp, cls.s3 = cls.create_server(name=cls.s3_name,
                                         image_id=cls.image_ref,
                                         flavor=cls.flavor_ref_alt,
                                         wait_until='ACTIVE')

        cls.fixed_network_name = cls.config.compute.fixed_network_name

    @utils.skip_unless_attr('multiple_images', 'Only one image found')
    @attr(type='gate')
    def test_list_servers_filter_by_image(self):
        # Filter the list of servers by image
        params = {'image': self.image_ref}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertIn(self.s1['id'], map(lambda x: x['id'], servers))
        self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s3['id'], map(lambda x: x['id'], servers))

    @attr(type='gate')
    def test_list_servers_filter_by_flavor(self):
        # Filter the list of servers by flavor
        params = {'flavor': self.flavor_ref_alt}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertNotIn(self.s1['id'], map(lambda x: x['id'], servers))
        self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s3['id'], map(lambda x: x['id'], servers))

    @attr(type='gate')
    def test_list_servers_filter_by_server_name(self):
        # Filter the list of servers by server name
        params = {'name': self.s1_name}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertIn(self.s1_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers))

    @attr(type='gate')
    def test_list_servers_filter_by_server_status(self):
        # Filter the list of servers by server status
        params = {'status': 'active'}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertIn(self.s1['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s2['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s3['id'], map(lambda x: x['id'], servers))

    @attr(type='gate')
    def test_list_servers_filter_by_limit(self):
        # Verify only the expected number of servers are returned
        params = {'limit': 1}
        resp, servers = self.client.list_servers(params)
        # when _interface='xml', one element for servers_links in servers
        self.assertEqual(1, len([x for x in servers['servers'] if 'id' in x]))

    @utils.skip_unless_attr('multiple_images', 'Only one image found')
    @attr(type='gate')
    def test_list_servers_detailed_filter_by_image(self):
        # Filter the detailed list of servers by image
        params = {'image': self.image_ref}
        resp, body = self.client.list_servers_with_detail(params)
        servers = body['servers']

        self.assertIn(self.s1['id'], map(lambda x: x['id'], servers))
        self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s3['id'], map(lambda x: x['id'], servers))

    @attr(type='gate')
    def test_list_servers_detailed_filter_by_flavor(self):
        # Filter the detailed list of servers by flavor
        params = {'flavor': self.flavor_ref_alt}
        resp, body = self.client.list_servers_with_detail(params)
        servers = body['servers']

        self.assertNotIn(self.s1['id'], map(lambda x: x['id'], servers))
        self.assertNotIn(self.s2['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s3['id'], map(lambda x: x['id'], servers))

    @attr(type='gate')
    def test_list_servers_detailed_filter_by_server_name(self):
        # Filter the detailed list of servers by server name
        params = {'name': self.s1_name}
        resp, body = self.client.list_servers_with_detail(params)
        servers = body['servers']

        self.assertIn(self.s1_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers))

    @attr(type='gate')
    def test_list_servers_detailed_filter_by_server_status(self):
        # Filter the detailed list of servers by server status
        params = {'status': 'active'}
        resp, body = self.client.list_servers_with_detail(params)
        servers = body['servers']

        self.assertIn(self.s1['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s2['id'], map(lambda x: x['id'], servers))
        self.assertIn(self.s3['id'], map(lambda x: x['id'], servers))
        self.assertEqual(['ACTIVE'] * 3, [x['status'] for x in servers])

    @attr(type='gate')
    def test_list_servers_filtered_by_name_wildcard(self):
        # List all servers that contains '-instance' in name
        params = {'name': '-instance'}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertIn(self.s1_name, map(lambda x: x['name'], servers))
        self.assertIn(self.s2_name, map(lambda x: x['name'], servers))
        self.assertIn(self.s3_name, map(lambda x: x['name'], servers))

        # Let's take random part of name and try to search it
        part_name = self.s1_name[6:-1]

        params = {'name': part_name}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertIn(self.s1_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers))

    @skip_because(bug="1170718")
    @attr(type='gate')
    def test_list_servers_filtered_by_ip(self):
        # Filter servers by ip
        # Here should be listed 1 server
        resp, self.s1 = self.client.get_server(self.s1['id'])
        ip = self.s1['addresses'][self.fixed_network_name][0]['addr']
        params = {'ip': ip}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertIn(self.s1_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s2_name, map(lambda x: x['name'], servers))
        self.assertNotIn(self.s3_name, map(lambda x: x['name'], servers))

    @skip_because(bug="1182883",
                  condition=config.TempestConfig().service_available.neutron)
    @attr(type='gate')
    def test_list_servers_filtered_by_ip_regex(self):
        # Filter servers by regex ip
        # List all servers filtered by part of ip address.
        # Here should be listed all servers
        resp, self.s1 = self.client.get_server(self.s1['id'])
        ip = self.s1['addresses'][self.fixed_network_name][0]['addr'][0:-3]
        params = {'ip': ip}
        resp, body = self.client.list_servers(params)
        servers = body['servers']

        self.assertIn(self.s1_name, map(lambda x: x['name'], servers))
        self.assertIn(self.s2_name, map(lambda x: x['name'], servers))
        self.assertIn(self.s3_name, map(lambda x: x['name'], servers))

    @attr(type='gate')
    def test_list_servers_detailed_limit_results(self):
        # Verify only the expected number of detailed results are returned
        params = {'limit': 1}
        resp, servers = self.client.list_servers_with_detail(params)
        self.assertEqual(1, len(servers['servers']))