Exemplo n.º 1
0
    def test_head_update_headers(self):
        self.useFixture(
            mockpatch.PatchObject(self.rest_client, 'response_checker'))

        __, return_dict = self.rest_client.head(self.url,
                                                extra_headers=True,
                                                headers=self.headers)

        self.assertDictContainsSubset(
            {
                'X-Configuration-Session': 'session_id',
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }, return_dict['headers'])
Exemplo n.º 2
0
    def setUp(self):
        super(TestEventEndpoint, self).setUp()
        self.CONF = self.useFixture(fixture_config.Config()).conf
        self.CONF([])
        self.CONF.set_override("connection", "log://", group='database')
        self.CONF.set_override("store_events", True, group="notification")
        self.setup_messaging(self.CONF)

        self.useFixture(mockpatch.PatchObject(publisher, 'get_publisher',
                                              side_effect=self.get_publisher))
        self.fake_publisher = mock.Mock()
        self.useFixture(mockpatch.Patch(
            'ceilometer.publisher.test.TestPublisher',
            return_value=self.fake_publisher))
Exemplo n.º 3
0
    def test_create_secgroup(self):
        self.useFixture(mockpatch.PatchObject(javelin, "client_for_user",
                                              return_value=self.fake_client))
        self.fake_client.secgroups.list_security_groups.return_value = (
            {'security_groups': []})
        self.fake_client.secgroups.create_security_group.return_value = \
            {'security_group': {'id': self.fake_object['secgroup_id']}}

        javelin.create_secgroups([self.fake_object])

        mocked_function = self.fake_client.secgroups.create_security_group
        mocked_function.assert_called_once_with(
            name=self.fake_object['name'],
            description=self.fake_object['description'])
Exemplo n.º 4
0
 def _mock_list_ec2_credentials(self, user_id, tenant_id):
     ec2_creds_fix = self.useFixture(
         mockpatch.PatchObject(
             json_iden_client.IdentityClientJSON,
             'list_user_ec2_credentials',
             return_value=(service_client.ResponseBodyList(
                 200, [{
                     'access': 'fake_access',
                     'secret': 'fake_secret',
                     'tenant_id': tenant_id,
                     'user_id': user_id,
                     'trust_id': None
                 }]))))
     return ec2_creds_fix
Exemplo n.º 5
0
    def test_hardware_discover_fail_minimize_logs(self, novalog, baselog):
        self.useFixture(
            mockpatch.PatchObject(novaclient.HTTPClient,
                                  'authenticate',
                                  side_effect=requests.ConnectionError))

        class PollsterHardware(agentbase.TestPollster):
            discovery = 'tripleo_overcloud_nodes'

        class PollsterHardwareAnother(agentbase.TestPollster):
            discovery = 'tripleo_overcloud_nodes'

        self.mgr.extensions.extend([
            extension.Extension(
                'testhardware',
                None,
                None,
                PollsterHardware(self.CONF),
            ),
            extension.Extension(
                'testhardware2',
                None,
                None,
                PollsterHardwareAnother(self.CONF),
            )
        ])
        ext = extension.Extension('tripleo_overcloud_nodes', None, None,
                                  discovery.NodesDiscoveryTripleO(self.CONF))
        self.mgr.discoveries = (extension.ExtensionManager.make_test_instance(
            [ext]))

        self.pipeline_cfg = {
            'sources': [{
                'name': "test_hardware",
                'interval': 10,
                'meters': ['testhardware', 'testhardware2'],
                'sinks': ['test_sink']
            }],
            'sinks': [{
                'name': 'test_sink',
                'transformers': [],
                'publishers': ["test"]
            }]
        }
        self.mgr.polling_manager = pipeline.PollingManager(
            self.CONF, self.pipeline_cfg)
        polling_tasks = self.mgr.setup_polling_tasks()
        self.mgr.interval_task(list(polling_tasks.values())[0])
        self.assertEqual(1, novalog.exception.call_count)
        self.assertFalse(baselog.exception.called)
Exemplo n.º 6
0
    def test_attach_volumes(self):
        self.useFixture(
            mockpatch.PatchObject(javelin,
                                  "client_for_user",
                                  return_value=self.fake_client))

        self.useFixture(
            mockpatch.PatchObject(javelin,
                                  "_get_volume_by_name",
                                  return_value=self.fake_object.volume))

        self.useFixture(
            mockpatch.PatchObject(javelin,
                                  "_get_server_by_name",
                                  return_value=self.fake_object.server))

        javelin.attach_volumes([self.fake_object])

        mocked_function = self.fake_client.volumes.attach_volume
        mocked_function.assert_called_once_with(
            self.fake_object.volume['id'],
            instance_uuid=self.fake_object.server['id'],
            mountpoint=self.fake_object['device'])
Exemplo n.º 7
0
    def test_create_user_missing_tenant(self):
        self.useFixture(
            mockpatch.Patch(
                'tempest.common.identity.get_tenant_by_name',
                side_effect=lib_exc.NotFound("tenant is not found")))
        self.useFixture(
            mockpatch.PatchObject(javelin,
                                  "keystone_admin",
                                  return_value=self.fake_client))

        javelin.create_users([self.fake_object])

        mocked_function = self.fake_client.users.create_user
        self.assertFalse(mocked_function.called)
Exemplo n.º 8
0
    def setUp(self):
        super(TestEventEndpoint, self).setUp()
        self.CONF = service.prepare_service([], [])
        self.CONF.set_override("connection", "log://", group='database')
        self.setup_messaging(self.CONF)

        self.useFixture(
            mockpatch.PatchObject(publisher,
                                  'get_publisher',
                                  side_effect=self.get_publisher))
        self.fake_publisher = mock.Mock()
        self.useFixture(
            mockpatch.Patch('ceilometer.publisher.test.TestPublisher',
                            return_value=self.fake_publisher))
Exemplo n.º 9
0
    def setUp(self):
        super(FloatingIpTestCase, self).setUp()

        self.event_created = floatingip.EVENT_FLOATINGIP_CREATE_END
        self.event_resized = floatingip.EVENT_FLOATINGIP_RESIZE_END
        self.event_deleted = floatingip.EVENT_FLOATINGIP_DELETE_END

        self.floating_ip_address = '2.4.6.8'
        self.price_data = self.build_segmented_price_data(
            '5.0000', [[10, '0.1'], [4, '0.2'], [0, '0.3']])

        self.useFixture(mockpatch.PatchObject(
            floatingip.FloatingIpNotificationBase,
            '_send_email_notification'))
Exemplo n.º 10
0
    def setUp(self):
        super(TestCase, self).setUp()

        self.addCleanup(CONF.reset)

        self.config_fixture = self.useFixture(config_fixture.Config(CONF))
        self.addCleanup(delattr, self, 'config_fixture')
        self.config(self.config_files())

        # NOTE(morganfainberg): mock the auth plugin setup to use the config
        # fixture which automatically unregisters options when performing
        # cleanup.
        def mocked_register_auth_plugin_opt(conf, opt):
            self.config_fixture.register_opt(opt, group='auth')

        self.useFixture(
            mockpatch.PatchObject(common_cfg,
                                  '_register_auth_plugin_opt',
                                  new=mocked_register_auth_plugin_opt))

        self.config_overrides()

        self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))

        # NOTE(morganfainberg): This code is a copy from the oslo-incubator
        # log module. This is not in a function or otherwise available to use
        # without having a CONF object to setup logging. This should help to
        # reduce the log size by limiting what we log (similar to how Keystone
        # would run under mod_wsgi or eventlet).
        for pair in CONF.default_log_levels:
            mod, _sep, level_name = pair.partition('=')
            logger = logging.getLogger(mod)
            logger.setLevel(level_name)

        self.useFixture(ksfixtures.Cache())

        # Clear the registry of providers so that providers from previous
        # tests aren't used.
        self.addCleanup(dependency.reset)

        self.addCleanup(kvs.INMEMDB.clear)

        # Ensure Notification subscriptions and resource types are empty
        self.addCleanup(notifications.clear_subscribers)
        self.addCleanup(notifications.reset_notifier)

        # Reset the auth-plugin registry
        self.addCleanup(self.clear_auth_plugin_registry)

        self.addCleanup(setattr, controllers, '_VERSIONS', [])
Exemplo n.º 11
0
    def test_create_images(self):
        self.fake_client.images.create_image.return_value = \
            self.fake_object['body']

        self.useFixture(mockpatch.PatchObject(javelin, "client_for_user",
                                              return_value=self.fake_client))
        self.useFixture(mockpatch.PatchObject(javelin, "_get_image_by_name",
                                              return_value=[]))
        self.useFixture(mockpatch.PatchObject(javelin, "_resolve_image",
                                              return_value=(None, None)))

        with mock.patch('six.moves.builtins.open', mock.mock_open(),
                        create=True) as open_mock:
            javelin.create_images([self.fake_object])

        mocked_function = self.fake_client.images.create_image
        mocked_function.assert_called_once_with(self.fake_object['name'],
                                                self.fake_object['format'],
                                                self.fake_object['format'])

        mocked_function = self.fake_client.images.store_image
        fake_image_id = self.fake_object['body'].get('id')
        mocked_function.assert_called_once_with(fake_image_id, open_mock())
Exemplo n.º 12
0
    def test_iter_accounts_cached(self):
        # Verify that if a method has already been called, _iter_accounts
        # uses the cached version and doesn't call rgw_clinet.
        mock_method = mock.Mock()
        mock_method.side_effect = AssertionError('should not be called', )

        api_method = 'get_%s' % self.pollster.METHOD

        with mockpatch.PatchObject(rgw_client, api_method, new=mock_method):
            cache = {self.pollster.CACHE_KEY_METHOD: [self.ACCOUNTS[0]]}
            data = list(
                self.pollster._iter_accounts(mock.Mock(), cache,
                                             ASSIGNED_TENANTS))
        self.assertEqual([self.ACCOUNTS[0]], data)
Exemplo n.º 13
0
    def test_put(self):
        put_mock = self.useFixture(mockpatch.PatchObject(
            self.client, 'put', autospec=True, return_value=(None, self.body))
        ).mock

        rsrc = self.mgr._put(self.url, self.body, "hello")
        put_mock.assert_called_once_with(self.url, body=self.body)
        self.assertEqual(rsrc.hi, 1)

        put_mock.reset_mock()

        rsrc = self.mgr._put(self.url, self.body)
        put_mock.assert_called_once_with(self.url, body=self.body)
        self.assertEqual(rsrc.hello["hi"], 1)
Exemplo n.º 14
0
 def _mock_list_roles(self, id, name):
     roles_fix = self.useFixture(
         mockpatch.PatchObject(
             json_iden_client.IdentityClientJSON,
             'list_roles',
             return_value=(service_client.ResponseBodyList(
                 200, [{
                     'id': id,
                     'name': name
                 }, {
                     'id': '1',
                     'name': 'FakeRole'
                 }]))))
     return roles_fix
 def test_get_nova_versions(self):
     self.useFixture(
         mockpatch.PatchObject(verify_tempest_config,
                               '_get_unversioned_endpoint',
                               return_value='http://fake_endpoint:5000'))
     fake_resp = {'versions': [{'id': 'v2.0'}, {'id': 'v3.0'}]}
     fake_resp = json.dumps(fake_resp)
     self.useFixture(
         mockpatch.Patch('tempest.lib.common.http.ClosingHttp.request',
                         return_value=(None, fake_resp)))
     fake_os = mock.MagicMock()
     versions = verify_tempest_config._get_api_versions(fake_os, 'nova')
     self.assertIn('v2.0', versions)
     self.assertIn('v3.0', versions)
 def test_verify_cinder_api_versions_no_v1(self, mock_request):
     self.useFixture(
         mockpatch.PatchObject(verify_tempest_config,
                               '_get_unversioned_endpoint',
                               return_value='http://fake_endpoint:5000'))
     fake_resp = {'versions': [{'id': 'v2.0'}]}
     fake_resp = json.dumps(fake_resp)
     mock_request.return_value = (None, fake_resp)
     fake_os = mock.MagicMock()
     with mock.patch.object(verify_tempest_config,
                            'print_and_or_update') as print_mock:
         verify_tempest_config.verify_cinder_api_versions(fake_os, True)
     print_mock.assert_called_once_with('api_v1', 'volume-feature-enabled',
                                        False, True)
Exemplo n.º 17
0
    def test_destroy_tenants(self):

        fake_tenant = self.fake_object['tenant']
        fake_auth = self.fake_client
        self.useFixture(
            mockpatch.Patch('tempest.common.identity.get_tenant_by_name',
                            return_value=fake_tenant))
        self.useFixture(
            mockpatch.PatchObject(javelin,
                                  "keystone_admin",
                                  return_value=fake_auth))
        javelin.destroy_tenants([fake_tenant])

        mocked_function = fake_auth.tenants.delete_tenant
        mocked_function.assert_called_once_with(fake_tenant['id'])
Exemplo n.º 18
0
    def setUp(self):
        self.config_fixture = self.useFixture(config_fixture.Config(CONF))
        self.config_fixture.register_cli_opt(cli.command_opt)
        super(CliNoConfigTestCase, self).setUp()

        # NOTE(crinkle): the command call doesn't have to actually work,
        # that's what the other unit tests are for. So just mock it out.
        class FakeConfCommand(object):
            def __init__(self):
                self.cmd_class = mock.Mock()

        self.useFixture(
            mockpatch.PatchObject(CONF, 'command', FakeConfCommand()))

        self.logging = self.useFixture(fixtures.FakeLogger(level=logging.WARN))
Exemplo n.º 19
0
 def _mock_list_role(self):
     roles_fix = self.useFixture(
         mockpatch.PatchObject(self.roles_client.RolesClient,
                               'list_roles',
                               return_value=(rest_client.ResponseBody(
                                   200, {
                                       'roles': [{
                                           'id': '1',
                                           'name': 'FakeRole'
                                       }, {
                                           'id': '2',
                                           'name': 'Member'
                                       }]
                                   }))))
     return roles_fix
Exemplo n.º 20
0
    def test_create_duplicate_tenant(self):
        self.fake_client.identity.list_tenants.return_value = {
            'tenants': [{
                'name': self.fake_object['name']
            }]
        }
        self.useFixture(
            mockpatch.PatchObject(javelin,
                                  "keystone_admin",
                                  return_value=self.fake_client))

        javelin.create_tenants([self.fake_object['name']])

        mocked_function = self.fake_client.identity.create_tenant
        self.assertFalse(mocked_function.called)
 def _mock_list_ec2_credentials(self, user_id, tenant_id):
     ec2_creds_fix = self.useFixture(
         mockpatch.PatchObject(json_users_client.UsersClient,
                               'list_user_ec2_credentials',
                               return_value=(rest_client.ResponseBody(
                                   200, {
                                       'credentials': [{
                                           'access': 'fake_access',
                                           'secret': 'fake_secret',
                                           'tenant_id': tenant_id,
                                           'user_id': user_id,
                                           'trust_id': None
                                       }]
                                   }))))
     return ec2_creds_fix
Exemplo n.º 22
0
    def setUp(self):
        super(TestCase, self).setUp()
        self.addCleanup(
            self.cleanup_instance('_paths', '_memo', '_overrides',
                                  '_group_overrides', 'maxDiff', 'exit_patch',
                                  'config_fixture', 'logger'))

        self._paths = []

        def _cleanup_paths():
            for path in self._paths:
                if path in sys.path:
                    sys.path.remove(path)

        self.addCleanup(_cleanup_paths)

        self._memo = {}
        self._overrides = []
        self._group_overrides = {}

        # show complete diffs on failure
        self.maxDiff = None

        self.addCleanup(CONF.reset)

        self.exit_patch = self.useFixture(mockpatch.PatchObject(sys, 'exit'))
        self.exit_patch.mock.side_effect = UnexpectedExit
        self.config_fixture = self.useFixture(config_fixture.Config(CONF))
        self.config(self.config_files())

        self.config_overrides()

        self.logger = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        self.useFixture(ksfixtures.Cache())

        # Clear the registry of providers so that providers from previous
        # tests aren't used.
        self.addCleanup(dependency.reset)

        self.addCleanup(kvs.INMEMDB.clear)

        # Ensure Notification subscriotions and resource types are empty
        self.addCleanup(notifications.clear_subscribers)
        self.addCleanup(notifications.reset_notifier)

        # Reset the auth-plugin registry
        self.addCleanup(self.clear_auth_plugin_registry)
Exemplo n.º 23
0
 def test__get_creds_by_roles_one_role(self):
     test_accounts_class = preprov_creds.PreProvisionedCredentialProvider(
         **self.fixed_params)
     hashes = test_accounts_class.hash_dict['roles']['role4']
     temp_hash = hashes[0]
     get_free_hash_mock = self.useFixture(
         mockpatch.PatchObject(test_accounts_class,
                               '_get_free_hash',
                               return_value=temp_hash))
     # Test a single role returns all matching roles
     test_accounts_class._get_creds(roles=['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)
Exemplo n.º 24
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.identity.get_tenant_by_name.return_value = fake_tenant
        fake_auth.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.identity.delete_user
        mocked_function.assert_called_once_with(fake_user['id'])
Exemplo n.º 25
0
 def test__get_creds_by_roles_one_role(self):
     self.useFixture(mockpatch.Patch(
         'tempest.common.accounts.read_accounts_yaml',
         return_value=self.test_accounts))
     test_accounts_class = accounts.Accounts('v2', 'test_name')
     hashes = test_accounts_class.hash_dict['roles']['role4']
     temp_hash = hashes[0]
     get_free_hash_mock = self.useFixture(mockpatch.PatchObject(
         test_accounts_class, '_get_free_hash', return_value=temp_hash))
     # Test a single role returns all matching roles
     test_accounts_class._get_creds(roles=['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)
Exemplo n.º 26
0
    def test_resource_lazy_getattr(self):
        # Creating a Client not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            self.client = client.Client(token=self.TEST_TOKEN,
                                        auth_url='http://127.0.0.1:5000',
                                        endpoint='http://127.0.0.1:5000')

        self.useFixture(mockpatch.PatchObject(
            self.client._adapter, 'get', side_effect=AttributeError,
            autospec=True))

        f = roles.Role(self.client.roles, {'id': 1, 'name': 'Member'})
        self.assertEqual(f.name, 'Member')

        # Missing stuff still fails after a second get
        self.assertRaises(AttributeError, getattr, f, 'blahblah')
Exemplo n.º 27
0
 def test_verify_extensions_nova_all(self):
     def fake_list_extensions():
         return ({'extensions': [{'alias': 'fake1'},
                                 {'alias': 'fake2'},
                                 {'alias': 'not_fake'}]})
     fake_os = mock.MagicMock()
     fake_os.extensions_client.list_extensions = fake_list_extensions
     self.useFixture(mockpatch.PatchObject(
         verify_tempest_config, 'get_enabled_extensions',
         return_value=(['all'])))
     results = verify_tempest_config.verify_extensions(fake_os,
                                                       'nova', {})
     self.assertIn('nova', results)
     self.assertIn('extensions', results['nova'])
     self.assertEqual(sorted(['fake1', 'fake2', 'not_fake']),
                      sorted(results['nova']['extensions']))
Exemplo n.º 28
0
 def test__get_creds_by_roles_list_role(self):
     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)
Exemplo n.º 29
0
    def test_resource_lazy_getattr(self):
        self.client = client.Client(username=self.TEST_USER,
                                    token=self.TEST_TOKEN,
                                    tenant_name=self.TEST_TENANT_NAME,
                                    auth_url='http://127.0.0.1:5000',
                                    endpoint='http://127.0.0.1:5000')

        self.useFixture(mockpatch.PatchObject(
            self.client._adapter, 'get', side_effect=AttributeError,
            autospec=True))

        f = roles.Role(self.client.roles, {'id': 1, 'name': 'Member'})
        self.assertEqual(f.name, 'Member')

        # Missing stuff still fails after a second get
        self.assertRaises(AttributeError, getattr, f, 'blahblah')
Exemplo n.º 30
0
    def setUp(self):
        super(CadfNotificationsWrapperTestCase, self).setUp()
        self._notifications = []

        def fake_notify(action, initiator, outcome):
            note = {
                'action': action,
                'initiator': initiator,
                # NOTE(stevemar): outcome has 2 stages, pending and success
                # so we are ignoring it for now.
                # 'outcome': outcome,
                'send_notification_called': True}
            self._notifications.append(note)

        self.useFixture(mockpatch.PatchObject(
            notifications, '_send_audit_notification', fake_notify))