Exemplo n.º 1
0
    def test_nova(self, nova):
        reload(clients)

        # test normal flow
        context = mock.Mock(
            auth_token='fake_token',
            service_catalog=[{'type': 'computev21',
                              'endpoints': [{'publicURL': 'novav21_url'}]}])
        with fixtures.LoggerFixture() as logs:
            res = clients.nova(context)
        self.assertEqual(nova.return_value, res)
        nova.assert_called_with(
            '2.3', bypass_url='novav21_url', cacert=None, insecure=False,
            auth_url='keystone_url', auth_token='fake_token',
            username=None, api_key=None, project_id=None)
        self.assertEqual(0, len(logs.output))

        # test switching to v2 client
        nova.side_effect = [nova_exception.UnsupportedVersion(), 'v2_client']
        with fixtures.LoggerFixture() as logs:
            res = clients.nova(context)
        self.assertEqual('v2_client', res)
        nova.assert_called_with(
            '2', bypass_url='novav21_url', cacert=None, insecure=False,
            auth_url='keystone_url', auth_token='fake_token',
            username=None, api_key=None, project_id=None)
        self.assertNotEqual(0, len(logs.output))

        # test raising of an exception if v2 client is not supported as well
        nova.side_effect = nova_exception.UnsupportedVersion()
        self.assertRaises(nova_exception.UnsupportedVersion,
                          clients.nova, context)

        nova.side_effect = None
        reload(clients)

        # test switching to 'compute' service type
        context.service_catalog = [{'type': 'compute',
                                    'endpoints': [{'publicURL': 'nova_url'}]}]
        with fixtures.LoggerFixture() as logs:
            res = clients.nova(context)
        nova.assert_called_with(
            '2.3', bypass_url='nova_url', cacert=None, insecure=False,
            auth_url='keystone_url', auth_token='fake_token',
            username=None, api_key=None, project_id=None)
        self.assertNotEqual(0, len(logs.output))

        # test behavior if 'compute' service type is not found as well
        context.service_catalog = [{'type': 'fake'}]
        clients.nova(context)
        nova.assert_called_with(
            '2.3', bypass_url=None, cacert=None, insecure=False,
            auth_url='keystone_url', auth_token='fake_token',
            username=None, api_key=None, project_id=None)
Exemplo n.º 2
0
    def test_get_api_version(self, nova):
        context = mock.NonCallableMock(session=mock.sentinel.session)
        v2 = mock.NonCallableMock()
        v2.configure_mock(id='v2',
                          version='',
                          links=[{
                              'href': 'http://host:port/path/v2/'
                          }])
        v2_1 = mock.NonCallableMock()
        v2_1.configure_mock(id='v2.1',
                            version='2.11',
                            links=[{
                                'href': 'http://host:port/path/v2.1/'
                            }])

        # test normal flow
        nova.return_value.versions.get_current.return_value = v2_1
        with fixtures.LoggerFixture(
                format='[%(levelname)s] %(message)s') as logs:
            res = clients._get_nova_api_version(context)
        self.assertEqual(clients.REQUIRED_NOVA_API_MICROVERSION, res)
        nova.assert_called_with('2.1',
                                service_type='compute',
                                session=mock.sentinel.session)
        nova.return_value.versions.get_current.assert_called_with()
        self.assertTrue(logs.output.startswith('[INFO]'))

        # test Nova doesn't supprt required microversion
        v2_1.version = '2.2'
        with fixtures.LoggerFixture(
                format='[%(levelname)s] %(message)s') as logs:
            res = clients._get_nova_api_version(context)
        self.assertEqual('2.2', res)
        self.assertTrue(logs.output.startswith('[WARNING]'))

        # test service type is not v2.1
        nova.return_value.versions.get_current.return_value = v2
        self.configure(nova_service_type='compute_legacy')
        with fixtures.LoggerFixture(
                format='[%(levelname)s] %(message)s') as logs:
            res = clients._get_nova_api_version(context)
        self.assertEqual('2', res)
        self.assertTrue(logs.output.startswith('[WARNING]'))
        self.configure(nova_service_type='compute')

        # test service url is not found in version list
        nova.return_value.versions.get_current.return_value = None
        with fixtures.LoggerFixture(
                format='[%(levelname)s] %(message)s') as logs:
            res = clients._get_nova_api_version(context)
        self.assertEqual(clients.REQUIRED_NOVA_API_MICROVERSION, res)
        self.assertTrue(logs.output.startswith('[WARNING]'))
Exemplo n.º 3
0
    def setUp(self):
        super(BaseTestCase, self).setUp()
        if not self.setUpClassCalled:
            raise RuntimeError("setUpClass does not calls the super's"
                               "setUpClass in the " + self.__class__.__name__)
        at_exit_set.add(self.__class__)
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        if (os.environ.get('OS_STDOUT_CAPTURE') == 'True'
                or os.environ.get('OS_STDOUT_CAPTURE') == '1'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if (os.environ.get('OS_STDERR_CAPTURE') == 'True'
                or os.environ.get('OS_STDERR_CAPTURE') == '1'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if (os.environ.get('OS_LOG_CAPTURE') != 'False'
                and os.environ.get('OS_LOG_CAPTURE') != '0'):
            self.useFixture(
                fixtures.LoggerFixture(nuke_handlers=False,
                                       format=self.log_format,
                                       level=None))
Exemplo n.º 4
0
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        environ_enabled = (lambda var_name: strutils.bool_from_string(
            os.environ.get(var_name)))
        if environ_enabled('OS_STDOUT_CAPTURE'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if environ_enabled('OS_STDERR_CAPTURE'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if environ_enabled('OS_LOG_CAPTURE'):
            log_format = '%(levelname)s [%(name)s] %(message)s'
            if environ_enabled('OS_DEBUG'):
                level = logging.DEBUG
            else:
                level = logging.INFO
            self.useFixture(
                fixtures.LoggerFixture(nuke_handlers=False,
                                       format=log_format,
                                       level=level))
Exemplo n.º 5
0
 def setUp(self):
     super().setUp()
     stdout = self.useFixture(fixtures.StringStream('stdout')).stream
     self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
     stderr = self.useFixture(fixtures.StringStream('stderr')).stream
     self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
     self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                            level=None))
Exemplo n.º 6
0
 def test_check_and_create_default_vpc_failed(self, create_vpc):
     self.configure(disable_ec2_classic=True)
     create_vpc.side_effect = Exception()
     with fixtures.LoggerFixture(
             format='[%(levelname)s] %(message)s') as log:
         vpc_api._check_and_create_default_vpc(self.context)
     self.assertTrue(
         log.output.startswith('[ERROR] Failed to create default vpc'))
Exemplo n.º 7
0
 def setUp(self):
     super().setUp()
     if os.environ.get("QISKIT_TEST_CAPTURE_STREAMS"):
         stdout = self.useFixture(fixtures.StringStream("stdout")).stream
         self.useFixture(fixtures.MonkeyPatch("sys.stdout", stdout))
         stderr = self.useFixture(fixtures.StringStream("stderr")).stream
         self.useFixture(fixtures.MonkeyPatch("sys.stderr", stderr))
         self.useFixture(fixtures.LoggerFixture(nuke_handlers=False, level=None))
Exemplo n.º 8
0
 def setUp(self):
     super(TestWrapper, self).setUp()
     self.useFixture(fixtures.LoggerFixture())
     qr = QuantumRegister(3)
     cr = ClassicalRegister(3)
     self.circuit = QuantumCircuit(qr, cr)
     self.circuit.ccx(qr[0], qr[1], qr[2])
     self.circuit.measure(qr, cr)
Exemplo n.º 9
0
 def setUp(self):
     super(TestCase, self).setUp()
     if os.environ.get('OS_STDOUT_CAPTURE') in self.true:
         stdout = self.useFixture(fixtures.StringStream('stdout')).stream
         self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
     if os.environ.get('OS_STDERR_CAPTURE') in self.true:
         stderr = self.useFixture(fixtures.StringStream('stderr')).stream
         self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
     if (os.environ.get('OS_LOG_CAPTURE') != 'False'
             and os.environ.get('OS_LOG_CAPTURE') != '0'):
         self.useFixture(
             fixtures.LoggerFixture(nuke_handlers=False, level=None))
Exemplo n.º 10
0
 def setUp(self):
     super().setUp()
     if self.__setup_called:
         raise ValueError(
             "In File: %s\n"
             "TestCase.setUp was already called. Do not explicitly call "
             "setUp from your tests. In your own setUp, use super to call "
             "the base setUp." %
             (sys.modules[self.__class__.__module__].__file__, ))
     self.__setup_called = True
     if os.environ.get('QISKIT_TEST_CAPTURE_STREAMS'):
         stdout = self.useFixture(fixtures.StringStream('stdout')).stream
         self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
         stderr = self.useFixture(fixtures.StringStream('stderr')).stream
         self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
         self.useFixture(
             fixtures.LoggerFixture(nuke_handlers=False, level=None))
Exemplo n.º 11
0
    def setUp(self):
        self.LOG.info('Starting: %s', self._testMethodName)
        super(TestCase, self).setUp()

        self.client = client.BarbicanClient()

        stdout_capture = os.environ.get('OS_STDOUT_CAPTURE')
        stderr_capture = os.environ.get('OS_STDERR_CAPTURE')
        log_capture = os.environ.get('OS_LOG_CAPTURE')

        if ((stdout_capture and stdout_capture.lower() == 'true') or
                stdout_capture == '1'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if ((stderr_capture and stderr_capture.lower() == 'true') or
                stderr_capture == '1'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if ((log_capture and log_capture.lower() == 'true') or
                log_capture == '1'):
            self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                                   format=self.log_format,
                                                   level=logging.DEBUG))
Exemplo n.º 12
0
 def setUp(self):
     super(TestIbmqQasmSimulator, self).setUp()
     self.useFixture(fixtures.LoggerFixture())
Exemplo n.º 13
0
    def setUp(self):
        super(ClientTestBase, self).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:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

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

        if (os.environ.get('OS_LOG_CAPTURE') != 'False'
                and os.environ.get('OS_LOG_CAPTURE') != '0'):
            self.useFixture(
                fixtures.LoggerFixture(nuke_handlers=False,
                                       format=self.log_format,
                                       level=None))

        # Collecting of credentials:
        #
        # Support the existence of a functional_creds.conf for
        # testing. This makes it possible to use a config file.
        #
        # Those variables can be overridden by environmental variables
        # as well to support existing users running these the old
        # way. We should deprecate that.

        # TODO(sdague): while we collect this information in
        # tempest-lib, we do it in a way that's not available for top
        # level tests. Long term this probably needs to be in the base
        # class.
        user = os.environ.get('OS_USERNAME')
        passwd = os.environ.get('OS_PASSWORD')
        tenant = os.environ.get('OS_TENANT_NAME')
        auth_url = os.environ.get('OS_AUTH_URL')

        config = ConfigParser.RawConfigParser()
        if config.read('functional_creds.conf'):
            # the OR pattern means the environment is preferred for
            # override
            user = user or config.get('admin', 'user')
            passwd = passwd or config.get('admin', 'pass')
            tenant = tenant or config.get('admin', 'tenant')
            auth_url = auth_url or config.get('auth', 'uri')

        # TODO(sdague): we made a lot of fun of the glanceclient team
        # for version as int in first parameter. I guess we know where
        # they copied it from.
        self.client = novaclient.client.Client(2,
                                               user,
                                               passwd,
                                               tenant,
                                               auth_url=auth_url)

        # pick some reasonable flavor / image combo
        self.flavor = pick_flavor(self.client.flavors.list())
        self.image = pick_image(self.client.images.list())

        # create a CLI client in case we'd like to do CLI
        # testing. tempest_lib does this realy weird thing where it
        # builds a giant factory of all the CLIs that it knows
        # about. Eventually that should really be unwound into
        # something more sensible.
        cli_dir = os.environ.get(
            'OS_NOVACLIENT_EXEC_DIR',
            os.path.join(os.path.abspath('.'), '.tox/functional/bin'))

        self.cli_clients = tempest_lib.cli.base.CLIClient(username=user,
                                                          password=passwd,
                                                          tenant_name=tenant,
                                                          uri=auth_url,
                                                          cli_dir=cli_dir)
Exemplo n.º 14
0
    def setUp(self):
        super(ClientTestBase, self).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:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

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

        if (os.environ.get('OS_LOG_CAPTURE') != 'False'
                and os.environ.get('OS_LOG_CAPTURE') != '0'):
            self.useFixture(
                fixtures.LoggerFixture(nuke_handlers=False,
                                       format=self.log_format,
                                       level=None))

        # Collecting of credentials:
        #
        # Grab the cloud config from a user's clouds.yaml file.
        # First look for a functional_admin cloud, as this is a cloud
        # that the user may have defined for functional testing that has
        # admin credentials.
        # If that is not found, get the devstack config and override the
        # username and project_name to be admin so that admin credentials
        # will be used.
        #
        # Finally, fall back to looking for environment variables to support
        # existing users running these the old way. We should deprecate that
        # as tox 2.0 blanks out environment.
        #
        # TODO(sdague): while we collect this information in
        # tempest-lib, we do it in a way that's not available for top
        # level tests. Long term this probably needs to be in the base
        # class.
        openstack_config = os_client_config.config.OpenStackConfig()
        try:
            cloud_config = openstack_config.get_one_cloud('functional_admin')
        except os_client_config.exceptions.OpenStackConfigException:
            try:
                cloud_config = openstack_config.get_one_cloud(
                    'devstack',
                    auth=dict(username='******', project_name='admin'))
            except os_client_config.exceptions.OpenStackConfigException:
                try:
                    cloud_config = openstack_config.get_one_cloud('envvars')
                except os_client_config.exceptions.OpenStackConfigException:
                    cloud_config = None

        if cloud_config is None:
            raise NoCloudConfigException(
                "Cloud not find a cloud named functional_admin or a cloud"
                " named devstack. Please check your clouds.yaml file and"
                " try again.")
        auth_info = cloud_config.config['auth']

        user = auth_info['username']
        passwd = auth_info['password']
        tenant = auth_info['project_name']
        auth_url = auth_info['auth_url']

        # TODO(sdague): we made a lot of fun of the glanceclient team
        # for version as int in first parameter. I guess we know where
        # they copied it from.
        self.client = novaclient.client.Client(2,
                                               user,
                                               passwd,
                                               tenant,
                                               auth_url=auth_url)

        # pick some reasonable flavor / image combo
        self.flavor = pick_flavor(self.client.flavors.list())
        self.image = pick_image(self.client.images.list())

        # create a CLI client in case we'd like to do CLI
        # testing. tempest_lib does this realy weird thing where it
        # builds a giant factory of all the CLIs that it knows
        # about. Eventually that should really be unwound into
        # something more sensible.
        cli_dir = os.environ.get(
            'OS_NOVACLIENT_EXEC_DIR',
            os.path.join(os.path.abspath('.'), '.tox/functional/bin'))

        self.cli_clients = tempest_lib.cli.base.CLIClient(username=user,
                                                          password=passwd,
                                                          tenant_name=tenant,
                                                          uri=auth_url,
                                                          cli_dir=cli_dir)
Exemplo n.º 15
0
 def setUp(self):
     super().setUp()
     self.useFixture(fixtures.LoggerFixture())
     tmpdir = self.useFixture(fixtures.TempDir())
     self.config_path = tmpdir.join('config.yaml')
     create_test_config(filename=self.config_path)
Exemplo n.º 16
0
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

        # Create default notifier
        self.notifier = fake_notifier.get_fake_notifier()

        # Mock rpc get notifier with fake notifier method that joins all
        # notifications with the default notifier
        p = mock.patch('cinder.rpc.get_notifier',
                       side_effect=self._get_joined_notifier)
        p.start()

        # Unit tests do not need to use lazy gettext
        i18n.enable_lazy(False)

        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        environ_enabled = (lambda var_name: strutils.bool_from_string(
            os.environ.get(var_name)))
        if environ_enabled('OS_STDOUT_CAPTURE'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if environ_enabled('OS_STDERR_CAPTURE'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if environ_enabled('OS_LOG_CAPTURE'):
            log_format = '%(levelname)s [%(name)s] %(message)s'
            if environ_enabled('OS_DEBUG'):
                level = logging.DEBUG
            else:
                level = logging.INFO
            self.useFixture(
                fixtures.LoggerFixture(nuke_handlers=False,
                                       format=log_format,
                                       level=level))

        rpc.add_extra_exmods("cinder.tests.unit")
        self.addCleanup(rpc.clear_extra_exmods)
        self.addCleanup(rpc.cleanup)

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_driver = 'fake'
        self.messaging_conf.response_timeout = 15
        self.useFixture(self.messaging_conf)
        rpc.init(CONF)

        conf_fixture.set_defaults(CONF)
        CONF([], default_config_files=[])

        # NOTE(vish): We need a better method for creating fixtures for tests
        #             now that we have some required db setup for the system
        #             to work properly.
        self.start = timeutils.utcnow()

        CONF.set_default('connection', 'sqlite://', 'database')
        CONF.set_default('sqlite_synchronous', False, 'database')

        global _DB_CACHE
        if not _DB_CACHE:
            _DB_CACHE = Database(sqla_api,
                                 migration,
                                 sql_connection=CONF.database.connection,
                                 sqlite_db=CONF.database.sqlite_db,
                                 sqlite_clean_db=CONF.sqlite_clean_db)
        self.useFixture(_DB_CACHE)

        # NOTE(danms): Make sure to reset us back to non-remote objects
        # for each test to avoid interactions. Also, backup the object
        # registry.
        objects_base.CinderObject.indirection_api = None
        self._base_test_obj_backup = copy.copy(
            objects_base.CinderObjectRegistry._registry._obj_classes)
        self.addCleanup(self._restore_obj_registry)

        # emulate some of the mox stuff, we can't use the metaclass
        # because it screws with our generators
        mox_fixture = self.useFixture(moxstubout.MoxStubout())
        self.mox = mox_fixture.mox
        self.stubs = mox_fixture.stubs
        self.addCleanup(CONF.reset)
        self.addCleanup(self._common_cleanup)
        self.injected = []
        self._services = []

        fake_notifier.stub_notifier(self.stubs)

        self.override_config('fatal_exception_format_errors', True)
        # This will be cleaned up by the NestedTempfile fixture
        lock_path = self.useFixture(fixtures.TempDir()).path
        self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF))
        self.fixture.config(lock_path=lock_path, group='oslo_concurrency')
        lockutils.set_defaults(lock_path)
        self.override_config('policy_file',
                             os.path.join(
                                 os.path.abspath(
                                     os.path.join(
                                         os.path.dirname(__file__),
                                         '..',
                                     )), 'cinder/tests/unit/policy.json'),
                             group='oslo_policy')

        self._disable_osprofiler()

        # NOTE(geguileo): This is required because common get_by_id method in
        # cinder.db.sqlalchemy.api caches get methods and if we use a mocked
        # get method in one test it would carry on to the next test.  So we
        # clear out the cache.
        sqla_api._GET_METHODS = {}
Exemplo n.º 17
0
    def setUp(self):
        super(ClientTestBase, self).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:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

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

        if (os.environ.get('OS_LOG_CAPTURE') != 'False'
                and os.environ.get('OS_LOG_CAPTURE') != '0'):
            self.useFixture(
                fixtures.LoggerFixture(nuke_handlers=False,
                                       format=self.log_format,
                                       level=None))

        # Collecting of credentials:
        #
        # Grab the cloud config from a user's clouds.yaml file.
        # First look for a functional_admin cloud, as this is a cloud
        # that the user may have defined for functional testing that has
        # admin credentials.
        # If that is not found, get the devstack config and override the
        # username and project_name to be admin so that admin credentials
        # will be used.
        #
        # Finally, fall back to looking for environment variables to support
        # existing users running these the old way. We should deprecate that
        # as tox 2.0 blanks out environment.
        #
        # TODO(sdague): while we collect this information in
        # tempest-lib, we do it in a way that's not available for top
        # level tests. Long term this probably needs to be in the base
        # class.
        openstack_config = os_client_config.config.OpenStackConfig()
        try:
            cloud_config = openstack_config.get_one_cloud('functional_admin')
        except os_client_config.exceptions.OpenStackConfigException:
            try:
                cloud_config = openstack_config.get_one_cloud(
                    'devstack',
                    auth=dict(username='******', project_name='admin'))
            except os_client_config.exceptions.OpenStackConfigException:
                try:
                    cloud_config = openstack_config.get_one_cloud('envvars')
                except os_client_config.exceptions.OpenStackConfigException:
                    cloud_config = None

        if cloud_config is None:
            raise NoCloudConfigException(
                "Could not find a cloud named functional_admin or a cloud"
                " named devstack. Please check your clouds.yaml file and"
                " try again.")
        auth_info = cloud_config.config['auth']

        user = auth_info['username']
        passwd = auth_info['password']
        self.project_name = auth_info['project_name']
        auth_url = auth_info['auth_url']
        user_domain_id = auth_info['user_domain_id']
        self.project_domain_id = auth_info['project_domain_id']

        if 'insecure' in cloud_config.config:
            self.insecure = cloud_config.config['insecure']
        else:
            self.insecure = False

        auth = identity.Password(username=user,
                                 password=passwd,
                                 project_name=self.project_name,
                                 auth_url=auth_url,
                                 project_domain_id=self.project_domain_id,
                                 user_domain_id=user_domain_id)
        session = ksession.Session(auth=auth, verify=(not self.insecure))

        self.client = self._get_novaclient(session)

        self.glance = glanceclient.Client('2', session=session)

        # pick some reasonable flavor / image combo
        if "flavor" not in CACHE:
            CACHE["flavor"] = pick_flavor(self.client.flavors.list())
        if "image" not in CACHE:
            CACHE["image"] = pick_image(self.glance.images.list())
        self.flavor = CACHE["flavor"]
        self.image = CACHE["image"]

        if "network" not in CACHE:
            # Get the networks from neutron.
            neutron = neutronclient.Client(session=session)
            neutron_networks = neutron.list_networks()['networks']
            # Convert the neutron dicts to Network objects.
            nets = []
            for network in neutron_networks:
                nets.append(networks.Network(networks.NeutronManager, network))
            # Keep track of whether or not there are multiple networks
            # available to the given tenant because if so, a specific
            # network ID has to be passed in on server create requests
            # otherwise the server POST will fail with a 409.
            CACHE['multiple_networks'] = len(nets) > 1
            CACHE["network"] = pick_network(nets)
        self.network = CACHE["network"]
        self.multiple_networks = CACHE['multiple_networks']

        # create a CLI client in case we'd like to do CLI
        # testing. tempest.lib does this really weird thing where it
        # builds a giant factory of all the CLIs that it knows
        # about. Eventually that should really be unwound into
        # something more sensible.
        cli_dir = os.environ.get(
            'OS_NOVACLIENT_EXEC_DIR',
            os.path.join(os.path.abspath('.'), '.tox/functional/bin'))

        self.cli_clients = tempest.lib.cli.base.CLIClient(
            username=user,
            password=passwd,
            tenant_name=self.project_name,
            uri=auth_url,
            cli_dir=cli_dir,
            insecure=self.insecure)

        self.keystone = keystoneclient.Client(session=session,
                                              username=user,
                                              password=passwd)
        self.cinder = cinderclient.Client(auth=auth, session=session)
Exemplo n.º 18
0
Arquivo: test.py Projeto: e0ne/brick
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        environ_enabled = (lambda var_name:
                           strutils.bool_from_string(os.environ.get(var_name)))
        if environ_enabled('OS_STDOUT_CAPTURE'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if environ_enabled('OS_STDERR_CAPTURE'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if environ_enabled('OS_LOG_CAPTURE'):
            log_format = '%(levelname)s [%(name)s] %(message)s'
            if environ_enabled('OS_DEBUG'):
                level = logging.DEBUG
            else:
                level = logging.INFO
            self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                                   format=log_format,
                                                   level=level))

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_driver = 'fake'
        self.messaging_conf.response_timeout = 15
        self.useFixture(self.messaging_conf)

        conf_fixture.set_defaults(CONF)
        CONF([], default_config_files=[])

        # NOTE(vish): We need a better method for creating fixtures for tests
        #             now that we have some required db setup for the system
        #             to work properly.
        self.start = timeutils.utcnow()

        # emulate some of the mox stuff, we can't use the metaclass
        # because it screws with our generators
        self.mox = mox.Mox()
        self.stubs = stubout.StubOutForTesting()
        self.addCleanup(CONF.reset)
        self.addCleanup(self.mox.UnsetStubs)
        self.addCleanup(self.stubs.UnsetAll)
        self.addCleanup(self.stubs.SmartUnsetAll)
        self.addCleanup(self.mox.VerifyAll)
        self.addCleanup(self._common_cleanup)
        self.injected = []

        CONF.set_override('fatal_exception_format_errors', True)
        # This will be cleaned up by the NestedTempfile fixture
        CONF.set_override('lock_path', tempfile.mkdtemp())
        CONF.set_override('policy_file',
                          os.path.join(
                              os.path.abspath(
                                  os.path.join(
                                      os.path.dirname(__file__),
                                      '..',
                                  )
                              ),
                              'brick/tests/policy.json'))
Exemplo n.º 19
0
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

        # Import cinder objects for test cases
        objects.register_all()

        # Unit tests do not need to use lazy gettext
        i18n.enable_lazy(False)

        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        environ_enabled = (lambda var_name:
                           strutils.bool_from_string(os.environ.get(var_name)))
        if environ_enabled('OS_STDOUT_CAPTURE'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if environ_enabled('OS_STDERR_CAPTURE'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if environ_enabled('OS_LOG_CAPTURE'):
            log_format = '%(levelname)s [%(name)s] %(message)s'
            if environ_enabled('OS_DEBUG'):
                level = logging.DEBUG
            else:
                level = logging.INFO
            self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                                   format=log_format,
                                                   level=level))

        rpc.add_extra_exmods("cinder.tests.unit")
        self.addCleanup(rpc.clear_extra_exmods)
        self.addCleanup(rpc.cleanup)

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_driver = 'fake'
        self.messaging_conf.response_timeout = 15
        self.useFixture(self.messaging_conf)
        rpc.init(CONF)

        conf_fixture.set_defaults(CONF)
        CONF([], default_config_files=[])

        # NOTE(vish): We need a better method for creating fixtures for tests
        #             now that we have some required db setup for the system
        #             to work properly.
        self.start = timeutils.utcnow()

        CONF.set_default('connection', 'sqlite://', 'database')
        CONF.set_default('sqlite_synchronous', False, 'database')

        global _DB_CACHE
        if not _DB_CACHE:
            _DB_CACHE = Database(sqla_api, migration,
                                 sql_connection=CONF.database.connection,
                                 sqlite_db=CONF.database.sqlite_db,
                                 sqlite_clean_db=CONF.sqlite_clean_db)
        self.useFixture(_DB_CACHE)

        # emulate some of the mox stuff, we can't use the metaclass
        # because it screws with our generators
        self.mox = mox.Mox()
        self.stubs = stubout.StubOutForTesting()
        self.addCleanup(CONF.reset)
        self.addCleanup(self.mox.UnsetStubs)
        self.addCleanup(self.stubs.UnsetAll)
        self.addCleanup(self.stubs.SmartUnsetAll)
        self.addCleanup(self.mox.VerifyAll)
        self.addCleanup(self._common_cleanup)
        self.injected = []
        self._services = []

        fake_notifier.stub_notifier(self.stubs)

        self.override_config('fatal_exception_format_errors', True)
        # This will be cleaned up by the NestedTempfile fixture
        lock_path = self.useFixture(fixtures.TempDir()).path
        self.fixture = self.useFixture(
            config_fixture.Config(lockutils.CONF))
        self.fixture.config(lock_path=lock_path,
                            group='oslo_concurrency')
        lockutils.set_defaults(lock_path)
        self.override_config('policy_file',
                             os.path.join(
                                 os.path.abspath(
                                     os.path.join(
                                         os.path.dirname(__file__),
                                         '..',
                                     )
                                 ),
                                 'cinder/tests/unit/policy.json'))
Exemplo n.º 20
0
 def setUp(self):
     super(TestDomainConfigFinder, self).setUp()
     self.logging = self.useFixture(fixtures.LoggerFixture())
Exemplo n.º 21
0
 def setUp(self):
     super().setUp()
     self.useFixture(fixtures.LoggerFixture())
Exemplo n.º 22
0
    def setUp(self):
        super(ClientTestBase, self).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:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

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

        if (os.environ.get('OS_LOG_CAPTURE') != 'False' and
                os.environ.get('OS_LOG_CAPTURE') != '0'):
            self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                                   format=self.log_format,
                                                   level=None))

        # TODO(sdague): while we collect this information in
        # tempest-lib, we do it in a way that's not available for top
        # level tests. Long term this probably needs to be in the base
        # class.
        user = os.environ['OS_USERNAME']
        passwd = os.environ['OS_PASSWORD']
        tenant = os.environ['OS_TENANT_NAME']
        auth_url = os.environ['OS_AUTH_URL']

        # TODO(sdague): we made a lot of fun of the glanceclient team
        # for version as int in first parameter. I guess we know where
        # they copied it from.
        self.client = novaclient.client.Client(
            2, user, passwd, tenant,
            auth_url=auth_url)

        # pick some reasonable flavor / image combo
        self.flavor = pick_flavor(self.client.flavors.list())
        self.image = pick_image(self.client.images.list())

        # create a CLI client in case we'd like to do CLI
        # testing. tempest_lib does this realy weird thing where it
        # builds a giant factory of all the CLIs that it knows
        # about. Eventually that should really be unwound into
        # something more sensible.
        cli_dir = os.environ.get(
            'OS_NOVACLIENT_EXEC_DIR',
            os.path.join(os.path.abspath('.'), '.tox/functional/bin'))

        self.cli_clients = tempest_lib.cli.base.CLIClient(
            username=os.environ.get('OS_USERNAME'),
            password=os.environ.get('OS_PASSWORD'),
            tenant_name=os.environ.get('OS_TENANT_NAME'),
            uri=os.environ.get('OS_AUTH_URL'),
            cli_dir=cli_dir)