Ejemplo n.º 1
0
    def setUp(self):
        super(TestCase, self).setUp()
        self.useFixture(conf_fixture.ConfReloadFixture())
        self.policy = self.useFixture(policy_fixture.PolicyFixture())
        self.messaging_conf = self.useFixture(conffixture.ConfFixture(CONF))
        self.messaging_conf.transport_driver = 'fake'

        cfg.CONF.set_override("auth_type",
                              "admin_token",
                              group='keystone_authtoken',
                              enforce_type=True)
        cfg.CONF.set_override("auth_uri",
                              "http://127.0.0.1/identity",
                              group='keystone_authtoken',
                              enforce_type=True)

        app_config_path = os.path.join(os.path.dirname(__file__), 'config.py')
        self.app = testing.load_test_app(app_config_path)
        self.token_info = {
            'token': {
                'project': {
                    'id': 'fake_project'
                },
                'user': {
                    'id': 'fake_user'
                }
            }
        }
        self.context = watcher_context.RequestContext(
            auth_token_info=self.token_info,
            project_id='fake_project',
            user_id='fake_user')

        self.policy = self.useFixture(policy_fixture.PolicyFixture())

        def make_context(*args, **kwargs):
            # If context hasn't been constructed with token_info
            if not kwargs.get('auth_token_info'):
                kwargs['auth_token_info'] = copy.deepcopy(self.token_info)
            if not kwargs.get('project_id'):
                kwargs['project_id'] = 'fake_project'
            if not kwargs.get('user_id'):
                kwargs['user_id'] = 'fake_user'

            context = watcher_context.RequestContext(*args, **kwargs)
            return watcher_context.RequestContext.from_dict(context.to_dict())

        p = mock.patch.object(watcher_context,
                              'make_context',
                              side_effect=make_context)
        self.mock_make_context = p.start()
        self.addCleanup(p.stop)

        self.useFixture(conf_fixture.ConfFixture(cfg.CONF))
        self._reset_singletons()

        self._base_test_obj_backup = copy.copy(
            objects_base.WatcherObject._obj_classes)
        self.addCleanup(self._restore_obj_registry)
        self.addCleanup(self._reset_singletons)
Ejemplo n.º 2
0
 def setUp(self):
     super(OrchestratorTest, self).setUp()
     messaging_conf = self.useFixture(conffixture.ConfFixture(self.conf))
     messaging_conf.transport_url = 'fake:/'
     self.conf.set_override('backend', 'keystone', 'fetcher')
     self.conf.import_group('fetcher_keystone',
                            'cloudkitty.fetcher.keystone')
Ejemplo n.º 3
0
    def setUp(self):
        """Set up common parts of all test-cases here."""
        super(BaseAuditMiddlewareTest, self).setUp()

        global user_counter

        self.audit_map_file_fixture = self.useFixture(
            createfile.CreateFileWithContent('audit',
                                             audit_map_content_nova,
                                             ext=".yaml"))

        self.cfg = self.useFixture(cfg_fixture.Config())
        self.msg = self.useFixture(msg_fixture.ConfFixture(self.cfg.conf))

        self.cfg.conf([])

        # service_name needs to be redefined by subclass
        self.service_name = None
        self.service_type = None
        self.project_id = str(uuid.uuid4().hex)
        self.user_id = str(uuid.uuid4().hex)
        self.username = "******" + str(user_counter)
        user_counter += 1

        patcher = mock.patch('datadog.dogstatsd.DogStatsd._report')
        self.statsd_report_mock = patcher.start()
        self.addCleanup(patcher.stop)
Ejemplo n.º 4
0
 def start_fixture(self):
     self.conf = None
     conf = conf_fixture.Config().conf
     policy_opts.set_defaults(conf)
     msg_conf = conffixture.ConfFixture(conf)
     msg_conf.transport_driver = 'fake'
     conf.import_group('api', 'cloudkitty.api.app')
     conf.set_override('auth_strategy', 'noauth', enforce_type=True)
     conf.set_override('connection', 'sqlite:///', 'database',
                       enforce_type=True)
     conf.set_override('policy_file',
                       os.path.abspath('etc/cloudkitty/policy.json'),
                       group='oslo_policy',
                       enforce_type=True)
     conf.set_override('api_paste_config',
                       os.path.abspath(
                           'cloudkitty/tests/gabbi/gabbi_paste.ini')
                       )
     conf.import_group('storage', 'cloudkitty.storage')
     conf.set_override('backend', 'sqlalchemy', 'storage',
                       enforce_type=True)
     self.conf = conf
     self.conn = ck_db_api.get_instance()
     migration = self.conn.get_migration()
     migration.upgrade('head')
Ejemplo n.º 5
0
    def setUp(self):
        super(TestCase, self).setUp()

        self.CONF = self.useFixture(cfg_fixture.Config(cfg.CONF)).conf

        self.messaging_conf = messaging_fixture.ConfFixture(cfg.CONF)
        self.messaging_conf.transport_driver = 'fake'
        self.messaging_conf.response_timeout = 5
        self.useFixture(self.messaging_conf)

        self.config(notification_driver='test')

        self.useFixture(fixtures.RPCFixture(cfg.CONF))

        self.config(storage_driver='sqlalchemy', group='service:central')

        self.config(emitter_type="noop", group="heartbeat_emitter")

        self.config(auth_strategy='noauth', group='service:api')

        # The database fixture needs to be set up here (as opposed to isolated
        # in a storage test case) because many tests end up using storage.
        REPOSITORY = os.path.abspath(
            os.path.join(os.path.dirname(__file__), '..', 'storage',
                         'impl_sqlalchemy', 'migrate_repo'))
        self.db_fixture = self.useFixture(
            fixtures.DatabaseFixture.get_fixture(REPOSITORY,
                                                 manage_database.INIT_VERSION))

        if os.getenv('DESIGNATE_SQL_DEBUG', "False").lower() in _TRUE_VALUES:
            connection_debug = 50
        else:
            connection_debug = 0

        self.config(connection=self.db_fixture.url,
                    connection_debug=connection_debug,
                    group='storage:sqlalchemy')

        self._setup_pool_manager_cache()

        self.config(network_api='fake')

        self.config(scheduler_filters=['pool_id_attribute', 'random'],
                    group='service:central')

        # "Read" Configuration
        self.CONF([], project='designate')
        utils.register_plugin_opts()

        self.useFixture(fixtures.PolicyFixture())
        self.network_api = fixtures.NetworkAPIFixture()
        self.useFixture(self.network_api)
        self.central_service = self.start_service('central')

        self.admin_context = self.get_admin_context()
        storage_driver = cfg.CONF['service:central'].storage_driver
        self.storage = storage.get_storage(storage_driver)

        # Setup the Default Pool with some useful settings
        self._setup_default_pool()
Ejemplo n.º 6
0
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

        rpc.add_extra_exmods("karbor.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)
        self.useFixture(_DB_CACHE)
 def setUp(self):
     super(RPCFixture, self).setUp()
     self.addCleanup(rpc.cleanup)
     rpc.add_extra_exmods(*self.exmods)
     self.addCleanup(rpc.clear_extra_exmods)
     self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
     self.messaging_conf.transport_driver = 'fake'
     self.useFixture(self.messaging_conf)
     rpc.init(CONF)
Ejemplo n.º 8
0
    def setUp(self, conf=cfg.CONF):
        super(BaseTestCase, self).setUp()

        from oslo_messaging import conffixture
        self.messaging_conf = self.useFixture(conffixture.ConfFixture(conf))
        self.messaging_conf.transport_url = 'fake:/'
        self.conf = self.messaging_conf.conf

        self.conf.project = 'project'
        self.conf.prog = 'prog'
Ejemplo n.º 9
0
    def setUp(self):
        super(BaseAuditMiddlewareTest, self).setUp()

        self.audit_map_file_fixture = self.useFixture(
            createfile.CreateFileWithContent('audit', audit_map_content))

        self.cfg = self.useFixture(cfg_fixture.Config())
        self.msg = self.useFixture(msg_fixture.ConfFixture(self.cfg.conf))

        self.cfg.conf([], project=self.PROJECT_NAME)
Ejemplo n.º 10
0
 def setUp(self):
     super(OrchestratorTest, self).setUp()
     messaging_conf = self.useFixture(conffixture.ConfFixture(self.conf))
     messaging_conf.transport_driver = 'fake'
     self.conf.set_override('backend',
                            'keystone',
                            'tenant_fetcher',
                            enforce_type=True)
     self.conf.import_group('keystone_fetcher',
                            'cloudkitty.tenant_fetcher.keystone')
Ejemplo n.º 11
0
    def setUp(self):
        super(TestDseNode, self).setUp()

        if USE_RABBIT:
            self.messaging_config = cfg.CONF
        else:
            mc_fixture = conffixture.ConfFixture(cfg.CONF)
            mc_fixture.conf.transport_url = 'kombu+memory://'
            self.messaging_config = mc_fixture.conf
        self.messaging_config.rpc_response_timeout = 1
Ejemplo n.º 12
0
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

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

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

        self.injected = []
        self._services = []
        self.flags(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')
        self.fixture.config(disable_process_locking=True,
                            group='oslo_concurrency')

        rpc.add_extra_exmods('manila.tests')
        self.addCleanup(rpc.clear_extra_exmods)
        self.addCleanup(rpc.cleanup)

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_url = 'fake:/'
        self.messaging_conf.response_timeout = 15
        self.useFixture(self.messaging_conf)

        oslo_messaging.get_notification_transport(CONF)
        self.override_config('driver', ['test'],
                             group='oslo_messaging_notifications')

        rpc.init(CONF)

        mock.patch('keystoneauth1.loading.load_auth_from_conf_options').start()

        fake_notifier.stub_notifier(self)

        self._disable_osprofiler()

        # Locks must be cleaned up after tests
        CONF.set_override('backend_url',
                          'file://' + lock_path,
                          group='coordination')
        coordination.LOCK_COORDINATOR.start()
        self.addCleanup(coordination.LOCK_COORDINATOR.stop)
Ejemplo n.º 13
0
    def setUp(self, conf=cfg.CONF):
        super(BaseTestCase, self).setUp()

        from oslo_messaging import conffixture
        self.messaging_conf = self.useFixture(conffixture.ConfFixture(conf))
        self.messaging_conf.transport_driver = 'fake'
        self.conf = self.messaging_conf.conf

        moxfixture = self.useFixture(moxstubout.MoxStubout())
        self.mox = moxfixture.mox
        self.stubs = moxfixture.stubs
Ejemplo n.º 14
0
 def setUp(self):
     super(TestRpc, self).setUp()
     self.addCleanup(rpc.cleanup)
     self.messaging_conf = messaging_conffixture.ConfFixture(cfg.CONF)
     self.messaging_conf.transport_url = 'fake:/'
     self.useFixture(self.messaging_conf)
     self.useFixture(fixtures.MonkeyPatch(
         'octavia.common.rpc.create_transport',
         self._fake_create_transport))
     with mock.patch('octavia.common.rpc.get_transport_url') as mock_gtu:
         mock_gtu.return_value = None
         rpc.init()
Ejemplo n.º 15
0
 def test_fixture_setup_teardown_decorator(self):
     conf = cfg.ConfigOpts()
     self.assertFalse(hasattr(conf.set_override, 'wrapped'))
     self.assertFalse(hasattr(conf.clear_override, 'wrapped'))
     fixture = conffixture.ConfFixture(conf)
     self.assertFalse(hasattr(conf.set_override, 'wrapped'))
     self.assertFalse(hasattr(conf.clear_override, 'wrapped'))
     self.useFixture(fixture)
     self.assertTrue(hasattr(conf.set_override, 'wrapped'))
     self.assertTrue(hasattr(conf.clear_override, 'wrapped'))
     fixture._teardown_decorator()
     self.assertFalse(hasattr(conf.set_override, 'wrapped'))
     self.assertFalse(hasattr(conf.clear_override, 'wrapped'))
Ejemplo n.º 16
0
    def setUp(self):
        super(CastExceptionTestCase, self).setUp()

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_url = 'fake://'
        self.messaging_conf.response_timeout = 0
        self.useFixture(self.messaging_conf)

        self.addCleanup(rpc.cleanup)
        rpc.init(CONF)
        rpc.TRANSPORT = mock.MagicMock()
        rpc.TRANSPORT._send.side_effect = Exception
        target = messaging.Target(version='1.0', topic='testing')
        self.client = rpc.get_client(target)
        self.cast_context = mock.Mock()
Ejemplo n.º 17
0
    def _setUp(self):
        # don't actually start RPC listeners when testing
        mock.patch.object(rpc.Connection, 'consume_in_threads',
                          return_value=[]).start()
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_messaging.Notifier', fake_notifier.FakeNotifier))

        self.messaging_conf = conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_driver = 'fake'
        # NOTE(russellb) We want all calls to return immediately.
        self.messaging_conf.response_timeout = 0
        self.useFixture(self.messaging_conf)

        self.addCleanup(rpc.cleanup)
        rpc.init(CONF)
Ejemplo n.º 18
0
    def setUp(self):
        super(ServiceTestCase, self).setUp()
        self.host = 'foo'
        self.topic = 'neutron-agent'

        self.target_mock = mock.patch('oslo_messaging.Target')
        self.target_mock.start()

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

        self.addCleanup(rpc.cleanup)
        rpc.init(CONF)
Ejemplo n.º 19
0
    def setup_rpc_mocks(self):
        # don't actually start RPC listeners when testing
        mock.patch('neutron_lib.rpc.Connection.consume_in_threads',
                   return_value=[]).start()

        self.useFixture(
            fixtures.MonkeyPatch('oslo_messaging.Notifier',
                                 fake_notifier.FakeNotifier))

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_url = 'fake:/'
        # NOTE(russellb) We want all calls to return immediately.
        self.messaging_conf.response_timeout = 0
        self.useFixture(self.messaging_conf)

        n_rpc.init(CONF)
Ejemplo n.º 20
0
 def setUp(self):
     super(RPCFixture, self).setUp()
     self.addCleanup(rpc.cleanup)
     rpc.add_extra_exmods(*self.exmods)
     self.addCleanup(rpc.clear_extra_exmods)
     self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
     self.messaging_conf.transport_driver = 'fake'
     self.useFixture(self.messaging_conf)
     self.useFixture(fixtures.MonkeyPatch(
         'nova.rpc.create_transport', self._fake_create_transport))
     # NOTE(danms): Execute the init with get_transport_url() as None,
     # instead of the parsed TransportURL(None) so that we can cache
     # it as it will be called later if the default is requested by
     # one of our mq-switching methods.
     with mock.patch('nova.rpc.get_transport_url') as mock_gtu:
         mock_gtu.return_value = None
         rpc.init(CONF)
Ejemplo n.º 21
0
    def setUp(self):
        super(TimeoutTestCase, self).setUp()

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

        self.addCleanup(rpc.cleanup)
        rpc.init(CONF)
        rpc.TRANSPORT = mock.MagicMock()
        rpc.TRANSPORT._send.side_effect = messaging.MessagingTimeout
        target = messaging.Target(version='1.0', topic='testing')
        self.client = rpc.get_client(target)
        self.call_context = mock.Mock()
        self.sleep = mock.patch('time.sleep').start()
        rpc.TRANSPORT.conf.rpc_response_timeout = 10
Ejemplo n.º 22
0
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

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

        global _DB_CACHE
        if not _DB_CACHE:
            _DB_CACHE = Database(db_api,
                                 sql_connection=CONF.database.connection)
        self.useFixture(_DB_CACHE)

        self.injected = []
        self._services = []
        # 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')
        self.fixture.config(disable_process_locking=True,
                            group='oslo_concurrency')

        rpc.add_extra_exmods('delfin.tests')
        self.addCleanup(rpc.clear_extra_exmods)
        self.addCleanup(rpc.cleanup)

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_url = 'fake:/'
        self.messaging_conf.response_timeout = 15
        self.useFixture(self.messaging_conf)

        oslo_messaging.get_notification_transport(CONF)
        self.override_config('driver', ['test'],
                             group='oslo_messaging_notifications')

        rpc.init(CONF)

        fake_notifier.stub_notifier(self)

        # Locks must be cleaned up after tests
        CONF.set_override('backend_type', 'file', group='coordination')
        CONF.set_override('backend_server', lock_path, group='coordination')
        coordination.LOCK_COORDINATOR.start()
        self.addCleanup(coordination.LOCK_COORDINATOR.stop)
Ejemplo n.º 23
0
    def setUp(self):
        """Run before each test method to initialize test environment."""
        super(TestCase, self).setUp()

        oslo_i18n.enable_lazy(enable=False)
        conf_fixture.set_defaults(CONF)
        CONF([], default_config_files=[])

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

        self.injected = []
        self._services = []
        self.flags(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')
        self.fixture.config(disable_process_locking=True,
                            group='oslo_concurrency')

        rpc.add_extra_exmods('meteos.tests')
        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)

        mock.patch('keystoneauth1.loading.load_auth_from_conf_options').start()

        fake_notifier.stub_notifier(self)
Ejemplo n.º 24
0
    def setup_rpc_mocks(self):
        # don't actually start RPC listeners when testing
        self.useFixture(fixtures.MonkeyPatch(
            'neutron.common.rpc.Connection.consume_in_threads',
            fake_consume_in_threads))

        self.useFixture(fixtures.MonkeyPatch(
            'oslo_messaging.Notifier', fake_notifier.FakeNotifier))

        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_driver = 'fake'
        # NOTE(russellb) We want all calls to return immediately.
        self.messaging_conf.response_timeout = 0
        self.useFixture(self.messaging_conf)

        self.addCleanup(n_rpc.clear_extra_exmods)
        n_rpc.add_extra_exmods('neutron.test')

        self.addCleanup(n_rpc.cleanup)
        n_rpc.init(CONF)
Ejemplo n.º 25
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
        self.patch('cinder.rpc.get_notifier',
                   side_effect=self._get_joined_notifier)

        if self.MOCK_WORKER:
            # Mock worker creation for all tests that don't care about it
            clean_path = 'cinder.objects.cleanable.CinderCleanableObject.%s'
            for method in ('create_worker', 'set_worker', 'unset_worker'):
                self.patch(clean_path % method, return_value=None)

        # 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))

        self.useFixture(log_fixture.get_logging_handle_error_fixture())
        self.useFixture(cinder_fixtures.StandardLogging())

        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)

        # Load oslo_messaging_notifications config group so we can set an
        # override to prevent notifications from being ignored due to the
        # short-circuit mechanism.
        oslo_messaging.get_notification_transport(CONF)
        #  We need to use a valid driver for the notifications, so we use test.
        self.override_config('driver', ['test'],
                             group='oslo_messaging_notifications')
        rpc.init(CONF)

        # NOTE(geguileo): This is required because _determine_obj_version_cap
        # and _determine_rpc_version_cap functions in cinder.rpc.RPCAPI cache
        # versions in LAST_RPC_VERSIONS and LAST_OBJ_VERSIONS so we may have
        # weird interactions between tests if we don't clear them before each
        # test.
        rpc.LAST_OBJ_VERSIONS = {}
        rpc.LAST_RPC_VERSIONS = {}

        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)
        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.mock_notifier(self)

        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__),
                                         '..',
                                     )), self.POLICY_PATH),
                             group='oslo_policy')

        self._disable_osprofiler()
        self._disallow_invalid_uuids()

        # 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 = {}

        self.override_config('backend_url',
                             'file://' + lock_path,
                             group='coordination')
        coordination.COORDINATOR.start()
        self.addCleanup(coordination.COORDINATOR.stop)
Ejemplo n.º 26
0
    def test_event_list_deleted_resource(self, mock_delete):
        self.useFixture(conffixture.ConfFixture(cfg.CONF))
        mock_delete.return_value = None

        res._register_class('GenericResourceType',
                            generic_rsrc.GenericResource)

        thread = mock.Mock()
        thread.link = mock.Mock(return_value=None)

        def run(stack_id, func, *args, **kwargs):
            func(*args, **kwargs)
            return thread

        self.eng.thread_group_mgr.start = run

        new_tmpl = {
            'HeatTemplateFormatVersion': '2012-12-12',
            'Resources': {
                'AResource': {
                    'Type': 'GenericResourceType'
                }
            }
        }

        result = self.eng.update_stack(self.ctx, self.stack.identifier(),
                                       new_tmpl, None, None, {})

        # The self.stack reference needs to be updated. Since the underlying
        # stack is updated in update_stack, the original reference is now
        # pointing to an orphaned stack object.
        self.stack = parser.Stack.load(self.ctx, stack_id=result['stack_id'])

        self.assertEqual(result, self.stack.identifier())
        self.assertIsInstance(result, dict)
        self.assertTrue(result['stack_id'])
        events = self.eng.list_events(self.ctx, self.stack.identifier())

        self.assertEqual(10, len(events))

        for ev in events:
            self.assertIn('event_identity', ev)
            self.assertIsInstance(ev['event_identity'], dict)
            self.assertTrue(ev['event_identity']['path'].rsplit('/', 1)[1])

            self.assertIn('resource_name', ev)
            self.assertIn('physical_resource_id', ev)
            self.assertIn('resource_status_reason', ev)

            self.assertIn(ev['resource_action'],
                          ('CREATE', 'UPDATE', 'DELETE'))
            self.assertIn(ev['resource_status'], ('IN_PROGRESS', 'COMPLETE'))

            self.assertIn('resource_type', ev)
            self.assertIn(ev['resource_type'],
                          ('AWS::EC2::Instance', 'GenericResourceType',
                           'OS::Heat::Stack'))

            self.assertIn('stack_identity', ev)

            self.assertIn('stack_name', ev)
            self.assertEqual(self.stack.name, ev['stack_name'])

            self.assertIn('event_time', ev)

        mock_delete.assert_called_once_with()
        expected = [
            mock.call(mock.ANY),
            mock.call(mock.ANY, self.stack.id, mock.ANY)
        ]
        self.assertEqual(expected, thread.link.call_args_list)
Ejemplo n.º 27
0
Archivo: test.py Proyecto: joshw/cinder
    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
        self.patch('cinder.rpc.get_notifier',
                   side_effect=self._get_joined_notifier)

        if self.MOCK_WORKER:
            # Mock worker creation for all tests that don't care about it
            clean_path = 'cinder.objects.cleanable.CinderCleanableObject.%s'
            for method in ('create_worker', 'set_worker', 'unset_worker'):
                self.patch(clean_path % method, return_value=None)

        if self.MOCK_TOOZ:
            self.patch('cinder.coordination.Coordinator.start')
            self.patch('cinder.coordination.Coordinator.stop')
            self.patch('cinder.coordination.Coordinator.get_lock')

        # 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))

        self.useFixture(log_fixture.get_logging_handle_error_fixture())
        self.useFixture(cinder_fixtures.StandardLogging())

        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_url = 'fake:/'
        self.messaging_conf.response_timeout = 15
        self.useFixture(self.messaging_conf)

        # Load oslo_messaging_notifications config group so we can set an
        # override to prevent notifications from being ignored due to the
        # short-circuit mechanism.
        oslo_messaging.get_notification_transport(CONF)
        #  We need to use a valid driver for the notifications, so we use test.
        self.override_config('driver', ['test'],
                             group='oslo_messaging_notifications')
        rpc.init(CONF)

        # NOTE(geguileo): This is required because _determine_obj_version_cap
        # and _determine_rpc_version_cap functions in cinder.rpc.RPCAPI cache
        # versions in LAST_RPC_VERSIONS and LAST_OBJ_VERSIONS so we may have
        # weird interactions between tests if we don't clear them before each
        # test.
        rpc.LAST_OBJ_VERSIONS = {}
        rpc.LAST_RPC_VERSIONS = {}

        # Init AuthProtocol to register some base options first, such as
        # auth_url.
        auth_token.AuthProtocol('fake_app', {
            'auth_type': 'password',
            'auth_url': 'fake_url'
        })

        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)
        self.useFixture(_DB_CACHE)

        # NOTE(blk-u): WarningsFixture must be after the Database fixture
        # because sqlalchemy-migrate messes with the warnings filters.
        self.useFixture(cinder_fixtures.WarningsFixture())

        # 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)

        self.addCleanup(CONF.reset)
        self.addCleanup(self._common_cleanup)
        self.injected = []
        self._services = []

        fake_notifier.mock_notifier(self)

        # 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__),
                                         '..',
                                     )), self.POLICY_PATH),
                             group='oslo_policy')
        self.override_config(
            'resource_query_filters_file',
            os.path.join(
                os.path.abspath(os.path.join(
                    os.path.dirname(__file__),
                    '..',
                )), self.RESOURCE_FILTER_PATH))
        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 = {}

        self.override_config('backend_url',
                             'file://' + lock_path,
                             group='coordination')
        coordination.COORDINATOR.start()
        self.addCleanup(coordination.COORDINATOR.stop)

        if six.PY3:
            # TODO(smcginnis) Python 3 deprecates assertRaisesRegexp to
            # assertRaisesRegex, but Python 2 does not have the new name. This
            # can be removed once we stop supporting py2 or the new name is
            # added.
            self.assertRaisesRegexp = self.assertRaisesRegex

        # Ensure we have the default tpool size value and we don't carry
        # threads from other test runs.
        tpool.killall()
        tpool._nthreads = 20

        # NOTE(mikal): make sure we don't load a privsep helper accidentally
        self.useFixture(cinder_fixtures.PrivsepNoHelperFixture())
Ejemplo n.º 28
0
 def setUp(self):
     super(TestDSE, self).setUp()
     mc_fixture = conffixture.ConfFixture(cfg.CONF)
     mc_fixture.conf.transport_url = 'kombu+memory://'
     self.messaging_config = mc_fixture.conf
     self.messaging_config.rpc_response_timeout = 1
Ejemplo n.º 29
0
def generate_messaging_config():
    mc_fixture = conffixture.ConfFixture(cfg.CONF)
    mc_fixture.conf.transport_url = 'kombu+memory://'
    messaging_config = mc_fixture.conf
    messaging_config.rpc_response_timeout = 10
    return messaging_config
Ejemplo n.º 30
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'))