def test_authorize_token(self): f = fakes.FakeAuthManager() user = nova.auth.manager.User('id1', 'user1', 'user1_key', None, None) f.add_user(user) f.create_project('user1_project', user) req = webob.Request.blank('/v1.0/', {'HTTP_HOST': 'foo'}) req.headers['X-Auth-User'] = '******' req.headers['X-Auth-Key'] = 'user1_key' result = req.get_response(fakes.wsgi_app()) self.assertEqual(result.status, '204 No Content') self.assertEqual(len(result.headers['X-Auth-Token']), 40) self.assertEqual(result.headers['X-Server-Management-Url'], "http://foo/v1.0/") self.assertEqual(result.headers['X-CDN-Management-Url'], "") self.assertEqual(result.headers['X-Storage-Url'], "") token = result.headers['X-Auth-Token'] self.stubs.Set(nova.api.openstack, 'APIRouterV10', fakes.FakeRouter) req = webob.Request.blank('/v1.0/fake') req.headers['X-Auth-Token'] = token result = req.get_response(fakes.wsgi_app()) self.assertEqual(result.status, '200 OK') self.assertEqual(result.headers['X-Test-Success'], 'True')
def test_get_servers_with_offset(self): req = webob.Request.blank('/v1.0/servers?offset=2') res = req.get_response(fakes.wsgi_app()) servers = json.loads(res.body)['servers'] self.assertEqual([s['id'] for s in servers], [2, 3, 4]) req = webob.Request.blank('/v1.0/servers?offset=aaa') res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 400) self.assertTrue('offset' in res.body)
def setUp(self): super(CloudpipeTest, self).setUp() self.app = fakes.wsgi_app() inner_app = compute.APIRouter() self.context = context.RequestContext('fake', 'fake', is_admin=True) self.app = auth.InjectContext(self.context, inner_app) route = inner_app.map.match('/1234/os-cloudpipe') self.controller = route['controller'].controller fakes.stub_out_networking(self.stubs) fakes.stub_out_rate_limiting(self.stubs) self.stubs.Set(db, "instance_get_all_by_project", db_instance_get_all_by_project) self.stubs.Set(db, "security_group_exists", db_security_group_exists) self.stubs.SmartSet(self.controller.cloudpipe, "launch_vpn_instance", pipelib_launch_vpn_instance) #self.stubs.SmartSet(self.controller.auth_manager, "get_project", # auth_manager_get_project) #self.stubs.SmartSet(self.controller.auth_manager, "get_projects", # auth_manager_get_projects) # NOTE(todd): The above code (just setting the stub, not invoking it) # causes failures in AuthManagerLdapTestCase. So use a fake object. self.controller.auth_manager = FakeAuthManager() self.stubs.Set(utils, 'vpn_ping', utils_vpn_ping) global EMPTY_INSTANCE_LIST EMPTY_INSTANCE_LIST = True
def test_keypair_list(self): req = webob.Request.blank('/v2/fake/os-keypairs') res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) res_dict = jsonutils.loads(res.body) response = {'keypairs': [{'keypair': fake_keypair('FAKE')}]} self.assertEqual(res_dict, response)
def test_migrate_live_enabled(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt, init_only=('servers',)) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.body = jsonutils.dumps({ 'os-migrateLive': { 'host': 'hostname', 'block_migration': False, 'disk_over_commit': False, } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None def fake_migrate_server(self, context, instance, scheduler_hint, live, rebuild, flavor, block_migration, disk_over_commit): return None self.stubs.Set(compute_api.API, 'update', fake_update) self.stubs.Set(conductor_api.ComputeTaskAPI, 'migrate_server', fake_migrate_server) res = req.get_response(app) self.assertEqual(res.status_int, 202)
def _make_request(self, url, method='GET'): req = webob.Request.blank(url) req.headers['Accept'] = self.content_type req.method = method res = req.get_response( fakes.wsgi_app(init_only=('servers', 'os-server-password'))) return res
def test_update_item_body_uri_mismatch(self): req = webob.Request.blank('/v1.1/images/1/metadata/bad') req.method = 'PUT' req.body = '{"meta": {"key1": "value1"}}' req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app()) self.assertEqual(400, res.status_int)
def test_list_consoles(self): def fake_get_consoles(cons_self, context, instance_id): self.assertEqual(instance_id, 10) pool1 = dict(console_type='fake_type', public_hostname='fake_hostname') cons1 = dict(id=10, password='******', port='fake_port', pool=pool1) pool2 = dict(console_type='fake_type2', public_hostname='fake_hostname2') cons2 = dict(id=11, password='******', port='fake_port2', pool=pool2) return [cons1, cons2] expected = {'consoles': [{'console': {'id': 10, 'console_type': 'fake_type'}}, {'console': {'id': 11, 'console_type': 'fake_type2'}}]} self.stubs.Set(console.API, 'get_consoles', fake_get_consoles) req = webob.Request.blank('/v1.1/fake/servers/10/consoles') res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) res_dict = json.loads(res.body) self.assertDictMatch(res_dict, expected)
def test_get_user_list(self): req = webob.Request.blank('/v1.0/users') res = req.get_response(fakes.wsgi_app()) res_dict = json.loads(res.body) self.assertEqual(res.status_int, 200) self.assertEqual(len(res_dict['users']), 2)
def test_volume_delete_no_volume(self): self.stubs.Set(volume.api.API, "get", fakes.stub_volume_get_notfound) req = webob.Request.blank('/v2/fake/os-volumes/456') req.method = 'DELETE' resp = req.get_response(fakes.wsgi_app()) self.assertEqual(resp.status_int, 404)
def test_vsa_volume_show_no_volume(self): self.stubs.Set(volume.api.API, "get", fakes.stub_volume_get_notfound) req = webob.Request.blank('/v2/fake/zadr-vsa/123/%s/333' % \ (self.test_objs)) resp = req.get_response(fakes.wsgi_app()) self.assertEqual(resp.status_int, 404)
def _test_verify_show(self, start, stop): tenant_id = 0 req = webob.Request.blank( '/v2/faketenant_0/os-simple-tenant-usage/' 'faketenant_%s?start=%s&end=%s' % (tenant_id, start.isoformat(), stop.isoformat())) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app( fake_auth_context=self.user_context)) self.assertEqual(res.status_int, 200) res_dict = jsonutils.loads(res.body) usage = res_dict['tenant_usage'] servers = usage['server_usages'] self.assertEqual(len(usage['server_usages']), SERVERS) uuids = ['00000000-0000-0000-0000-00000000000000%02d' % (x + (tenant_id * SERVERS)) for x in xrange(SERVERS)] for j in xrange(SERVERS): delta = STOP - START uptime = delta.days * 24 * 3600 + delta.seconds self.assertEqual(int(servers[j]['uptime']), uptime) self.assertEqual(int(servers[j]['hours']), HOURS) self.assertTrue(servers[j]['instance_id'] in uuids)
def test_get_all_server_details_with_host(self): ''' We want to make sure that if two instances are on the same host, then they return the same hostId. If two instances are on different hosts, they should return different hostId's. In this test, there are 5 instances - 2 on one host and 3 on another. ''' def stub_instance(id, user_id=1): return Instance(id=id, state=0, image_id=10, user_id=user_id, display_name='server%s' % id, host='host%s' % (id % 2)) def return_servers_with_host(context, user_id=1): return [stub_instance(i) for i in xrange(5)] self.stubs.Set(nova.db.api, 'instance_get_all_by_user', return_servers_with_host) req = webob.Request.blank('/v1.0/servers/detail') res = req.get_response(fakes.wsgi_app()) res_dict = json.loads(res.body) server_list = res_dict['servers'] host_ids = [server_list[0]['hostId'], server_list[1]['hostId']] self.assertTrue(host_ids[0] and host_ids[1]) self.assertNotEqual(host_ids[0], host_ids[1]) for i, s in enumerate(res_dict['servers']): self.assertEqual(s['id'], i) self.assertEqual(s['hostId'], host_ids[i % 2]) self.assertEqual(s['name'], 'server%d' % i) self.assertEqual(s['imageId'], 10)
def test_delete(self): self.stubs.Set(nova.db.api, 'instance_type_extra_specs_delete', delete_flavor_extra_specs) req = webob.Request.blank('/v1.1/flavors/1/os-extra_specs/key5') req.method = 'DELETE' res = req.get_response(fakes.wsgi_app()) self.assertEqual(200, res.status_int)
def test_instance_type_exists_exception_returns_409(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": 1235, "swap": 512, "rxtx_factor": 1, } } def fake_create(name, memory_mb, vcpus, root_gb, ephemeral_gb, flavorid, swap, rxtx_factor): raise exception.InstanceTypeExists() self.stubs.Set(instance_types, "create", fake_create) url = "/v2/fake/flavors" req = webob.Request.blank(url) req.headers["Content-Type"] = "application/json" req.method = "POST" req.body = json.dumps(expected) res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 409)
def test_show_spec_not_found(self): self.stubs.Set(nova.db.api, 'instance_type_extra_specs_get', return_empty_flavor_extra_specs) req = webob.Request.blank('/v1.1/flavors/1/os-extra_specs/key6') res = req.get_response(fakes.wsgi_app()) res_dict = json.loads(res.body) self.assertEqual(404, res.status_int)
def test_keypair_import(self): body = { 'keypair': { 'name': 'create_test', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBYIznA' 'x9D7118Q1VKGpXy2HDiKyUTM8XcUuhQpo0srqb9rboUp4' 'a9NmCwpWpeElDLuva707GOUnfaBAvHBwsRXyxHJjRaI6Y' 'Qj2oLJwqvaSaWUbyT1vtryRqy6J3TecN0WINY71f4uymi' 'MZP0wby4bKBcYnac8KiCIlvkEl0ETjkOGUq8OyWRmn7lj' 'j5SESEUdBP0JnuTFKddWTU/wD6wydeJaUhBTqOlHn0kX1' 'GyqoNTE1UEhcM5ZRWgfUZfTjVyDF2kGj3vJLCJtJ8LoGc' 'j7YaN4uPg1rBle+izwE/tLonRrds+cev8p6krSSrxWOwB' 'bHkXa6OciiJDvkRzJXzf', }, } req = webob.Request.blank('/v2/fake/os-keypairs') req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['Content-Type'] = 'application/json' res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) # FIXME(ja): sholud we check that public_key was sent to create? res_dict = jsonutils.loads(res.body) self.assertTrue(len(res_dict['keypair']['fingerprint']) > 0) self.assertFalse('private_key' in res_dict['keypair'])
def test_keypair_import_quota_limit(self): def fake_quotas_count(self, context, resource, *args, **kwargs): return 100 self.stubs.Set(QUOTAS, "count", fake_quotas_count) body = { 'keypair': { 'name': 'create_test', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBYIznA' 'x9D7118Q1VKGpXy2HDiKyUTM8XcUuhQpo0srqb9rboUp4' 'a9NmCwpWpeElDLuva707GOUnfaBAvHBwsRXyxHJjRaI6Y' 'Qj2oLJwqvaSaWUbyT1vtryRqy6J3TecN0WINY71f4uymi' 'MZP0wby4bKBcYnac8KiCIlvkEl0ETjkOGUq8OyWRmn7lj' 'j5SESEUdBP0JnuTFKddWTU/wD6wydeJaUhBTqOlHn0kX1' 'GyqoNTE1UEhcM5ZRWgfUZfTjVyDF2kGj3vJLCJtJ8LoGc' 'j7YaN4uPg1rBle+izwE/tLonRrds+cev8p6krSSrxWOwB' 'bHkXa6OciiJDvkRzJXzf', }, } req = webob.Request.blank('/v2/fake/os-keypairs') req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['Content-Type'] = 'application/json' res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 413)
def test_create_public_flavor_should_not_create_flavor_access(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True } } ctxt = context.RequestContext('fake', 'fake', is_admin=True, auth_token=True) self.app = fakes.wsgi_app(init_only=('flavors',), fake_auth_context=ctxt) self.mox.StubOutWithMock(flavors, "add_flavor_access") self.mox.ReplayAll() url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key])
def test_verify_index(self): req = webob.Request.blank( '/v2/faketenant_0/os-simple-tenant-usage?start=%s&end=%s' % (START.isoformat(), STOP.isoformat())) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app( fake_auth_context=self.admin_context)) self.assertEqual(res.status_int, 200) res_dict = json.loads(res.body) usages = res_dict['tenant_usages'] from nova import log as logging logging.warn(usages) for i in xrange(TENANTS): self.assertEqual(int(usages[i]['total_hours']), SERVERS * HOURS) self.assertEqual(int(usages[i]['total_local_gb_usage']), SERVERS * (ROOT_GB + EPHEMERAL_GB) * HOURS) self.assertEqual(int(usages[i]['total_memory_mb_usage']), SERVERS * MEMORY_MB * HOURS) self.assertEqual(int(usages[i]['total_vcpus_usage']), SERVERS * VCPUS * HOURS) self.assertFalse(usages[i].get('server_usages'))
def test_create_private_flavor_should_create_flavor_access(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": False } } ctxt = context.RequestContext('fake', 'fake', is_admin=True, auth_token=True) self.app = fakes.wsgi_app(init_only=('flavors',), fake_auth_context=ctxt) url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key]) flavor_access_body = self.flavor_access_controller.index( FakeRequest(), body["flavor"]["id"]) expected_flavor_access_body = { "tenant_id": "%s" % ctxt.project_id, "flavor_id": "%s" % body["flavor"]["id"] } self.assertTrue(expected_flavor_access_body in flavor_access_body["flavor_access"])
def setUp(self): super(PrivateFlavorManageTest, self).setUp() # self.stubs.Set(flavors, # "get_flavor_by_flavor_id", # fake_get_flavor_by_flavor_id) # self.stubs.Set(flavors, "destroy", fake_destroy) # self.stubs.Set(flavors, "create", fake_create) self.controller = flavor_manage.FlavorManageController() self.flavor_access_controller = flavor_access.FlavorAccessController() self.app = fakes.wsgi_app(init_only=('flavors',)) self.base_request_dict = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "ephemeral": 1, "id": unicode('1234'), "swap": 512, "rxtx_factor": 1, "flavor-access:is_public": False } }
def test_vsa_volume_create(self): self.stubs.Set(volume.api.API, "create", fakes.stub_volume_create) vol = {"size": 100, "displayName": "VSA Volume Test Name", "displayDescription": "VSA Volume Test Desc"} body = {self.test_obj: vol} req = webob.Request.blank('/v2/fake/zadr-vsa/123/%s' % self.test_objs) req.method = 'POST' req.body = json.dumps(body) req.headers['content-type'] = 'application/json' resp = req.get_response(fakes.wsgi_app()) if self.test_obj == "volume": self.assertEqual(resp.status_int, 200) resp_dict = json.loads(resp.body) self.assertTrue(self.test_obj in resp_dict) self.assertEqual(resp_dict[self.test_obj]['size'], vol['size']) self.assertEqual(resp_dict[self.test_obj]['displayName'], vol['displayName']) self.assertEqual(resp_dict[self.test_obj]['displayDescription'], vol['displayDescription']) else: self.assertEqual(resp.status_int, 400)
def test_create_root_volume(self): body = dict(server=dict( name='test_server', imageRef=IMAGE_UUID, flavorRef=2, min_count=1, max_count=1, block_device_mapping=[dict( volume_id=1, device_name='/dev/vda', virtual='root', delete_on_termination=False, )] )) global _block_device_mapping_seen _block_device_mapping_seen = None req = webob.Request.blank('/v2/fake/os-volumes_boot') req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['content-type'] = 'application/json' res = req.get_response(fakes.wsgi_app( init_only=('os-volumes_boot', 'servers'))) self.assertEqual(res.status_int, 202) server = jsonutils.loads(res.body)['server'] self.assertEqual(FAKE_UUID, server['id']) self.assertEqual(CONF.password_length, len(server['adminPass'])) self.assertEqual(len(_block_device_mapping_seen), 1) self.assertEqual(_block_device_mapping_seen[0]['volume_id'], 1) self.assertEqual(_block_device_mapping_seen[0]['device_name'], '/dev/vda')
def test_detail(self): expected = [ { 'id': '1', 'name': 'test', 'ram': 512, 'vcpus': 1, 'disk': 1, 'OS-FLV-EXT-DATA:ephemeral': 1, }, { 'id': '2', 'name': 'test', 'ram': 512, 'vcpus': 1, 'disk': 1, 'OS-FLV-EXT-DATA:ephemeral': 1, }, ] url = '/v2/fake/flavors/detail' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' res = req.get_response(fakes.wsgi_app(init_only=('flavors',))) body = jsonutils.loads(res.body) for i, flavor in enumerate(body['flavors']): self._verify_flavor_response(flavor, expected[i])
def test_evacuate_instance_with_target(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) uuid = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'false', 'adminPass': '******' } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None self.stubs.Set(compute_api.API, 'update', fake_update) resp = req.get_response(app) self.assertEqual(resp.status_int, 200) resp_json = jsonutils.loads(resp.body) self.assertEqual("MyNewPass", resp_json['adminPass'])
def test_bad_user_bad_key(self): req = webob.Request.blank('/v2/') req.headers['X-Auth-User'] = '******' req.headers['X-Auth-Key'] = 'unknown_user_key' req.headers['X-Auth-Project-Id'] = 'user_project' result = req.get_response(fakes.wsgi_app(fake_auth=False)) self.assertEqual(result.status, '401 Unauthorized')
def test_too_many_metadata_items_on_put(self): req = webob.Request.blank('/v1.1/images/3/metadata/blah') req.method = 'PUT' req.body = '{"meta": {"blah": "blah"}}' req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app()) self.assertEqual(413, res.status_int)
def test_user_create(self): secret = utils.generate_password() body = dict(user=dict(name='test_guy', access='acc3', secret=secret, admin=True)) req = webob.Request.blank('/v1.0/users') req.headers["Content-Type"] = "application/json" req.method = 'POST' req.body = json.dumps(body) res = req.get_response(fakes.wsgi_app()) res_dict = json.loads(res.body) self.assertEqual(res.status_int, 200) # NOTE(justinsb): This is a questionable assertion in general # fake sets id=name, but others might not... self.assertEqual(res_dict['user']['id'], 'test_guy') self.assertEqual(res_dict['user']['name'], 'test_guy') self.assertEqual(res_dict['user']['access'], 'acc3') self.assertEqual(res_dict['user']['secret'], secret) self.assertEqual(res_dict['user']['admin'], True) self.assertTrue('test_guy' in [u.id for u in fakes.FakeAuthManager.auth_data]) self.assertEqual(len(fakes.FakeAuthManager.auth_data), 3)
def test_snapshot_create_force(self): global _last_param _last_param = {} snapshot = {"volume_id": 12, "force": True, "display_name": "Snapshot Test Name", "display_description": "Snapshot Test Desc"} body = dict(snapshot=snapshot) req = webob.Request.blank('/v2/fake/os-snapshots') req.method = 'POST' req.body = json.dumps(body) req.headers['content-type'] = 'application/json' resp = req.get_response(fakes.wsgi_app()) LOG.debug(_("test_snapshot_create_force: param=%s"), _last_param) self.assertEqual(resp.status_int, 200) # Compare if parameters were correctly passed to stub self.assertEqual(_last_param['display_name'], "Snapshot Test Name") self.assertEqual(_last_param['display_description'], "Snapshot Test Desc") resp_dict = json.loads(resp.body) LOG.debug(_("test_snapshot_create_force: resp_dict=%s"), resp_dict) self.assertTrue('snapshot' in resp_dict) self.assertEqual(resp_dict['snapshot']['displayName'], snapshot['display_name']) self.assertEqual(resp_dict['snapshot']['displayDescription'], snapshot['display_description'])
def test_create_public_default(self): flavor = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": 1234, "swap": 512, "rxtx_factor": 1, } } expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": 1234, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } self.stubs.Set(instance_types, "create", fake_create) url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(flavor) res = req.get_response(fakes.wsgi_app()) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEquals(body["flavor"][key], expected["flavor"][key])
def test_get_version_list_xml(self): req = webob.Request.blank('/') req.accept = "application/xml" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) self.assertEqual(res.content_type, "application/xml") root = etree.XML(res.body) print res.body xmlutil.validate_schema(root, 'versions') self.assertTrue(root.xpath('/ns:versions', namespaces=NS)) versions = root.xpath('ns:version', namespaces=NS) self.assertEqual(len(versions), 1) for i, v in enumerate(['v2.0']): version = versions[i] expected = VERSIONS[v] for key in ['id', 'status', 'updated']: self.assertEqual(version.get(key), expected[key]) (link,) = version.xpath('atom:link', namespaces=NS) self.assertTrue(common.compare_links(link, [{'rel': 'self', 'href': 'http://localhost/%s/' % v}]))
def test_associate_floating_ip_to_instance_no_project_id(self): def fake_fixed_ip_get_by_address(ctx, address, session=None): return { 'address': address, 'network': { 'multi_host': None, 'host': 'fake' } } self.stubs.Set(db.api, "fixed_ip_get_by_address", fake_fixed_ip_get_by_address) db.floating_ip_update(self.context, self.address, { 'project_id': None, 'fixed_ip_id': 1 }) body = dict(addFloatingIp=dict(address=self.address)) req = webob.Request.blank('/v1.1/123/servers/test_inst/action') req.method = "POST" req.body = json.dumps(body) req.headers["content-type"] = "application/json" resp = req.get_response(fakes.wsgi_app()) self.assertEqual(resp.status_int, 400)
def test_floating_ips_list(self): req = webob.Request.blank('/v1.1/os-floating-ips') res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) res_dict = json.loads(res.body) response = { 'floating_ips': [{ 'floating_ip': { 'instance_id': 11, 'ip': '10.10.10.10', 'fixed_ip': '10.0.0.1', 'id': 1 } }, { 'floating_ip': { 'instance_id': None, 'ip': '10.10.10.11', 'fixed_ip': None, 'id': 2 } }] } self.assertEqual(res_dict, response)
def test_verify_show_cant_view_other_tenant(self): req = webob.Request.blank( '/v2/faketenant_1/os-simple-tenant-usage/' 'faketenant_0?start=%s&end=%s' % (START.isoformat(), STOP.isoformat())) req.method = "GET" req.headers["content-type"] = "application/json" rules = { "compute_extension:simple_tenant_usage:show": common_policy.parse_rule([ ["role:admin"], ["project_id:%(project_id)s"] ]) } common_policy.set_rules(common_policy.Rules(rules)) try: res = req.get_response(fakes.wsgi_app( fake_auth_context=self.alt_user_context, init_only=('os-simple-tenant-usage',))) self.assertEqual(res.status_int, 403) finally: policy.reset()
def test_get_version_list_xml(self): req = webob.Request.blank('/') req.accept = "application/xml" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) self.assertEqual(res.content_type, "application/xml") expected = """<versions> <version id="v1.1" status="CURRENT"> <links> <link href="http://localhost/v1.1" rel="self"/> </links> </version> <version id="v1.0" status="DEPRECATED"> <links> <link href="http://localhost/v1.0" rel="self"/> </links> </version> </versions>""".replace(" ", "").replace("\n", "") actual = res.body.replace(" ", "").replace("\n", "") self.assertEqual(expected, actual)
def test_create(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": 1234, "swap": 512, "rxtx_factor": 1, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = json.dumps(expected) res = req.get_response(fakes.wsgi_app()) body = json.loads(res.body) for key in expected["flavor"]: self.assertEquals(body["flavor"][key], expected["flavor"][key])
def test_associate_not_allocated_floating_ip_to_instance(self): def fake_associate_floating_ip(self, context, instance, floating_address, fixed_address, affect_auto_assigned=False): raise exception.FloatingIpNotFoundForAddress( address=floating_address) self.stubs.Set(network.api.API, "associate_floating_ip", fake_associate_floating_ip) floating_ip = '10.10.10.11' body = dict(addFloatingIp=dict(address=floating_ip)) req = webob.Request.blank('/v2/fake/servers/test_inst/action') req.method = "POST" req.body = jsonutils.dumps(body) req.headers["content-type"] = "application/json" resp = req.get_response(fakes.wsgi_app(init_only=('servers', ))) res_dict = jsonutils.loads(resp.body) self.assertEqual(resp.status_int, 404) self.assertEqual(res_dict['itemNotFound']['message'], "floating ip not found")
def test_evacuate_shared_and_pass(self): ctxt = self._get_admin_context() app = fakes.wsgi_app(fake_auth_context=ctxt) uuid1 = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid1) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my-host', 'onSharedStorage': 'True', 'adminPass': '******' } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None self.stubs.Set(compute_api.API, 'update', fake_update) res = req.get_response(app) self.assertEqual(res.status_int, 400)
def _test_verify_index(self, start, stop): req = webob.Request.blank( '/v2/faketenant_0/os-simple-tenant-usage?start=%s&end=%s' % (start.isoformat(), stop.isoformat())) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response( fakes.wsgi_app(fake_auth_context=self.admin_context, init_only=('os-simple-tenant-usage', ))) self.assertEqual(res.status_int, 200) res_dict = jsonutils.loads(res.body) usages = res_dict['tenant_usages'] for i in xrange(TENANTS): self.assertEqual(int(usages[i]['total_hours']), SERVERS * HOURS) self.assertEqual(int(usages[i]['total_local_gb_usage']), SERVERS * (ROOT_GB + EPHEMERAL_GB) * HOURS) self.assertEqual(int(usages[i]['total_memory_mb_usage']), SERVERS * MEMORY_MB * HOURS) self.assertEqual(int(usages[i]['total_vcpus_usage']), SERVERS * VCPUS * HOURS) self.assertFalse(usages[i].get('server_usages'))
def test_get_flavor_by_id_v1_1(self): req = webob.Request.blank('/v1.1/fake/flavors/12') req.environ['api.version'] = '1.1' res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) flavor = json.loads(res.body) expected = { "flavor": { "id": "12", "name": "flavor 12", "ram": "256", "disk": "10", "rxtx_cap": "", "rxtx_quota": "", "swap": "", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/v1.1/fake/flavors/12", }, { "rel": "bookmark", "href": "http://localhost/fake/flavors/12", }, ], }, } self.assertEqual(flavor, expected)
def test_migrate_live_enabled(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt, init_only=('servers', )) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.body = jsonutils.dumps({ 'os-migrateLive': { 'host': 'hostname', 'block_migration': False, 'disk_over_commit': False, } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None def fake_scheduler_api_live_migration(self, context, dest, block_migration=False, disk_over_commit=False, instance=None, instance_id=None, topic=None): return None self.stubs.Set(compute_api.API, 'update', fake_update) self.stubs.Set(scheduler_rpcapi.SchedulerAPI, 'live_migration', fake_scheduler_api_live_migration) res = req.get_response(app) self.assertEqual(res.status_int, 202)
def test_create_private_flavor_should_not_grant_flavor_access(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": False } } ctxt = context.RequestContext('fake', 'fake', is_admin=True, auth_token=True) self.app = fakes.wsgi_app(init_only=('flavors', ), fake_auth_context=ctxt) url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key]) flavor_access_body = self.flavor_access_controller.index( FakeRequest(), body["flavor"]["id"]) expected_flavor_access_body = { "tenant_id": "%s" % ctxt.project_id, "flavor_id": "%s" % body["flavor"]["id"] } self.assertNotIn(expected_flavor_access_body, flavor_access_body["flavor_access"])
def test_evacuate_with_active_service(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.content_type = 'application/json' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my-host', 'onSharedStorage': 'false', 'adminPass': '******' } }) def fake_evacuate(*args, **kwargs): raise exception.ComputeServiceInUse("Service still in use") self.stubs.Set(compute_api.API, 'evacuate', fake_evacuate) res = req.get_response(app) self.assertEqual(res.status_int, 400)
def test_quotas_defaults(self): uri = '/v1.1/fake/os-quota-sets/fake_tenant/defaults' req = webob.Request.blank(uri) req.method = 'GET' req.headers['Content-Type'] = 'application/json' res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) expected = { 'quota_set': { 'id': 'fake_tenant', 'instances': 10, 'cores': 20, 'ram': 51200, 'volumes': 10, 'gigabytes': 1000, 'floating_ips': 10, 'metadata_items': 128, 'injected_files': 5, 'injected_file_content_bytes': 10240 } } self.assertEqual(json.loads(res.body), expected)
def setUp(self): super(CreateBackupTestsV2, self).setUp() self.controller = admin_actions_v2.AdminActionsController() self.compute_api = self.controller.compute_api self.context = nova.context.RequestContext('fake', 'fake') def _fake_controller(*args, **kwargs): return self.controller self.stubs.Set(admin_actions_v2, 'AdminActionsController', _fake_controller) self.flags( osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions'], osapi_compute_ext_list=['Admin_actions']) self.app = fakes.wsgi_app(init_only=('servers',), fake_auth_context=self.context) self.mox.StubOutWithMock(self.compute_api, 'get') self.mox.StubOutWithMock(common, 'check_img_metadata_properties_quota') self.mox.StubOutWithMock(self.compute_api, 'backup')
def test_get_version_1_1_detail_atom(self): req = webob.Request.blank('/v1.1/') req.accept = "application/atom+xml" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) self.assertEqual("application/atom+xml", res.content_type) expected = """ <feed xmlns="http://www.w3.org/2005/Atom"> <title type="text">About This Version</title> <updated>2011-01-21T11:33:21Z</updated> <id>http://localhost/v1.1/</id> <author> <name>Rackspace</name> <uri>http://www.rackspace.com/</uri> </author> <link href="http://localhost/v1.1/" rel="self"/> <entry> <id>http://localhost/v1.1/</id> <title type="text">Version v1.1</title> <updated>2011-01-21T11:33:21Z</updated> <link href="http://localhost/v1.1/" rel="self"/> <link href="http://docs.rackspacecloud.com/servers/ api/v1.1/cs-devguide-20110125.pdf" rel="describedby" type="application/pdf"/> <link href="http://docs.rackspacecloud.com/servers/ api/v1.1/application.wadl" rel="describedby" type="application/vnd.sun.wadl+xml"/> <content type="text"> Version v1.1 CURRENT (2011-01-21T11:33:21Z) </content> </entry> </feed>""".replace(" ", "").replace("\n", "") actual = res.body.replace(" ", "").replace("\n", "") self.assertEqual(expected, actual)
def test_verify_index(self): req = webob.Request.blank( '/v1.1/faketenant_0/os-simple-tenant-usage?start=%s&end=%s' % (START.isoformat(), STOP.isoformat())) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response( fakes.wsgi_app(fake_auth_context=self.admin_context)) self.assertEqual(res.status_int, 200) res_dict = json.loads(res.body) usages = res_dict['tenant_usages'] from nova import log as logging logging.warn(usages) for i in xrange(TENANTS): self.assertEqual(int(usages[i]['total_hours']), SERVERS * HOURS) self.assertEqual(int(usages[i]['total_local_gb_usage']), SERVERS * LOCAL_GB * HOURS) self.assertEqual(int(usages[i]['total_memory_mb_usage']), SERVERS * MEMORY_MB * HOURS) self.assertEqual(int(usages[i]['total_vcpus_usage']), SERVERS * VCPUS * HOURS) self.assertFalse(usages[i].get('server_usages'))
def test_evacuate_not_shared_pass_generated(self): ctxt = self._get_admin_context() app = fakes.wsgi_app(fake_auth_context=ctxt) uuid1 = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid1) req.method = 'POST' req.body = jsonutils.dumps( {'evacuate': { 'host': 'my-host', 'onSharedStorage': 'False', }}) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None self.stubs.Set(compute_api.API, 'update', fake_update) resp = req.get_response(app) self.assertEqual(resp.status_int, 200) resp_json = jsonutils.loads(resp.body) self.assertEqual(CONF.password_length, len(resp_json['adminPass']))
def test_migrate_live_destination_hypervisor_too_old(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt, init_only=('servers',)) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.body = jsonutils.dumps({ 'os-migrateLive': { 'host': 'hostname', 'block_migration': False, 'disk_over_commit': False, } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None def fake_migrate_server(self, context, instance, scheduler_hint, live, rebuild, flavor, block_migration, disk_over_commit): raise exception.DestinationHypervisorTooOld() self.stubs.Set(compute_api.API, 'update', fake_update) self.stubs.Set(conductor_api.ComputeTaskAPI, 'migrate_server', fake_migrate_server) res = req.get_response(app) self.assertEqual(res.status_int, 400) self.assertIn( unicode(exception.DestinationHypervisorTooOld()), res.body)
def test_get_version_2_detail_atom(self): req = webob.Request.blank('/v2/') req.accept = "application/atom+xml" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) self.assertEqual("application/atom+xml", res.content_type) xmlutil.validate_schema(etree.XML(res.body), 'atom') f = feedparser.parse(res.body) self.assertEqual(f.feed.title, 'About This Version') self.assertEqual(f.feed.updated, '2011-01-21T11:33:21Z') self.assertEqual(f.feed.id, 'http://localhost/v2/') self.assertEqual(f.feed.author, 'Rackspace') self.assertEqual(f.feed.author_detail.href, 'http://www.rackspace.com/') self.assertEqual(f.feed.links[0]['href'], 'http://localhost/v2/') self.assertEqual(f.feed.links[0]['rel'], 'self') self.assertEqual(len(f.entries), 1) entry = f.entries[0] self.assertEqual(entry.id, 'http://localhost/v2/') self.assertEqual(entry.title, 'Version v2.0') self.assertEqual(entry.updated, '2011-01-21T11:33:21Z') self.assertEqual(len(entry.content), 1) self.assertEqual(entry.content[0].value, 'Version v2.0 CURRENT (2011-01-21T11:33:21Z)') self.assertEqual(len(entry.links), 2) self.assertEqual(entry.links[0]['href'], 'http://localhost/v2/') self.assertEqual(entry.links[0]['rel'], 'self') self.assertEqual( entry.links[1], { 'href': EXP_LINKS['v2.0']['html'], 'type': 'text/html', 'rel': 'describedby' })
def test_get_version_2_detail_xml(self): req = webob.Request.blank('/v2/') req.accept = "application/xml" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 200) self.assertEqual(res.content_type, "application/xml") version = etree.XML(res.body) xmlutil.validate_schema(version, 'version') expected = VERSIONS['v2.0'] self.assertTrue(version.xpath('/ns:version', namespaces=NS)) media_types = version.xpath('ns:media-types/ns:media-type', namespaces=NS) self.assertTrue( common.compare_media_types(media_types, expected['media-types'])) for key in ['id', 'status', 'updated']: self.assertEqual(version.get(key), expected[key]) links = version.xpath('atom:link', namespaces=NS) self.assertTrue( common.compare_links(links, [{ 'rel': 'self', 'href': 'http://localhost/v2/' }] + expected['links']))
def test_get_security_group_by_id(self): security_group = {} security_group['name'] = "test" security_group['description'] = "group-description" response = _create_security_group_json(security_group) res_dict = json.loads(response.body) req = webob.Request.blank('/v1.1/fake/os-security-groups/%s' % res_dict['security_group']['id']) req.headers['Content-Type'] = 'application/json' req.method = 'GET' response = req.get_response(fakes.wsgi_app()) res_dict = json.loads(response.body) expected = { 'security_group': { 'id': 2, 'name': "test", 'tenant_id': "fake", 'description': "group-description", 'rules': [] } } self.assertEquals(res_dict, expected)
def test_get_image_v1_1(self): request = webob.Request.blank('/v1.1/images/123') response = request.get_response(fakes.wsgi_app()) actual_image = json.loads(response.body) href = "http://localhost/v1.1/images/123" expected_image = { "image": { "id": 123, "name": "public image", "updated": self.NOW_API_FORMAT, "created": self.NOW_API_FORMAT, "status": "ACTIVE", "links": [{ "rel": "self", "href": href, }, { "rel": "bookmark", "type": "application/json", "href": href, }, { "rel": "bookmark", "type": "application/xml", "href": href, }], }, } self.assertEqual(expected_image, actual_image)
def test_multi_choice_server(self): uuid = str(stdlib_uuid.uuid4()) req = webob.Request.blank('/servers/' + uuid) req.accept = "application/json" res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 300) self.assertEqual(res.content_type, "application/json") expected = { "choices": [ { "id": "v2.0", "status": "CURRENT", "links": [ { "href": "http://localhost/v2/servers/" + uuid, "rel": "self", }, ], "media-types": [ { "base": "application/xml", "type": "application/vnd.openstack.compute+xml" ";version=2" }, { "base": "application/json", "type": "application/vnd.openstack.compute+json" ";version=2" }, ], }, ], } self.assertThat(jsonutils.loads(res.body), matchers.DictMatches(expected))
def test_quotas_update_as_user(self): updated_quota_set = { 'quota_set': { 'instances': 50, 'cores': 50, 'ram': 51200, 'volumes': 10, 'gigabytes': 1000, 'floating_ips': 10, 'metadata_items': 128, 'injected_files': 5, 'injected_file_content_bytes': 10240 } } req = webob.Request.blank('/v1.1/fake/os-quota-sets/update_me') req.method = 'PUT' req.body = json.dumps(updated_quota_set) req.headers['Content-Type'] = 'application/json' res = req.get_response( fakes.wsgi_app(fake_auth_context=self.user_context)) self.assertEqual(res.status_int, 403)
def _make_request(self, url): req = fakes.HTTPRequest.blank(url) req.accept = self.content_type res = req.get_response(fakes.wsgi_app(init_only=('servers', ))) return res
def _setup_app(self): self.app = fakes.wsgi_app(init_only=('flavors', ))
def _get_app(self): return fakes.wsgi_app(init_only=('servers', ))
def _get_wsgi_instance(self): return fakes.wsgi_app()