def test_ambiguous_endpoints(self): cs = client.Client("username", "password", "project_id", "auth_url/v2.0", service_type='compute') resp = { "access": { "token": { "expires": "12345", "id": "FAKE_ID", }, "serviceCatalog": [ { "adminURL": "http://*****:*****@mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.AmbiguousEndpoints, cs.client.authenticate) test_auth_call()
def setUp(self): super(KeystoneClientTest, self).setUp() domain_scoped_fake_resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(client_fixtures.DOMAIN_SCOPED_TOKEN), "headers": client_fixtures.AUTH_RESPONSE_HEADERS }) self.domain_scoped_mock_req = mock.Mock( return_value=domain_scoped_fake_resp) project_scoped_fake_resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(client_fixtures.PROJECT_SCOPED_TOKEN), "headers": client_fixtures.AUTH_RESPONSE_HEADERS }) self.project_scoped_mock_req = mock.Mock( return_value=project_scoped_fake_resp) unscoped_fake_resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(client_fixtures.UNSCOPED_TOKEN), "headers": client_fixtures.AUTH_RESPONSE_HEADERS }) self.unscoped_mock_req = mock.Mock(return_value=unscoped_fake_resp) trust_fake_resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(client_fixtures.TRUST_TOKEN), "headers": client_fixtures.AUTH_RESPONSE_HEADERS }) self.trust_mock_req = mock.Mock(return_value=trust_fake_resp)
def test_authenticate_failure(self): cs = client.Client("username", "password", "project_id", "auth_url") auth_response = utils.TestResponse({'status_code': 401}) mock_request = mock.Mock(return_value=(auth_response)) @mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.Unauthorized, cs.client.authenticate) test_auth_call()
def test_get_error(self): cl = get_authed_client() fake_err_response = utils.TestResponse({ "status_code": 400, "text": 'Some evil plaintext string', }) err_MOCK_REQUEST = mock.Mock(return_value=(fake_err_response)) with mock.patch.object(requests, "request", err_MOCK_REQUEST): self.assertRaises(exceptions.BadRequest, cl.get, '/hi')
def test_delete(self): resp = utils.TestResponse({"status_code": 204, "text": ""}) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('DELETE', urlparse.urljoin(self.TEST_URL, 'v2.0/tokens/1'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() self.client.tokens.delete(1)
def test_authenticate_success_expired(self): # Build an expired token self.TEST_RESPONSE_DICT['access']['token']['expires'] = \ (timeutils.utcnow() - timedelta(1)).isoformat() resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_RESPONSE_DICT), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY) requests.request('POST', self.TEST_URL + "/tokens", **kwargs).AndReturn((resp)) self.mox.ReplayAll() cs = client.Client(tenant_id=self.TEST_TENANT_ID, auth_url=self.TEST_URL, username=self.TEST_USER, password=self.TEST_TOKEN) self.assertEqual( cs.management_url, self.TEST_RESPONSE_DICT["access"] ["serviceCatalog"][3]['endpoints'][0]["adminURL"]) # Build a new response self.mox.ResetAll() TEST_TOKEN = "abcdef" self.TEST_RESPONSE_DICT['access']['token']['expires'] = \ "2999-01-01T00:00:10Z" self.TEST_RESPONSE_DICT['access']['token']['id'] = TEST_TOKEN resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_RESPONSE_DICT), }) requests.request('POST', self.TEST_URL + "/tokens", **kwargs).AndReturn((resp)) self.mox.ReplayAll() self.assertEqual(cs.auth_token, TEST_TOKEN)
def test_list(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_USERS), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', urlparse.urljoin(self.TEST_URL, 'v2.0/users'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() user_list = self.client.users.list() [self.assertTrue(isinstance(u, users.User)) for u in user_list]
def test_list_marker(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_TENANTS), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request( 'GET', urlparse.urljoin(self.TEST_URL, 'v2.0/tenants?marker=1'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() tenant_list = self.client.tenants.list(marker=1) [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list]
def test_roles_for_user(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_ROLES), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request( 'GET', urlparse.urljoin(self.TEST_URL, 'v2.0/users/foo/roles'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() role_list = self.client.roles.roles_for_user('foo') [self.assertTrue(isinstance(r, roles.Role)) for r in role_list]
def test_remove_user_role_tenant(self): resp = utils.TestResponse({ "status_code": 204, "text": '', }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('DELETE', urlparse.urljoin(self.TEST_URL, 'v2.0/tenants/4/users/foo/roles/OS-KSADM/barrr'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() self.client.roles.remove_user_role('foo', 'barrr', '4')
def test_authenticate_failure(self): cs = client.Client("username", "password", "project_id", "auth_url/v2.0") resp = {"unauthorized": {"message": "Unauthorized", "code": "401"}} auth_response = utils.TestResponse({ "status_code": 401, "text": json.dumps(resp), }) mock_request = mock.Mock(return_value=(auth_response)) @mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.Unauthorized, cs.client.authenticate) test_auth_call()
def test_update(self): req_body = { "tenant": { "id": 4, "name": "tenantX", "description": "I changed you!", "enabled": False, "extravalue01": "metadataChanged", #"extraname": "dontoverwrite!", }, } resp_body = { "tenant": { "name": "tenantX", "enabled": False, "id": 4, "description": "I changed you!", "extravalue01": "metadataChanged", }, } resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(resp_body), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_POST_HEADERS kwargs['data'] = json.dumps(req_body) requests.request('POST', urlparse.urljoin(self.TEST_URL, 'v2.0/tenants/4'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() tenant = self.client.tenants.update( req_body['tenant']['id'], req_body['tenant']['name'], req_body['tenant']['description'], req_body['tenant']['enabled'], extravalue01=req_body['tenant']['extravalue01'], name="dont overwrite priors") self.assertTrue(isinstance(tenant, tenants.Tenant)) self.assertEqual(tenant.id, 4) self.assertEqual(tenant.name, "tenantX") self.assertEqual(tenant.description, "I changed you!") self.assertFalse(tenant.enabled) self.assertEqual(tenant.extravalue01, "metadataChanged")
def test_list(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_SERVICES), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', urlparse.urljoin(self.TEST_URL, 'v2.0/OS-KSADM/services'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() service_list = self.client.services.list() [self.assertTrue(isinstance(r, services.Service)) for r in service_list]
def test_list(self): user_id = 'usr' tenant_id = 'tnt' resp_body = { "credentials": { "values": [ { "access": "access", "secret": "secret", "tenant_id": tenant_id, "created": "12/12/12", "enabled": True, }, { "access": "another", "secret": "key", "tenant_id": tenant_id, "created": "12/12/31", "enabled": True, } ] } } resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(resp_body), }) url = urlparse.urljoin(self.TEST_URL, 'v2.0/users/%s/credentials/OS-EC2' % user_id) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', url, **kwargs).AndReturn((resp)) self.mox.ReplayAll() creds = self.client.ec2.list(user_id) self.assertTrue(len(creds), 2) cred = creds[0] self.assertTrue(isinstance(cred, ec2.EC2)) self.assertEqual(cred.tenant_id, tenant_id) self.assertEqual(cred.enabled, True) self.assertEqual(cred.access, 'access') self.assertEqual(cred.secret, 'secret')
def test_list(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_ENDPOINTS), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', urlparse.urljoin(self.TEST_URL, 'v2.0/endpoints'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() endpoint_list = self.client.endpoints.list() [ self.assertTrue(isinstance(r, endpoints.Endpoint)) for r in endpoint_list ]
def test_get(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps({ 'tenant': self.TEST_TENANTS['tenants']['values'][2], }), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', urlparse.urljoin(self.TEST_URL, 'v2.0/tenants/1'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() t = self.client.tenants.get(1) self.assertTrue(isinstance(t, tenants.Tenant)) self.assertEqual(t.id, 1) self.assertEqual(t.name, 'admin')
def test_delete(self): user_id = 'usr' access = 'access' resp = utils.TestResponse({ "status_code": 204, "text": "", }) url = urlparse.urljoin(self.TEST_URL, 'v2.0/users/%s/credentials/OS-EC2/%s' % (user_id, access)) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('DELETE', url, **kwargs).AndReturn((resp)) self.mox.ReplayAll() self.client.ec2.delete(user_id, access)
def test_get_version_local(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_RESPONSE_DICT), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', "http://localhost:35357", **kwargs).AndReturn( (resp)) self.mox.ReplayAll() cs = client.Client() versions = cs.discover() self.assertIsInstance(versions, dict) self.assertIn('message', versions) self.assertIn('v2.0', versions) self.assertEquals( versions['v2.0']['url'], self.TEST_RESPONSE_DICT['versions'] ['values'][0]['links'][0]['href'])
def test_update_own_password(self): req_body = {'user': {'password': '******', 'original_password': '******'}} resp_body = {'access': {}} resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(resp_body) }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_POST_HEADERS kwargs['data'] = json.dumps(req_body) requests.request( 'PATCH', urlparse.urljoin(self.TEST_URL, 'v2.0/OS-KSCRUD/users/123'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() self.client.user_id = '123' self.client.users.update_own_password('DCBA', 'ABCD')
def test_get(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps({ 'role': self.TEST_ROLES['roles']['values'][0], }), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', urlparse.urljoin(self.TEST_URL, 'v2.0/OS-KSADM/roles/1'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() role = self.client.roles.get(1) self.assertTrue(isinstance(role, roles.Role)) self.assertEqual(role.id, 1) self.assertEqual(role.name, 'admin')
def test_get(self): test_services = self.TEST_SERVICES['OS-KSADM:services']['values'][0] resp = utils.TestResponse({ "status_code": 200, "text": json.dumps({'OS-KSADM:service': test_services}), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', urlparse.urljoin(self.TEST_URL, 'v2.0/OS-KSADM/services/1'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() service = self.client.services.get(1) self.assertTrue(isinstance(service, services.Service)) self.assertEqual(service.id, 1) self.assertEqual(service.name, 'nova') self.assertEqual(service.type, 'compute')
def test_create(self): req_body = { "user": { "name": "gabriel", "password": "******", "tenantId": 2, "email": "*****@*****.**", "enabled": True, } } resp_body = { "user": { "name": "gabriel", "enabled": True, "tenantId": 2, "id": 3, "password": "******", "email": "*****@*****.**", } } resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(resp_body), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_POST_HEADERS kwargs['data'] = json.dumps(req_body) requests.request('POST', urlparse.urljoin(self.TEST_URL, 'v2.0/users'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() user = self.client.users.create(req_body['user']['name'], req_body['user']['password'], req_body['user']['email'], tenant_id=req_body['user']['tenantId'], enabled=req_body['user']['enabled']) self.assertTrue(isinstance(user, users.User)) self.assertEqual(user.id, 3) self.assertEqual(user.name, "gabriel") self.assertEqual(user.email, "*****@*****.**")
def test_create(self): req_body = { "endpoint": { "region": "RegionOne", "publicurl": "http://host-3:8774/v1.1/$(tenant_id)s", "internalurl": "http://host-3:8774/v1.1/$(tenant_id)s", "adminurl": "http://host-3:8774/v1.1/$(tenant_id)s", "service_id": "e044e21", } } resp_body = { "endpoint": { "adminurl": "http://host-3:8774/v1.1/$(tenant_id)s", "region": "RegionOne", "id": "1fd485b2ffd54f409a5ecd42cba11401", "internalurl": "http://host-3:8774/v1.1/$(tenant_id)s", "publicurl": "http://host-3:8774/v1.1/$(tenant_id)s", } } resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(resp_body), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_POST_HEADERS kwargs['data'] = json.dumps(req_body) requests.request('POST', urlparse.urljoin(self.TEST_URL, 'v2.0/endpoints'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() endpoint = self.client.endpoints.create( region=req_body['endpoint']['region'], publicurl=req_body['endpoint']['publicurl'], adminurl=req_body['endpoint']['adminurl'], internalurl=req_body['endpoint']['internalurl'], service_id=req_body['endpoint']['service_id']) self.assertTrue(isinstance(endpoint, endpoints.Endpoint))
def test_get(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps({ 'user': self.TEST_USERS['users']['values'][0], }) }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS requests.request('GET', urlparse.urljoin(self.TEST_URL, 'v2.0/users/1'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() u = self.client.users.get(1) self.assertTrue(isinstance(u, users.User)) self.assertEqual(u.id, 1) self.assertEqual(u.name, 'admin')
def test_authenticate_success_password_unscoped(self): del self.TEST_RESPONSE_DICT['access']['serviceCatalog'] del self.TEST_REQUEST_BODY['auth']['tenantId'] resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_RESPONSE_DICT), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY) requests.request('POST', self.TEST_URL + "/tokens", **kwargs).AndReturn((resp)) self.mox.ReplayAll() cs = client.Client(username=self.TEST_USER, password=self.TEST_TOKEN, auth_url=self.TEST_URL) self.assertEqual(cs.auth_token, self.TEST_RESPONSE_DICT["access"]["token"]["id"]) self.assertFalse('serviceCatalog' in cs.service_catalog.catalog)
def test_update_empty_description(self): req_body = { "tenant": { "id": 4, "name": "tenantX", "description": "", "enabled": False, }, } resp_body = { "tenant": { "name": "tenantX", "enabled": False, "id": 4, "description": "", }, } resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(resp_body), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_POST_HEADERS kwargs['data'] = json.dumps(req_body) requests.request('POST', urlparse.urljoin(self.TEST_URL, 'v2.0/tenants/4'), **kwargs).AndReturn((resp)) self.mox.ReplayAll() tenant = self.client.tenants.update(req_body['tenant']['id'], req_body['tenant']['name'], req_body['tenant']['description'], req_body['tenant']['enabled']) self.assertTrue(isinstance(tenant, tenants.Tenant)) self.assertEqual(tenant.id, 4) self.assertEqual(tenant.name, "tenantX") self.assertEqual(tenant.description, "") self.assertFalse(tenant.enabled)
def test_auth_redirect(self): correct_response = json.dumps(self.TEST_RESPONSE_DICT) dict_responses = [ { "headers": { 'location': self.TEST_ADMIN_URL + "/tokens", }, "status_code": 305, "text": "Use proxy", }, { "headers": {}, "status_code": 200, "text": correct_response, }, ] responses = [(utils.TestResponse(resp)) for resp in dict_responses] kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY) requests.request('POST', self.TEST_URL + "/tokens", **kwargs).AndReturn(responses[0]) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY) requests.request('POST', self.TEST_ADMIN_URL + "/tokens", **kwargs).AndReturn(responses[1]) self.mox.ReplayAll() cs = client.Client(username=self.TEST_USER, password=self.TEST_TOKEN, tenant_id=self.TEST_TENANT_ID, auth_url=self.TEST_URL) self.assertEqual( cs.management_url, self.TEST_RESPONSE_DICT["access"] ["serviceCatalog"][3]['endpoints'][0]["adminURL"]) self.assertEqual(cs.auth_token, self.TEST_RESPONSE_DICT["access"]["token"]["id"])
def test_authenticate_success_password_scoped(self): resp = utils.TestResponse({ "status_code": 200, "text": json.dumps(self.TEST_RESPONSE_DICT), }) kwargs = copy.copy(self.TEST_REQUEST_BASE) kwargs['headers'] = self.TEST_REQUEST_HEADERS kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY) requests.request('POST', self.TEST_URL + "/tokens", **kwargs).AndReturn((resp)) self.mox.ReplayAll() cs = client.Client(username=self.TEST_USER, password=self.TEST_TOKEN, tenant_id=self.TEST_TENANT_ID, auth_url=self.TEST_URL) self.assertEqual( cs.management_url, self.TEST_RESPONSE_DICT["access"] ["serviceCatalog"][3]['endpoints'][0]["adminURL"]) self.assertEqual(cs.auth_token, self.TEST_RESPONSE_DICT["access"]["token"]["id"])
def test_get_error_with_json_resp(self): cl = get_authed_client() err_response = { "error": { "code": 400, "title": "Error title", "message": "Error message string" } } fake_err_response = utils.TestResponse({ "status_code": 400, "text": json.dumps(err_response) }) err_MOCK_REQUEST = mock.Mock(return_value=(fake_err_response)) with mock.patch.object(requests, "request", err_MOCK_REQUEST): exc_raised = False try: cl.get('/hi') except exceptions.BadRequest as exc: exc_raised = True self.assertEqual(exc.message, "Error message string") self.assertTrue(exc_raised, 'Exception not raised.')
def _cs_request(self, url, method, **kwargs): # Check that certain things are called correctly if method in ['GET', 'DELETE']: assert 'body' not in kwargs elif method == 'PUT': kwargs.setdefault('body', None) # Call the method args = urlparse.parse_qsl(urlparse.urlparse(url)[4]) kwargs.update(args) munged_url = url.rsplit('?', 1)[0] munged_url = munged_url.strip('/').replace('/', '_').replace('.', '_') munged_url = munged_url.replace('-', '_') callback = "%s_%s" % (method.lower(), munged_url) if not hasattr(self, callback): raise AssertionError('Called unknown API method: %s %s, ' 'expected fakes method name: %s' % (method, url, callback)) # Note the call self.callstack.append((method, url, kwargs.get('body', None))) if not hasattr(self, callback): raise AssertionError('Called unknown API method: %s %s, ' 'expected fakes method name: %s' % (method, url, callback)) # Note the call self.callstack.append((method, url, kwargs.get('body', None))) status, body = getattr(self, callback)(**kwargs) r = utils.TestResponse({ "status_code": status, "text": body}) return r, body