def test_service_catalog_default(self): ctxt = context.RequestContext('111', '222') self.assertEqual(ctxt.service_catalog, []) ctxt = context.RequestContext('111', '222', service_catalog=[]) self.assertEqual(ctxt.service_catalog, []) ctxt = context.RequestContext('111', '222', service_catalog=None) self.assertEqual(ctxt.service_catalog, [])
def setUp(self): super(SimpleTenantUsageTestV21, self).setUp() self.admin_context = context.RequestContext('fakeadmin_0', 'faketenant_0', is_admin=True) self.user_context = context.RequestContext('fakeadmin_0', 'faketenant_0', is_admin=False) self.alt_user_context = context.RequestContext('fakeadmin_0', 'faketenant_1', is_admin=False)
def setUp(self): super(DeferredDeleteExtensionTestV21, self).setUp() self.fake_input_dict = {} self.fake_uuid = 'fake_uuid' self.fake_context = context.RequestContext('fake', 'fake') self.fake_req = FakeRequest(self.fake_context) self.extension = self.ext_ver()
def test_default_client_without_retries(self, create_client_mock, sleep_mock, shuffle_mock): api_servers = ['host1:9292', 'https://host2:9293', 'http://host3:9294'] client_mock = mock.MagicMock() images_mock = mock.MagicMock() images_mock.get.side_effect = glanceclient.exc.ServiceUnavailable type(client_mock).images = mock.PropertyMock(return_value=images_mock) create_client_mock.return_value = client_mock shuffle_mock.return_value = api_servers self.flags(num_retries=0, group='glance') self.flags(api_servers=api_servers, group='glance') # Here we are testing the behaviour that calling client.call() twice # when there are no retries will cycle through the api_servers and not # sleep (which would be an indication of a retry) ctx = context.RequestContext('fake', 'fake') client = glance.GlanceClientWrapper() self.assertRaises(exception.GlanceConnectionFailed, client.call, ctx, 1, 'get', 'meow') self.assertFalse(sleep_mock.called) self.assertRaises(exception.GlanceConnectionFailed, client.call, ctx, 1, 'get', 'meow') self.assertFalse(sleep_mock.called) create_client_mock.assert_has_calls([ mock.call(ctx, 'host1', 9292, False, 1), mock.call(ctx, 'host2', 9293, True, 1), ])
def setUp(self): def fake_get_nw_info(cls, ctxt, instance): self.assertTrue(ctxt.is_admin) return fake_network.fake_get_instance_nw_info(self.stubs, 1, 1) super(UsageInfoTestCase, self).setUp() self.stubs.Set(network_api.API, 'get_instance_nw_info', fake_get_nw_info) fake_notifier.stub_notifier(self.stubs) self.addCleanup(fake_notifier.reset) self.flags(use_local=True, group='conductor') self.flags(compute_driver='patron.virt.fake.FakeDriver', network_manager='patron.network.manager.FlatManager') self.compute = importutils.import_object(CONF.compute_manager) self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) def fake_show(meh, context, id, **kwargs): return {'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1}} self.stubs.Set(patron.tests.unit.image.fake._FakeImageService, 'show', fake_show) fake_network.set_stub_network_methods(self.stubs) fake_server_actions.stub_out_action_events(self.stubs)
def test_service_catalog_cinder_only(self): service_catalog = [{ u'type': u'compute', u'name': u'patron' }, { u'type': u's3', u'name': u's3' }, { u'type': u'image', u'name': u'glance' }, { u'type': u'volume', u'name': u'cinder' }, { u'type': u'ec2', u'name': u'ec2' }, { u'type': u'object-store', u'name': u'swift' }, { u'type': u'identity', u'name': u'keystone' }, { u'type': None, u'name': u'S_withouttype' }, { u'type': u'vo', u'name': u'S_partofvolume' }] volume_catalog = [{u'type': u'volume', u'name': u'cinder'}] ctxt = context.RequestContext('111', '222', service_catalog=service_catalog) self.assertEqual(ctxt.service_catalog, volume_catalog)
def setUp(self): super(HyperVAPIBaseTestCase, self).setUp() self._user_id = 'fake' self._project_id = 'fake' self._instance = None self._image_metadata = None self._fetched_image = None self._update_image_raise_exception = False self._volume_target_portal = 'testtargetportal:3260' self._volume_id = '0ef5d708-45ab-4129-8c59-d774d2837eb7' self._context = context.RequestContext(self._user_id, self._project_id) self._instance_disks = [] self._instance_dvds = [] self._instance_volume_disks = [] self._test_vm_name = None self._test_instance_dir = 'C:\\FakeInstancesPath\\instance-0000001' self._check_min_windows_version_satisfied = True self._setup_stubs() self.flags(instances_path=r'C:\Hyper-V\test\instances', network_api_class='patron.network.neutronv2.api.API') self.flags(force_volumeutils_v1=True, group='hyperv') self.flags(force_hyperv_utils_v1=True, group='hyperv') self._conn = driver_hyperv.HyperVDriver(None)
def setUp(self): super(TestGlanceStore, self).setUp() self.store = glance.GlanceStore() self.flags(host='1.1.1.1', port=123, api_insecure=False, group='glance') self.flags(connection_url='test_url', connection_password='******', group='xenserver') self.context = context.RequestContext('user', 'project', auth_token='foobar') fake.reset() stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.stubs.Set(vm_utils, 'get_sr_path', lambda *a, **kw: '/fake/sr/path') self.instance = { 'uuid': 'blah', 'system_metadata': [], 'auto_disk_config': True, 'os_type': 'default', 'xenapi_use_agent': 'true' }
def setUp(self): super(TestBittorrentStore, self).setUp() self.store = bittorrent.BittorrentStore() self.mox = mox.Mox() self.flags(torrent_base_url='http://foo', connection_url='test_url', connection_password='******', group='xenserver') self.context = context.RequestContext('user', 'project', auth_token='foobar') fake.reset() stubs.stubout_session(self.stubs, fake.SessionBase) def mock_iter_eps(namespace): return [] self.stubs.Set(pkg_resources, 'iter_entry_points', mock_iter_eps) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.stubs.Set(vm_utils, 'get_sr_path', lambda *a, **kw: '/fake/sr/path')
def __call__(self, req): """Generate a WSGI response based on the exception passed to ctor.""" code = patron.api.ec2.exception_to_ec2code(self.wrapped_exc) status = self.wrapped_exc.status_int message = self.wrapped_exc.explanation if status == 501: message = "The requested function is not supported" if 'AWSAccessKeyId' not in req.params: raise webob.exc.HTTPBadRequest() user_id, _sep, project_id = req.params['AWSAccessKeyId'].partition(':') project_id = project_id or user_id remote_address = getattr(req, 'remote_address', '127.0.0.1') if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) ctxt = context.RequestContext(user_id, project_id, remote_address=remote_address) resp = ec2_error_response(ctxt.request_id, code, message=message, status=status) return resp
def test_default_client_with_retries(self, create_client_mock, sleep_mock, shuffle_mock): api_servers = ['host1:9292', 'https://host2:9293', 'http://host3:9294'] client_mock = mock.MagicMock() images_mock = mock.MagicMock() images_mock.get.side_effect = [ glanceclient.exc.ServiceUnavailable, None ] type(client_mock).images = mock.PropertyMock(return_value=images_mock) create_client_mock.return_value = client_mock self.flags(num_retries=1, group='glance') self.flags(api_servers=api_servers, group='glance') ctx = context.RequestContext('fake', 'fake') # And here we're testing that if num_retries is not 0, then we attempt # to retry the same connection action against the next client. client = glance.GlanceClientWrapper() client.call(ctx, 1, 'get', 'meow') create_client_mock.assert_has_calls([ mock.call(ctx, 'host1', 9292, False, 1), mock.call(ctx, 'host2', 9293, True, 1), ]) sleep_mock.assert_called_once_with(1)
def _test_scheduler_api(self, method, rpc_method, **kwargs): ctxt = context.RequestContext('fake_user', 'fake_project') rpcapi = scheduler_rpcapi.SchedulerAPI() self.assertIsNotNone(rpcapi.client) self.assertEqual(rpcapi.client.target.topic, CONF.scheduler_topic) expected_retval = 'foo' if rpc_method == 'call' else None expected_version = kwargs.pop('version', None) expected_fanout = kwargs.pop('fanout', None) expected_kwargs = kwargs.copy() self.mox.StubOutWithMock(rpcapi, 'client') rpcapi.client.can_send_version( mox.IsA(str)).MultipleTimes().AndReturn(True) prepare_kwargs = {} if expected_fanout: prepare_kwargs['fanout'] = True if expected_version: prepare_kwargs['version'] = expected_version rpcapi.client.prepare(**prepare_kwargs).AndReturn(rpcapi.client) rpc_method = getattr(rpcapi.client, rpc_method) rpc_method(ctxt, method, **expected_kwargs).AndReturn(expected_retval) self.mox.ReplayAll() # NOTE(markmc): MultipleTimes() is OnceOrMore() not ZeroOrMore() rpcapi.client.can_send_version('I fool you mox') retval = getattr(rpcapi, method)(ctxt, **kwargs) self.assertEqual(retval, expected_retval)
def create_mapping(**kwargs): args = sample_mapping.copy() if 'instance_uuid' not in kwargs: args['instance_uuid'] = uuidutils.generate_uuid() args.update(kwargs) ctxt = context.RequestContext('fake-user', 'fake-project') return instance_mapping.InstanceMapping._create_in_db(ctxt, args)
def setUp(self): super(NotificationsTestCase, self).setUp() self.fixture = self.useFixture(o_fixture.ClearRequestContext()) self.net_info = fake_network.fake_get_instance_nw_info( self.stubs, 1, 1) def fake_get_nw_info(cls, ctxt, instance): self.assertTrue(ctxt.is_admin) return self.net_info self.stubs.Set(network_api.API, 'get_instance_nw_info', fake_get_nw_info) fake_network.set_stub_network_methods(self.stubs) fake_notifier.stub_notifier(self.stubs) self.addCleanup(fake_notifier.reset) self.flags(compute_driver='patron.virt.fake.FakeDriver', network_manager='patron.network.manager.FlatManager', notify_on_state_change="vm_and_task_state", host='testhost') self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) self.instance = self._wrapped_create()
def base_call(self, req, project_id_in_path, always_admin=True): if 'X-Auth-Token' not in req.headers: user_id = req.headers.get('X-Auth-User', 'admin') project_id = req.headers.get('X-Auth-Project-Id', 'admin') if project_id_in_path: os_url = '/'.join([req.url.rstrip('/'), project_id]) else: os_url = req.url.rstrip('/') res = webob.Response() # NOTE(vish): This is expecting and returning Auth(1.1), whereas # keystone uses 2.0 auth. We should probably allow # 2.0 auth here as well. res.headers['X-Auth-Token'] = '%s:%s' % (user_id, project_id) res.headers['X-Server-Management-Url'] = os_url res.content_type = 'text/plain' res.status = '204' return res token = req.headers['X-Auth-Token'] user_id, _sep, project_id = token.partition(':') project_id = project_id or user_id remote_address = getattr(req, 'remote_address', '127.0.0.1') if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) is_admin = always_admin or (user_id == 'admin') ctx = context.RequestContext(user_id, project_id, is_admin=is_admin, remote_address=remote_address) req.environ['patron.context'] = ctx return self.application
def test_convert_from_rc_to_dict(self): ctx = context.RequestContext( 111, 222, request_id='req-679033b7-1755-4929-bf85-eb3bfaef7e0b', timestamp='2015-03-02T22:31:56.641629') values2 = ctx.to_dict() expected_values = { 'auth_token': None, 'domain': None, 'instance_lock_checked': False, 'is_admin': False, 'project_id': 222, 'project_domain': None, 'project_name': None, 'quota_class': None, 'read_deleted': 'no', 'read_only': False, 'remote_address': None, 'request_id': 'req-679033b7-1755-4929-bf85-eb3bfaef7e0b', 'resource_uuid': None, 'roles': [], 'service_catalog': [], 'show_deleted': False, 'tenant': 222, 'timestamp': '2015-03-02T22:31:56.641629', 'user': 111, 'user_domain': None, 'user_id': 111, 'user_identity': '111 222 - - -', 'user_name': None } self.assertEqual(expected_values, values2)
def setUp(self): super(ConsoleAPITestCase, self).setUp() self.context = context.RequestContext('fake', 'fake') self.console_api = console_api.API() self.fake_uuid = '00000000-aaaa-bbbb-cccc-000000000000' self.fake_instance = { 'id': 1, 'uuid': self.fake_uuid, 'host': 'fake_host' } self.fake_console = { 'pool': {'host': 'fake_host'}, 'id': 'fake_id' } def _fake_db_console_get(_ctxt, _console_uuid, _instance_uuid): return self.fake_console self.stubs.Set(db, 'console_get', _fake_db_console_get) def _fake_db_console_get_all_by_instance(_ctxt, _instance_uuid, columns_to_join): return [self.fake_console] self.stubs.Set(db, 'console_get_all_by_instance', _fake_db_console_get_all_by_instance)
def setUp(self): super(TestNeutronDriver, self).setUp() self.mox.StubOutWithMock(neutronapi, 'get_client') self.moxed_client = self.mox.CreateMock(client.Client) neutronapi.get_client(mox.IgnoreArg()).MultipleTimes().AndReturn( self.moxed_client) self.context = context.RequestContext('userid', 'my_tenantid') setattr(self.context, 'auth_token', 'bff4a5a6b9eb4ea2a6efec6eefb77936')
def test_display_members(self): ctx = context.RequestContext('fake_user', 'fake') (ig_uuid, instances, members) = self._create_groups_and_instances(ctx) res_dict = self.controller.show(self.req, ig_uuid) result_members = res_dict['server_group']['members'] self.assertEqual(2, len(result_members)) for member in members: self.assertIn(member, result_members)
def test_get_by_hint(self): instances = self._populate_instances() for instance in instances: ctxt = context.RequestContext('fake_user', instance[2]) ig = instance_group.InstanceGroup.get_by_hint(ctxt, instance[1]) self.assertEqual(instance[1], ig.name) ig = instance_group.InstanceGroup.get_by_hint(ctxt, instance[0]) self.assertEqual(instance[0], ig.uuid)
def setUp(self): super(_TestBandwidthUsage, self).setUp() self.user_id = 'fake_user' self.project_id = 'fake_project' self.context = context.RequestContext(self.user_id, self.project_id) now, start_period = self._time_now_and_start_period() self.expected_bw_usage = self._fake_bw_usage( time=now, start_period=start_period)
def test_request_context_elevated(self): user_ctxt = context.RequestContext('111', '222', admin=False) self.assertFalse(user_ctxt.is_admin) admin_ctxt = user_ctxt.elevated() self.assertTrue(admin_ctxt.is_admin) self.assertIn('admin', admin_ctxt.roles) self.assertFalse(user_ctxt.is_admin) self.assertNotIn('admin', user_ctxt.roles)
def setUp(self): super(FloatingIpPoolTestV21, self).setUp() self.stubs.Set(network.api.API, "get_floating_ip_pools", fake_get_floating_ip_pools) self.context = context.RequestContext('fake', 'fake') self.controller = self.floating_ip_pools.FloatingIPPoolsController() self.req = fakes.HTTPRequest.blank('')
def _get_default_networks(self): project_id = CONF.neutron_default_tenant_id ctx = patron_context.RequestContext(user_id=None, project_id=project_id) networks = {} for n in self.network_api.get_all(ctx): networks[n['id']] = n['label'] return [{'id': k, 'label': v} for k, v in networks.iteritems()]
def setUp(self): super(BaseAPITestCase, self).setUp() self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) self.conductor = self.start_service('conductor', manager=CONF.conductor.manager) self.compute = self.start_service('compute') self.base_rpcapi = baserpc.BaseAPI(CONF.compute_topic)
def test_heal_instances(self): self.flags(instance_updated_at_threshold=1000, instance_update_num_instances=2, group='cells') fake_context = context.RequestContext('fake', 'fake') stalled_time = timeutils.utcnow() updated_since = stalled_time - datetime.timedelta(seconds=1000) def utcnow(): return stalled_time call_info = {'get_instances': 0, 'sync_instances': []} instances = ['instance1', 'instance2', 'instance3'] def get_instances_to_sync(context, **kwargs): self.assertEqual(context, fake_context) call_info['shuffle'] = kwargs.get('shuffle') call_info['project_id'] = kwargs.get('project_id') call_info['updated_since'] = kwargs.get('updated_since') call_info['get_instances'] += 1 return iter(instances) def instance_get_by_uuid(context, uuid): return instances[int(uuid[-1]) - 1] def sync_instance(context, instance): self.assertEqual(context, fake_context) call_info['sync_instances'].append(instance) self.stubs.Set(cells_utils, 'get_instances_to_sync', get_instances_to_sync) self.stubs.Set(self.cells_manager.db, 'instance_get_by_uuid', instance_get_by_uuid) self.stubs.Set(self.cells_manager, '_sync_instance', sync_instance) self.stubs.Set(timeutils, 'utcnow', utcnow) self.cells_manager._heal_instances(fake_context) self.assertEqual(call_info['shuffle'], True) self.assertIsNone(call_info['project_id']) self.assertEqual(call_info['updated_since'], updated_since) self.assertEqual(call_info['get_instances'], 1) # Only first 2 self.assertEqual(call_info['sync_instances'], instances[:2]) call_info['sync_instances'] = [] self.cells_manager._heal_instances(fake_context) self.assertEqual(call_info['shuffle'], True) self.assertIsNone(call_info['project_id']) self.assertEqual(call_info['updated_since'], updated_since) self.assertEqual(call_info['get_instances'], 2) # Now the last 1 and the first 1 self.assertEqual(call_info['sync_instances'], [instances[-1], instances[0]])
def test_request_context_read_deleted_invalid(self): self.assertRaises(ValueError, context.RequestContext, '111', '222', read_deleted=True) ctxt = context.RequestContext('111', '222') self.assertRaises(ValueError, setattr, ctxt, 'read_deleted', True)
def setUp(self): super(ConsoleTestCase, self).setUp() self.flags(console_driver='patron.console.fake.FakeConsoleProxy', stub_compute=True) self.console = importutils.import_object(CONF.console_manager) self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) self.host = 'test_compute_host'
def setUp(self): super(MetadataPasswordTestCase, self).setUp() fake_network.stub_out_nw_api_get_instance_nw_info(self.stubs) self.context = context.RequestContext('fake', 'fake') self.instance = fake_inst_obj(self.context) self.flags(use_local=True, group='conductor') self.mdinst = fake_InstanceMetadata(self.stubs, self.instance, address=None, sgroups=None) self.flags(use_local=True, group='conductor')
def setUp(self): super(ComputeGetImageMetadataTestCase, self).setUp() self.context = context.RequestContext('fake', 'fake') self.image = { "min_ram": 10, "min_disk": 1, "disk_format": "raw", "container_format": "bare", "properties": {}, } self.mock_image_api = mock.Mock() self.mock_image_api.get.return_value = self.image self.ctx = context.RequestContext('fake', 'fake') sys_meta = { 'image_min_ram': 10, 'image_min_disk': 1, 'image_disk_format': 'raw', 'image_container_format': 'bare', } flavor = objects.Flavor( id=0, name='m1.fake', memory_mb=10, vcpus=1, root_gb=1, ephemeral_gb=1, flavorid='0', swap=1, rxtx_factor=0.0, vcpu_weight=None) instance = fake_instance.fake_db_instance( memory_mb=0, root_gb=0, system_metadata=sys_meta) self.instance_obj = objects.Instance._from_db_object( self.ctx, objects.Instance(), instance, expected_attrs=instance_obj.INSTANCE_DEFAULT_FIELDS) with mock.patch.object(self.instance_obj, 'save'): self.instance_obj.set_flavor(flavor)