def test__get_creds_by_roles_list_role(self):
     self.useFixture(
         mockpatch.Patch('tempest.common.preprov_creds.read_accounts_yaml',
                         return_value=self.test_accounts))
     test_accounts_class = preprov_creds.PreProvisionedCredentialProvider(
         **self.fixed_params)
     hashes = test_accounts_class.hash_dict['roles']['role4']
     hashes2 = test_accounts_class.hash_dict['roles']['role2']
     hashes = list(set(hashes) & set(hashes2))
     temp_hash = hashes[0]
     get_free_hash_mock = self.useFixture(
         mockpatch.PatchObject(test_accounts_class,
                               '_get_free_hash',
                               return_value=temp_hash))
     # Test an intersection of multiple roles
     test_accounts_class._get_creds(roles=['role2', 'role4'])
     calls = get_free_hash_mock.mock.mock_calls
     self.assertEqual(len(calls), 1)
     args = calls[0][1][0]
     for i in hashes:
         self.assertIn(i, args)
    def setUp(self):
        super(TestCollector, self).setUp()
        self.CONF = self.useFixture(fixture_config.Config()).conf
        self.CONF.import_opt("connection", "oslo_db.options", group="database")
        self.CONF.set_override("connection", "log://", group='database')
        self.CONF.set_override('telemetry_secret',
                               'not-so-secret',
                               group='publisher')
        self._setup_messaging()

        self.counter = sample.Sample(
            name='foobar',
            type='bad',
            unit='F',
            volume=1,
            user_id='jd',
            project_id='ceilometer',
            resource_id='cat',
            timestamp=timeutils.utcnow().isoformat(),
            resource_metadata={},
        ).as_dict()

        self.utf8_msg = utils.meter_message_from_counter(
            sample.Sample(
                name=u'test',
                type=sample.TYPE_CUMULATIVE,
                unit=u'',
                volume=1,
                user_id=u'test',
                project_id=u'test',
                resource_id=u'test_run_tasks',
                timestamp=timeutils.utcnow().isoformat(),
                resource_metadata={u'name': [([u'TestPublish'])]},
                source=u'testsource',
            ), 'not-so-secret')

        self.srv = collector.CollectorService()

        self.useFixture(
            mockpatch.Patch("threading.Thread", side_effect=FakeThread))
Example #3
0
    def setUp(self):
        super(TestBase, self).setUp()
        db_url = os.environ.get('PIFPAF_URL',
                                "sqlite://").replace("mysql://",
                                                     "mysql+pymysql://")

        engine = urlparse.urlparse(db_url).scheme
        # in case some drivers have additional specification, for example:
        # PyMySQL will have scheme mysql+pymysql
        engine = engine.split('+')[0]

        # NOTE(Alexei_987) Shortcut to skip expensive db setUp
        test_method = self._get_test_method()
        if (hasattr(test_method, '_run_with')
                and engine not in test_method._run_with):
            raise testcase.TestSkipped('Test is not applicable for %s' %
                                       engine)

        conf = service.prepare_service([], [])
        self.CONF = self.useFixture(fixture_config.Config(conf)).conf

        manager = self.DRIVER_MANAGERS.get(engine)
        if not manager:
            self.skipTest("missing driver manager: %s" % engine)

        self.db_manager = manager(self.CONF, db_url)

        self.useFixture(self.db_manager)

        self.conn = self.db_manager.connection
        self.conn.upgrade()

        self.useFixture(
            mockpatch.Patch('ceilometer.storage.get_connection',
                            side_effect=self._get_connection))

        # Set a default location for the pipeline config file so the
        # tests work even if ceilometer is not installed globally on
        # the system.
        self.CONF.import_opt('pipeline_cfg_file', 'ceilometer.pipeline')
    def setUp(self):
        super(EventPipelineTestCase, self).setUp()
        self.p_type = pipeline.EVENT_TYPE
        self.transformer_manager = None

        self.test_event = models.Event(
            message_id=uuid.uuid4(),
            event_type='a',
            generated=datetime.datetime.utcnow(),
            traits=[
                models.Trait('t_text', 1, 'text_trait'),
                models.Trait('t_int', 2, 'int_trait'),
                models.Trait('t_float', 3, 'float_trait'),
                models.Trait('t_datetime', 4, 'datetime_trait')
            ],
            raw={'status': 'started'})

        self.test_event2 = models.Event(
            message_id=uuid.uuid4(),
            event_type='b',
            generated=datetime.datetime.utcnow(),
            traits=[
                models.Trait('t_text', 1, 'text_trait'),
                models.Trait('t_int', 2, 'int_trait'),
                models.Trait('t_float', 3, 'float_trait'),
                models.Trait('t_datetime', 4, 'datetime_trait')
            ],
            raw={'status': 'stopped'})

        self.useFixture(
            mockpatch.PatchObject(publisher,
                                  'get_publisher',
                                  side_effect=self.get_publisher))

        self._setup_pipeline_cfg()

        self._reraise_exception = True
        self.useFixture(
            mockpatch.Patch('ceilometer.pipeline.LOG.exception',
                            side_effect=self._handle_reraise_exception))
Example #5
0
 def test_networks_returned_with_creds(self):
     test_accounts = [{
         'username': '******',
         'tenant_name': 'test_tenant13',
         'password': '******',
         'resources': {
             'network': 'network-1'
         }
     }, {
         'username': '******',
         'tenant_name': 'test_tenant14',
         'password': '******',
         'roles': ['role-7', 'role-11'],
         'resources': {
             'network': 'network-2'
         }
     }]
     self.useFixture(
         mockpatch.Patch('tempest.common.preprov_creds.read_accounts_yaml',
                         return_value=test_accounts))
     test_accounts_class = preprov_creds.PreProvisionedCredentialProvider(
         **self.fixed_params)
     with mock.patch(
             'tempest.lib.services.compute.networks_client.'
             'NetworksClient.list_networks',
             return_value={
                 'networks': [{
                     'name': 'network-2',
                     'id': 'fake-id',
                     'label': 'network-2'
                 }]
             }):
         creds = test_accounts_class.get_creds_by_roles(['role-7'])
     self.assertIsInstance(creds, cred_provider.TestResources)
     network = creds.network
     self.assertIsNotNone(network)
     self.assertIn('name', network)
     self.assertIn('id', network)
     self.assertEqual('fake-id', network['id'])
     self.assertEqual('network-2', network['name'])
Example #6
0
    def test_destroy_users(self):

        fake_user = self.fake_object['user']
        fake_tenant = self.fake_object['tenant']

        fake_auth = self.fake_client
        fake_auth.tenants.list_tenants.return_value = \
            {'tenants': [fake_tenant]}
        fake_auth.users.list_users.return_value = {'users': [fake_user]}

        self.useFixture(
            mockpatch.Patch('tempest.common.identity.get_user_by_username',
                            return_value=fake_user))
        self.useFixture(
            mockpatch.PatchObject(javelin,
                                  "keystone_admin",
                                  return_value=fake_auth))

        javelin.destroy_users([fake_user])

        mocked_function = fake_auth.users.delete_user
        mocked_function.assert_called_once_with(fake_user['id'])
    def test_event_pipeline_endpoint_requeue_on_failure(self):
        self.CONF = self.useFixture(fixture_config.Config()).conf
        self.CONF([])

        self.CONF.set_override("ack_on_event_error", False,
                               group="notification")
        self.CONF.set_override("telemetry_secret", "not-so-secret",
                               group="publisher")
        test_data = {
            'message_id': uuid.uuid4(),
            'event_type': 'a',
            'generated': '2013-08-08 21:06:37.803826',
            'traits': [
                {'name': 't_text',
                 'value': 1,
                 'dtype': 'text_trait'
                 }
            ],
            'raw': {'status': 'started'}
        }
        message_sign = utils.compute_signature(test_data, 'not-so-secret')
        test_data['message_signature'] = message_sign

        fake_publisher = mock.Mock()
        self.useFixture(mockpatch.Patch(
            'ceilometer.publisher.test.TestPublisher',
            return_value=fake_publisher))

        pipeline_manager = pipeline.PipelineManager(self.pipeline_cfg,
                                                    self.transformer_manager,
                                                    self.p_type)
        event_pipeline_endpoint = pipeline.EventPipelineEndpoint(
            pipeline_manager.pipelines[0])

        fake_publisher.publish_events.side_effect = Exception
        ret = event_pipeline_endpoint.sample([
            {'ctxt': {}, 'publisher_id': 'compute.vagrant-precise',
             'event_type': 'a', 'payload': [test_data], 'metadata': {}}])
        self.assertEqual(oslo_messaging.NotificationResult.REQUEUE, ret)
    def test_notify_alarm_trust_action(self):
        action = 'trust+http://trust-1234@host/action'
        url = 'http://host/action'

        client = mock.MagicMock()
        client.session.auth.get_access.return_value.auth_token = 'token_1234'
        headers = {'X-Auth-Token': 'token_1234'}
        headers.update(self.HTTP_HEADERS)

        self.useFixture(mockpatch.Patch('keystoneclient.v3.client.Client',
                                        lambda **kwargs: client))

        with mock.patch.object(requests.Session, 'post') as poster:
            self.service.notify_alarm({},
                                      self._notification(action))
            headers = {'X-Auth-Token': 'token_1234'}
            headers.update(self.HTTP_HEADERS)
            poster.assert_called_with(
                url, data=mock.ANY, headers=mock.ANY)
            args, kwargs = poster.call_args
            self.assertEqual(headers, kwargs['headers'])
            self.assertEqual(DATA_JSON, jsonutils.loads(kwargs['data']))
Example #9
0
    def setUp(self):
        super(TestBase, self).setUp()
        engine = urlparse.urlparse(self.db_url).scheme

        # NOTE(Alexei_987) Shortcut to skip expensive db setUp
        test_method = self._get_test_method()
        if (hasattr(test_method, '_run_with')
                and engine not in test_method._run_with):
            raise testcase.TestSkipped('Test is not applicable for %s' %
                                       engine)

        self.CONF = self.useFixture(fixture_config.Config()).conf
        self.CONF([], project='ceilometer', validate_default_values=True)

        try:
            self.db_manager = self._get_driver_manager(engine)(self.db_url)
        except ValueError as exc:
            self.skipTest("missing driver manager: %s" % exc)
        self.useFixture(self.db_manager)

        self.conn = self.db_manager.connection
        self.conn.upgrade()

        self.alarm_conn = self.db_manager.alarm_connection
        self.alarm_conn.upgrade()

        self.event_conn = self.db_manager.event_connection
        self.event_conn.upgrade()

        self.useFixture(
            mockpatch.Patch('ceilometer.storage.get_connection',
                            side_effect=self._get_connection))

        # Set a default location for the pipeline config file so the
        # tests work even if ceilometer is not installed globally on
        # the system.
        self.CONF.import_opt('pipeline_cfg_file', 'ceilometer.pipeline')
        self.CONF.set_override('pipeline_cfg_file',
                               self.path_get('etc/ceilometer/pipeline.yaml'))
    def _test_show_aggregate(self, bytes_body=False):
        expected = {
            "name": "hoge",
            "availability_zone": None,
            "deleted": False,
            "created_at": "2015-07-16T03:07:32.000000",
            "updated_at": None,
            "hosts": [],
            "deleted_at": None,
            "id": 1,
            "metadata": {}
        }
        serialized_body = json.dumps({"aggregate": expected})
        if bytes_body:
            serialized_body = serialized_body.encode('utf-8')

        mocked_resp = (httplib2.Response({'status': 200}), serialized_body)
        self.useFixture(
            mockpatch.Patch('tempest.common.service_client.ServiceClient.get',
                            return_value=mocked_resp))
        resp = self.client.show_aggregate(1)
        self.assertEqual(expected, resp)
Example #11
0
    def _test_show_extension(self, bytes_body=False):
        expected = {
            "extension": {
                "updated": "2011-06-09T00:00:00Z",
                "name": "Multinic",
                "links": [],
                "namespace":
                "http://docs.openstack.org/compute/ext/multinic/api/v1.1",
                "alias": "NMN",
                "description": u'\u2740(*\xb4\u25e1`*)\u2740'
            }
        }
        serialized_body = json.dumps(expected)
        if bytes_body:
            serialized_body = serialized_body.encode('utf-8')

        mocked_resp = (httplib2.Response({'status': 200}), serialized_body)
        self.useFixture(
            mockpatch.Patch('tempest.common.service_client.ServiceClient.get',
                            return_value=mocked_resp))
        resp = self.client.show_extension("NMN")
        self.assertEqual(expected, resp)
Example #12
0
    def test_get_versions_invalid_response(self):
        # When the response doesn't contain a JSON response, an error is
        # logged.
        mock_log_error = self.useFixture(mockpatch.PatchObject(
            verify_tempest_config.LOG, 'error')).mock

        self.useFixture(mockpatch.PatchObject(
            verify_tempest_config, '_get_unversioned_endpoint'))

        # Simulated response is not JSON.
        sample_body = (
            '<html><head>Sample Response</head><body>This is the sample page '
            'for the web server. Why are you requesting it?</body></html>')
        self.useFixture(mockpatch.Patch(
            'tempest.lib.common.http.ClosingHttp.request',
            return_value=(None, sample_body)))

        # service value doesn't matter, just needs to match what
        # _get_api_versions puts in its client_dict.
        self.assertRaises(ValueError, verify_tempest_config._get_api_versions,
                          os=mock.MagicMock(), service='keystone')
        self.assertTrue(mock_log_error.called)
    def _test_create_aggregate(self, bytes_body=False):
        expected = {
            "aggregate": {
                "name": u'\xf4',
                "availability_zone": None,
                "deleted": False,
                "created_at": "2015-07-21T04:11:18.000000",
                "updated_at": None,
                "deleted_at": None,
                "id": 1
            }
        }
        serialized_body = json.dumps(expected)
        if bytes_body:
            serialized_body = serialized_body.encode('utf-8')

        mocked_resp = (httplib2.Response({'status': 200}), serialized_body)
        self.useFixture(
            mockpatch.Patch('tempest.common.service_client.ServiceClient.post',
                            return_value=mocked_resp))
        resp = self.client.create_aggregate(name='hoge')
        self.assertEqual(expected, resp)
 def test_when_keystone_fail(self):
     """Test for bug 1316532."""
     self.useFixture(mockpatch.Patch(
         'keystoneclient.v2_0.client.Client',
         side_effect=ks_exceptions.ClientException))
     self.pipeline_cfg = {
         'sources': [{
             'name': "test_keystone",
             'interval': 10,
             'meters': ['testkeystone'],
             'resources': ['test://'] if self.source_resources else [],
             'sinks': ['test_sink']}],
         'sinks': [{
             'name': 'test_sink',
             'transformers': [],
             'publishers': ["test"]}]
     }
     self.mgr.polling_manager = pipeline.PollingManager(self.pipeline_cfg)
     polling_tasks = self.mgr.setup_polling_tasks()
     self.mgr.interval_task(list(polling_tasks.values())[0])
     self.assertFalse(self.PollsterKeystone.samples)
     self.assertFalse(self.notified_samples)
Example #15
0
 def test__get_creds_by_roles_no_admin(self):
     self.useFixture(
         mockpatch.Patch('tempest.common.preprov_creds.read_accounts_yaml',
                         return_value=self.test_accounts))
     test_accounts_class = preprov_creds.PreProvisionedCredentialProvider(
         **self.fixed_params)
     hashes = list(test_accounts_class.hash_dict['creds'].keys())
     admin_hashes = test_accounts_class.hash_dict['roles'][
         cfg.CONF.identity.admin_role]
     temp_hash = hashes[0]
     get_free_hash_mock = self.useFixture(
         mockpatch.PatchObject(test_accounts_class,
                               '_get_free_hash',
                               return_value=temp_hash))
     # Test an intersection of multiple roles
     test_accounts_class._get_creds()
     calls = get_free_hash_mock.mock.mock_calls
     self.assertEqual(len(calls), 1)
     args = calls[0][1][0]
     self.assertEqual(len(args), 10)
     for i in admin_hashes:
         self.assertNotIn(i, args)
Example #16
0
    def test_get_free_hash_some_in_use_accounts(self, lock_mock):
        # Emulate no pre-existing lock
        self.useFixture(mockpatch.Patch('os.path.isdir', return_value=True))
        hash_list = self._get_hash_list(self.test_accounts)
        test_account_class = preprov_creds.PreProvisionedCredentialProvider(
            **self.fixed_params)

        def _fake_is_file(path):
            # Fake isfile() to return that the path exists unless a specific
            # hash is in the path
            if hash_list[3] in path:
                return False
            return True

        self.patchobject(os.path, 'isfile', _fake_is_file)
        with mock.patch('six.moves.builtins.open',
                        mock.mock_open(),
                        create=True) as open_mock:
            test_account_class._get_free_hash(hash_list)
            lock_path = os.path.join(self.fixed_params['accounts_lock_dir'],
                                     hash_list[3])
            open_mock.assert_has_calls([mock.call(lock_path, 'w')])
Example #17
0
 def test_networks_returned_with_creds(self):
     test_accounts = [{
         'username': '******',
         'tenant_name': 'test_tenant13',
         'password': '******',
         'resources': {
             'network': 'network-1'
         }
     }, {
         'username': '******',
         'tenant_name': 'test_tenant14',
         'password': '******',
         'roles': ['role-7', 'role-11'],
         'resources': {
             'network': 'network-2'
         }
     }]
     # Clear previous mock using self.test_accounts
     self.accounts_mock.cleanUp()
     self.useFixture(
         mockpatch.Patch('tempest.common.accounts.read_accounts_yaml',
                         return_value=test_accounts))
     test_accounts_class = accounts.Accounts('v2', 'test_name')
     with mock.patch(
             'tempest.services.compute.json.networks_client.'
             'NetworksClientJSON.list_networks',
             return_value=[{
                 'name': 'network-2',
                 'id': 'fake-id'
             }]):
         creds = test_accounts_class.get_creds_by_roles(['role-7'])
     self.assertTrue(isinstance(creds, cred_provider.TestResources))
     network = creds.network
     self.assertIsNotNone(network)
     self.assertIn('name', network)
     self.assertIn('id', network)
     self.assertEqual('fake-id', network['id'])
     self.assertEqual('network-2', network['name'])
Example #18
0
    def setUp(self):
        super(DispatcherWorkflowTest, self).setUp()
        self.conf = self.useFixture(config_fixture.Config())
        # Set this explicitly to avoid conflicts with any existing
        # configuration.
        self.conf.config(url='http://localhost:8041',
                         group='dispatcher_gnocchi')
        ks_client = mock.Mock()
        ks_client.projects.find.return_value = mock.Mock(
            name='gnocchi', id='a2d42c23-d518-46b6-96ab-3fba2e146859')
        self.useFixture(
            mockpatch.Patch('ceilometer.keystone_client.get_client',
                            return_value=ks_client))
        self.ks_client = ks_client

        ceilometer_service.prepare_service(argv=[], config_files=[])
        self.conf.config(resources_definition_file=self.path_get(
            'etc/ceilometer/gnocchi_resources.yaml'),
                         group="dispatcher_gnocchi")

        self.sample['resource_id'] = str(uuid.uuid4()) + "/foobar"
        self.sample['message_signature'] = utils.compute_signature(
            self.sample, self.conf.conf.publisher.telemetry_secret)
Example #19
0
    def setUp(self):
        super(TestPollsterBase, self).setUp()

        self.inspector = mock.Mock()
        self.instance = mock.MagicMock()
        self.instance.name = 'instance-00000001'
        setattr(self.instance, 'OS-EXT-SRV-ATTR:instance_name',
                self.instance.name)
        self.instance.id = 1
        self.instance.flavor = {
            'name': 'm1.small',
            'id': 2,
            'vcpus': 1,
            'ram': 512,
            'disk': 20,
            'ephemeral': 0
        }
        self.instance.status = 'active'

        patch_virt = mockpatch.Patch(
            'ceilometer.compute.virt.inspector.get_hypervisor_inspector',
            new=mock.Mock(return_value=self.inspector))
        self.useFixture(patch_virt)
    def _test_and_check_logging_communicate_errors(self,
                                                   log_errors=None,
                                                   attempts=None):
        mock = self.useFixture(
            mockpatch.Patch('subprocess.Popen.communicate',
                            side_effect=OSError(errno.EAGAIN, 'fake-test')))

        fixture = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
        kwargs = {}

        if log_errors:
            kwargs.update({"log_errors": log_errors})

        if attempts:
            kwargs.update({"attempts": attempts})

        self.assertRaises(OSError, processutils.execute, '/usr/bin/env',
                          'false', **kwargs)

        self.assertEqual(attempts if attempts else 1, mock.mock.call_count)
        self.assertIn('Got an OSError', fixture.output)
        self.assertIn('errno: %d' % errno.EAGAIN, fixture.output)
        self.assertIn("'/usr/bin/env false'", fixture.output)
Example #21
0
    def setUp(self):
        super(TestBase, self).setUp()
        db_url = os.environ.get('AODH_TEST_STORAGE_URL',
                                'sqlite://').replace("mysql://",
                                                     "mysql+pymysql://")
        engine = urlparse.urlparse(db_url).scheme
        # In case some drivers have additional specification, for example:
        # PyMySQL will have scheme mysql+pymysql.
        self.engine = engine.split('+')[0]

        conf = service.prepare_service(argv=[], config_files=[])
        self.CONF = self.useFixture(fixture_config.Config(conf)).conf
        self.CONF.set_override('connection',
                               db_url,
                               group="database",
                               enforce_type=True)

        manager = self.DRIVER_MANAGERS.get(self.engine)
        if not manager:
            self.skipTest("missing driver manager: %s" % self.engine)

        self.db_manager = manager(self.CONF)

        self.useFixture(self.db_manager)

        self.CONF.set_override('connection',
                               self.db_manager.url,
                               group="database",
                               enforce_type=True)

        self.alarm_conn = storage.get_connection_from_config(self.CONF)
        self.alarm_conn.upgrade()

        self.useFixture(
            mockpatch.Patch('aodh.storage.get_connection_from_config',
                            side_effect=self._get_connection))
Example #22
0
    def setUp(self):
        super(ScenarioTestCase, self).setUp()
        if self.patch_benchmark_utils:
            self.mock_resource_is = mockpatch.Patch(
                self.benchmark_utils + ".resource_is")
            self.mock_get_from_manager = mockpatch.Patch(
                self.benchmark_utils + ".get_from_manager")
            self.mock_wait_for = mockpatch.Patch(
                self.benchmark_utils + ".wait_for")
            self.mock_wait_for_delete = mockpatch.Patch(
                self.benchmark_utils + ".wait_for_delete")
            self.mock_wait_for_status = mockpatch.Patch(
                self.benchmark_utils + ".wait_for_status")
            self.useFixture(self.mock_resource_is)
            self.useFixture(self.mock_get_from_manager)
            self.useFixture(self.mock_wait_for)
            self.useFixture(self.mock_wait_for_delete)
            self.useFixture(self.mock_wait_for_status)

        self.mock_sleep = mockpatch.Patch("time.sleep")
        self.useFixture(self.mock_sleep)

        self._clients = {}
        base_path = "rally.plugins.openstack"
        self._client_mocks = [
            mock.patch(
                "%s.scenario.OpenStackScenario.clients" % base_path,
                mock.Mock(side_effect=self.clients)),
            mock.patch(
                "%s.scenario.OpenStackScenario.admin_clients" % base_path,
                mock.Mock(side_effect=self.admin_clients))
        ]
        for patcher in self._client_mocks:
            patcher.start()

        self.context = get_test_context()
Example #23
0
 def patch(self, target, **kwargs):
     mockfixture = self.useFixture(mockpatch.Patch(target, **kwargs))
     return mockfixture.mock
Example #24
0
 def setUp(self):
     self.source_resources = True
     super(TestRunTasks, self).setUp()
     self.useFixture(
         mockpatch.Patch('keystoneclient.v2_0.client.Client',
                         return_value=mock.Mock()))
Example #25
0
 def setUp(self):
     self.client = self.useFixture(
         mockpatch.Patch(
             'aodh.evaluator.gnocchi.client')).mock.Client.return_value
     super(BaseCompositeEvaluate, self).setUp()
Example #26
0
 def test_is_resource_deleted_false(self):
     module = ('tempest.lib.services.compute.volumes_client.'
               'VolumesClient.show_volume')
     self.useFixture(mockpatch.Patch(
         module, return_value={}))
     self.assertFalse(self.client.is_resource_deleted('fake-id'))
Example #27
0
 def test_is_resource_deleted_true(self):
     module = ('tempest.lib.services.compute.volumes_client.'
               'VolumesClient.show_volume')
     self.useFixture(mockpatch.Patch(
         module, side_effect=lib_exc.NotFound))
     self.assertTrue(self.client.is_resource_deleted('fake-id'))
Example #28
0
 def setUp(self):
     super(OpenStackProviderTestCase, self).setUp()
     self.useFixture(
         mockpatch.Patch(
             "rally.deployment.serverprovider.provider.ResourceManager"))
Example #29
0
    def test_send_receive(self):
        self.config(kombu_reconnect_timeout=0.5, group="oslo_messaging_rabbit")
        self.config(heartbeat_timeout_threshold=0,
                    group="oslo_messaging_rabbit")
        self.config(send_single_reply=self.send_single_reply,
                    group="oslo_messaging_rabbit")
        transport = oslo_messaging.get_transport(self.conf,
                                                 'kombu+memory:////')
        self.addCleanup(transport.cleanup)

        driver = transport._driver

        target = oslo_messaging.Target(topic='testtopic')

        listener = driver.listen(target)

        senders = []
        replies = []
        msgs = []
        errors = []

        def stub_error(msg, *a, **kw):
            if (a and len(a) == 1 and isinstance(a[0], dict) and a[0]):
                a = a[0]
            errors.append(str(msg) % a)

        self.stubs.Set(driver_common.LOG, 'error', stub_error)

        def send_and_wait_for_reply(i):
            try:
                if self.reply_failure_404:
                    timeout = 0.01
                else:
                    timeout = self.timeout
                replies.append(
                    driver.send(target,
                                self.ctxt, {'tx_id': i},
                                wait_for_reply=True,
                                timeout=timeout))
                self.assertFalse(self.failure)
                self.assertIsNone(self.timeout)
            except (ZeroDivisionError, oslo_messaging.MessagingTimeout) as e:
                replies.append(e)
                self.assertTrue(self.failure or self.timeout is not None
                                or self.reply_failure_404)

        while len(senders) < self.n_senders:
            senders.append(
                threading.Thread(target=send_and_wait_for_reply,
                                 args=(len(senders), )))

        for i in range(len(senders)):
            senders[i].start()

            received = listener.poll()
            self.assertIsNotNone(received)
            self.assertEqual(self.ctxt, received.ctxt)
            self.assertEqual({'tx_id': i}, received.message)
            msgs.append(received)

        # reply in reverse, except reply to the first guy second from last
        order = list(range(len(senders) - 1, -1, -1))
        if len(order) > 1:
            order[-1], order[-2] = order[-2], order[-1]

        if self.reply_failure_404:
            start = time.time()
            # NOTE(sileht): Simulate a rpc client restart
            # By returning a ExchangeNotFound when we try to
            # send reply
            exc = (
                driver._reply_q_conn.connection.connection.channel_errors[0]())
            exc.code = 404
            self.useFixture(
                mockpatch.Patch('kombu.messaging.Producer.publish',
                                side_effect=exc))

        for i in order:
            if self.timeout is None:
                if self.failure:
                    try:
                        raise ZeroDivisionError
                    except Exception:
                        failure = sys.exc_info()
                    msgs[i].reply(failure=failure,
                                  log_failure=not self.expected)
                elif self.rx_id:
                    msgs[i].reply({'rx_id': i})
                else:
                    msgs[i].reply(self.reply)
            elif self.reply_failure_404:
                msgs[i].reply({})
            senders[i].join()

        if self.reply_failure_404:
            # NOTE(sileht) all reply fail, first take
            # kombu_reconnect_timeout seconds to fail
            # next immediately fail
            dt = time.time() - start
            timeout = self.conf.oslo_messaging_rabbit.kombu_reconnect_timeout
            self.assertTrue(timeout <= dt < (timeout + 0.100), dt)

        self.assertEqual(len(senders), len(replies))
        for i, reply in enumerate(replies):
            if self.timeout is not None or self.reply_failure_404:
                self.assertIsInstance(reply, oslo_messaging.MessagingTimeout)
            elif self.failure:
                self.assertIsInstance(reply, ZeroDivisionError)
            elif self.rx_id:
                self.assertEqual({'rx_id': order[i]}, reply)
            else:
                self.assertEqual(self.reply, reply)

        if not self.timeout and self.failure and not self.expected:
            self.assertTrue(len(errors) > 0, errors)
        else:
            self.assertEqual(0, len(errors), errors)
Example #30
0
 def setUp(self):
     super(TestAccount, self).setUp()
     self.useFixture(fake_config.ConfigFixture())
     self.stubs.Set(config, 'TempestConfigPrivate', fake_config.FakePrivate)
     self.useFixture(lockutils_fixtures.ExternalLockFixture())
     self.test_accounts = [
         {
             'username': '******',
             'tenant_name': 'test_tenant1',
             'password': '******'
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant2',
             'password': '******'
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant3',
             'password': '******'
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant4',
             'password': '******'
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant5',
             'password': '******'
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant6',
             'password': '******',
             'roles': ['role1', 'role2']
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant7',
             'password': '******',
             'roles': ['role2', 'role3']
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant8',
             'password': '******',
             'roles': ['role4', 'role1']
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant9',
             'password': '******',
             'roles': ['role1', 'role2', 'role3', 'role4']
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant10',
             'password': '******',
             'roles': ['role1', 'role2', 'role3', 'role4']
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant11',
             'password': '******',
             'roles': [cfg.CONF.identity.admin_role]
         },
         {
             'username': '******',
             'tenant_name': 'test_tenant12',
             'password': '******',
             'roles': [cfg.CONF.identity.admin_role]
         },
     ]
     self.useFixture(
         mockpatch.Patch('tempest.common.accounts.read_accounts_yaml',
                         return_value=self.test_accounts))
     cfg.CONF.set_default('test_accounts_file', 'fake_path', group='auth')
     self.useFixture(mockpatch.Patch('os.path.isfile', return_value=True))