desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Workaround for a bug in eventlet.
This currently affects RHEL6.1, but the fix can safely be
applied to all RHEL and Fedora distributions.
This can be removed when the fix is applied upstream.
Nova: https://bugs.launchpad.net/nova/+bug/884915
Upstream: https://bitbucket.org/which_linden/eventlet/issue/89'
| def post_process(self):
| if (not self.check_pkg('patch')):
self.yum_install('patch')
self.apply_patch(os.path.join(self.venv, 'lib', self.py_version, 'site-packages', 'eventlet/green/subprocess.py'), 'contrib/redhat-eventlet.patch')
|
'Due to lack of endpoint CRUD'
| def test_policy_crud(self):
| raise nose.exc.SkipTest('N/A')
|
'Populates a ref with attributes common to all API entities.'
| def new_ref(self):
| return {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'enabled': True}
|
'Applicable only to JSON.'
| def _get_token_id(self, r):
| return r.body['access']['token']['id']
|
'Setup for Identity Protection Test Cases.
As well as the usual housekeeping, create a set of domains,
users, roles and projects for the subsequent tests:
- Three domains: A,B & C. C is disabled.
- DomainA has user1, DomainB has user2 and user3
- DomainA has group1 and group2, DomainB has group3
- User1 has a role on ... | def setUp(self):
| super(IdentityTestProtectedCase, self).setUp(load_sample_data=False)
self.domainA = self.new_domain_ref()
domainA_ref = self.identity_api.create_domain(self.domainA['id'], self.domainA)
self.domainB = self.new_domain_ref()
domainB_ref = self.identity_api.create_domain(self.domainB['id'], self.domain... |
'GET /users (unprotected)
Test Plan:
- Update policy so api is unprotected
- Use an un-scoped token to make sure we can get back all
the users independent of domain'
| def test_list_users_unprotected(self):
| self._set_policy({'identity:list_users': []})
r = self.get('/users', auth=self.auth)
id_list = self._get_id_list_from_ref_list(r.body.get('users'))
self.assertIn(self.user1['id'], id_list)
self.assertIn(self.user2['id'], id_list)
self.assertIn(self.user3['id'], id_list)
|
'GET /users?domain_id=mydomain (filtered)
Test Plan:
- Update policy so api is unprotected
- Use an un-scoped token to make sure we can filter the
users by domainB, getting back the 2 users in that domain'
| def test_list_users_filtered_by_domain(self):
| self._set_policy({'identity:list_users': []})
url_by_name = ('/users?domain_id=%s' % self.domainB['id'])
r = self.get(url_by_name, auth=self.auth)
id_list = self._get_id_list_from_ref_list(r.body.get('users'))
self.assertIn(self.user2['id'], id_list)
self.assertIn(self.user3['id'], id_list)
|
'GET /users/{id} (match payload)
Test Plan:
- Update policy to protect api by user_id
- List users with user_id of user1 as filter, to check that
this will correctly match user_id in the flattened
payload'
| def test_get_user_protected_match_id(self):
| new_policy = {'identity:get_user': [['user_id:%(user_id)s']]}
self._set_policy(new_policy)
url_by_name = ('/users/%s' % self.user1['id'])
r = self.get(url_by_name, auth=self.auth)
body = r.body
self.assertEquals(self.user1['id'], body['user']['id'])
|
'GET /users?domain_id=mydomain (protected)
Test Plan:
- Update policy to protect api by domain_id
- List groups using a token scoped to domainA with a filter
specifying domainA - we should only get back the one user
that is in domainA.
- Try and read the users from domainB - this should fail since
we don\'t have a toke... | def test_list_users_protected_by_domain(self):
| new_policy = {'identity:list_users': ['domain_id:%(domain_id)s']}
self._set_policy(new_policy)
self.auth = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], domain_id=self.domainA['id'])
url_by_name = ('/users?domain_id=%s' % self.domainA['id'])
r = self.ge... |
'GET /groups?domain_id=mydomain (protected)
Test Plan:
- Update policy to protect api by domain_id
- List groups using a token scoped to domainA and make sure
we only get back the two groups that are in domainA
- Try and read the groups from domainB - this should fail since
we don\'t have a token scoped for domainB'
| def test_list_groups_protected_by_domain(self):
| new_policy = {'identity:list_groups': ['domain_id:%(domain_id)s']}
self._set_policy(new_policy)
self.auth = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], domain_id=self.domainA['id'])
url_by_name = ('/groups?domain_id=%s' % self.domainA['id'])
r = self.... |
'GET /groups?domain_id=mydomain&name=myname (protected)
Test Plan:
- Update policy to protect api by domain_id
- List groups using a token scoped to domainA with a filter
specifying both domainA and the name of group.
- We should only get back the group in domainA that matches
the name'
| def test_list_groups_protected_by_domain_and_filtered(self):
| new_policy = {'identity:list_groups': ['domain_id:%(domain_id)s']}
self._set_policy(new_policy)
self.auth = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], domain_id=self.domainA['id'])
url_by_name = ('/groups?domain_id=%s&name=%s' % (self.domainA['id'], self... |
'GET /domains?enabled=0
Test Plan:
- Update policy for no protection on api
- Filter by the \'enabled\' boolean to get disabled domains, which
should return just domainC
- Try the filter using different ways of specifying \'true\'
to test that our handling of booleans in filter matching is
correct'
| def test_list_filtered_domains(self):
| new_policy = {'identity:list_domains': []}
self._set_policy(new_policy)
r = self.get('/domains?enabled=0', auth=self.auth)
id_list = self._get_id_list_from_ref_list(r.body.get('domains'))
self.assertEqual(len(id_list), 1)
self.assertIn(self.domainC['id'], id_list)
r = self.get('/domains?enab... |
'GET /domains?enabled&name=myname
Test Plan:
- Update policy for no protection on api
- Filter by the \'enabled\' boolean and name - this should
return a single domain'
| def test_multiple_filters(self):
| new_policy = {'identity:list_domains': []}
self._set_policy(new_policy)
my_url = ('/domains?enableds&name=%s' % self.domainA['name'])
r = self.get(my_url, auth=self.auth)
id_list = self._get_id_list_from_ref_list(r.body.get('domains'))
self.assertEqual(len(id_list), 1)
self.assertIn(self.dom... |
'You should be able to cleanly undo and re-apply all upgrades.
Upgrades are run in the following order::
0 -> 1 -> 0 -> 1 -> 2 -> 1 -> 2 -> 3 -> 2 -> 3 ...'
| def test_two_steps_forward_one_step_back(self):
| for x in range(1, (self.max_version + 1)):
self.upgrade(x)
self.downgrade((x - 1))
self.upgrade(x)
|
'Asserts that the table contains the expected set of columns.'
| def assertTableColumns(self, table_name, expected_cols):
| self.initialize_sql()
table = self.select_table(table_name)
actual_cols = [col.name for col in table.columns]
self.assertEqual(expected_cols, actual_cols, ('%s table' % table_name))
|
'Naively inserts key-value pairs into a table, given a dictionary.'
| def insert_dict(self, session, table_name, d):
| this_table = sqlalchemy.Table(table_name, self.metadata, autoload=True)
insert = this_table.insert()
insert.execute(d)
session.commit()
|
'Asserts that a given table exists cannot be selected by name.'
| def assertTableDoesNotExist(self, table_name):
| try:
temp_metadata = sqlalchemy.MetaData()
temp_metadata.bind = self.engine
sqlalchemy.Table(table_name, temp_metadata, autoload=True)
except sqlalchemy.exc.NoSuchTableError:
pass
else:
raise AssertionError(('Table "%s" already exists' % table_name))
|
'Assert that two tokens are equal.
Compare two tokens except for their ids. This also truncates
the time in the comparison.'
| def assertEqualTokens(self, a, b):
| def normalize(token):
token['access']['token']['id'] = 'dummy'
del token['access']['token']['expires']
del token['access']['token']['issued_at']
return token
self.assertCloseEnoughForGovernmentWork(timeutils.parse_isotime(a['access']['token']['expires']), timeutils.parse_isotime(... |
'Verify that _authenticate_external() raises exception if
not applicable'
| def test_no_external_auth(self):
| self.assertRaises(token.controllers.ExternalAuthNotApplicable, self.controller._authenticate_external, {}, {})
|
'Verity that _authenticate_token() raises exception if no token'
| def test_no_token_in_auth(self):
| self.assertRaises(exception.ValidationError, self.controller._authenticate_token, None, {})
|
'Verity that _authenticate_local() raises exception if no creds'
| def test_no_credentials_in_auth(self):
| self.assertRaises(exception.ValidationError, self.controller._authenticate_local, None, {})
|
'Verify sending empty json dict raises the right exception.'
| def test_authenticate_blank_request_body(self):
| self.assertRaises(exception.ValidationError, self.controller.authenticate, {}, {})
|
'Verify sending blank \'auth\' raises the right exception.'
| def test_authenticate_blank_auth(self):
| body_dict = _build_user_auth()
self.assertRaises(exception.ValidationError, self.controller.authenticate, {}, body_dict)
|
'Verify sending invalid \'auth\' raises the right exception.'
| def test_authenticate_invalid_auth_content(self):
| self.assertRaises(exception.ValidationError, self.controller.authenticate, {}, {'auth': 'abcd'})
|
'Verify sending large \'userId\' raises the right exception.'
| def test_authenticate_user_id_too_large(self):
| body_dict = _build_user_auth(user_id=('0' * 65), username='FOO', password='foo2')
self.assertRaises(exception.ValidationSizeError, self.controller.authenticate, {}, body_dict)
|
'Verify sending large \'username\' raises the right exception.'
| def test_authenticate_username_too_large(self):
| body_dict = _build_user_auth(username=('0' * 65), password='foo2')
self.assertRaises(exception.ValidationSizeError, self.controller.authenticate, {}, body_dict)
|
'Verify sending large \'tenantId\' raises the right exception.'
| def test_authenticate_tenant_id_too_large(self):
| body_dict = _build_user_auth(username='FOO', password='foo2', tenant_id=('0' * 65))
self.assertRaises(exception.ValidationSizeError, self.controller.authenticate, {}, body_dict)
|
'Verify sending large \'tenantName\' raises the right exception.'
| def test_authenticate_tenant_name_too_large(self):
| body_dict = _build_user_auth(username='FOO', password='foo2', tenant_name=('0' * 65))
self.assertRaises(exception.ValidationSizeError, self.controller.authenticate, {}, body_dict)
|
'Verify sending large \'token\' raises the right exception.'
| def test_authenticate_token_too_large(self):
| body_dict = _build_user_auth(token={'id': ('0' * 8193)})
self.assertRaises(exception.ValidationSizeError, self.controller.authenticate, {}, body_dict)
|
'Verify sending large \'password\' raises the right exception.'
| def test_authenticate_password_too_large(self):
| body_dict = _build_user_auth(username='FOO', password=('0' * 8193))
self.assertRaises(exception.ValidationSizeError, self.controller.authenticate, {}, body_dict)
|
'Verify getting an unscoped token with password creds'
| def test_unscoped_token(self):
| body_dict = _build_user_auth(username='FOO', password='foo2')
unscoped_token = self.controller.authenticate({}, body_dict)
tenant = unscoped_token['access']['token'].get('tenant', None)
self.assertEqual(tenant, None)
|
'Verify exception is raised if invalid token'
| def test_auth_invalid_token(self):
| body_dict = _build_user_auth(token={'id': uuid.uuid4().hex})
self.assertRaises(exception.Unauthorized, self.controller.authenticate, {}, body_dict)
|
'Verify exception is raised if invalid token'
| def test_auth_bad_formatted_token(self):
| body_dict = _build_user_auth(token={})
self.assertRaises(exception.ValidationError, self.controller.authenticate, {}, body_dict)
|
'Verify getting an unscoped token with an unscoped token'
| def test_auth_unscoped_token_no_project(self):
| body_dict = _build_user_auth(username='FOO', password='foo2')
unscoped_token = self.controller.authenticate({}, body_dict)
body_dict = _build_user_auth(token=unscoped_token['access']['token'])
unscoped_token_2 = self.controller.authenticate({}, body_dict)
self.assertEqualTokens(unscoped_token, unsco... |
'Verify getting a token in a tenant with an unscoped token'
| def test_auth_unscoped_token_project(self):
| self.identity_api.add_role_to_user_and_project(self.user_foo['id'], self.tenant_bar['id'], self.role_member['id'])
body_dict = _build_user_auth(username='FOO', password='foo2')
unscoped_token = self.controller.authenticate({}, body_dict)
body_dict = _build_user_auth(token=unscoped_token['access']['token... |
'Verify getting a token in a tenant with group roles'
| def test_auth_token_project_group_role(self):
| self.identity_api.add_role_to_user_and_project(self.user_foo['id'], self.tenant_bar['id'], self.role_member['id'])
new_group = {'id': uuid.uuid4().hex, 'domain_id': uuid.uuid4().hex, 'name': uuid.uuid4().hex}
self.identity_api.create_group(new_group['id'], new_group)
self.identity_api.add_user_to_group(... |
'Verify getting a token in cross domain group/project roles'
| def test_auth_token_cross_domain_group_and_project(self):
| domain1 = {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex}
self.identity_api.create_domain(domain1['id'], domain1)
project1 = {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'domain_id': domain1['id']}
self.identity_api.create_project(project1['id'], project1)
role_foo_domain1 = {'id': uuid.uui... |
'Verify exception is raised if invalid user'
| def test_auth_invalid_user(self):
| body_dict = _build_user_auth(username=uuid.uuid4().hex, password=uuid.uuid4().hex)
self.assertRaises(exception.Unauthorized, self.controller.authenticate, {}, body_dict)
|
'Verify exception is raised if invalid password'
| def test_auth_valid_user_invalid_password(self):
| body_dict = _build_user_auth(username='FOO', password=uuid.uuid4().hex)
self.assertRaises(exception.Unauthorized, self.controller.authenticate, {}, body_dict)
|
'Verify exception is raised if empty password'
| def test_auth_empty_password(self):
| body_dict = _build_user_auth(username='FOO', password='')
self.assertRaises(exception.Unauthorized, self.controller.authenticate, {}, body_dict)
|
'Verify exception is raised if empty password'
| def test_auth_no_password(self):
| body_dict = _build_user_auth(username='FOO')
self.assertRaises(exception.ValidationError, self.controller.authenticate, {}, body_dict)
|
'Verify sending empty json dict as passwordCredentials raises the
right exception.'
| def test_authenticate_blank_password_credentials(self):
| body_dict = {'passwordCredentials': {}, 'tenantName': 'demo'}
self.assertRaises(exception.ValidationError, self.controller.authenticate, {}, body_dict)
|
'Verify skipping username raises the right exception.'
| def test_authenticate_no_username(self):
| body_dict = _build_user_auth(password='pass', tenant_name='demo')
self.assertRaises(exception.ValidationError, self.controller.authenticate, {}, body_dict)
|
'Verify getting an unscoped token with external authn'
| def test_unscoped_remote_authn(self):
| body_dict = _build_user_auth(username='FOO', password='foo2')
local_token = self.controller.authenticate({}, body_dict)
body_dict = _build_user_auth()
remote_token = self.controller.authenticate({'REMOTE_USER': 'FOO'}, body_dict)
self.assertEqualTokens(local_token, remote_token)
|
'Verify that external auth with invalid request fails'
| def test_unscoped_remote_authn_jsonless(self):
| self.assertRaises(exception.ValidationError, self.controller.authenticate, {'REMOTE_USER': 'FOO'}, None)
|
'Verify getting a token with external authn'
| def test_scoped_remote_authn(self):
| body_dict = _build_user_auth(username='FOO', password='foo2', tenant_name='BAR')
local_token = self.controller.authenticate({}, body_dict)
body_dict = _build_user_auth(tenant_name='BAR')
remote_token = self.controller.authenticate({'REMOTE_USER': 'FOO'}, body_dict)
self.assertEqualTokens(local_token... |
'Verify getting a token with external authn and no metadata'
| def test_scoped_nometa_remote_authn(self):
| body_dict = _build_user_auth(username='TWO', password='two2', tenant_name='BAZ')
local_token = self.controller.authenticate({}, body_dict)
body_dict = _build_user_auth(tenant_name='BAZ')
remote_token = self.controller.authenticate({'REMOTE_USER': 'TWO'}, body_dict)
self.assertEqualTokens(local_token... |
'Verify that external auth with invalid user fails'
| def test_scoped_remote_authn_invalid_user(self):
| body_dict = _build_user_auth(tenant_name='BAR')
self.assertRaises(exception.Unauthorized, self.controller.authenticate, {'REMOTE_USER': uuid.uuid4().hex}, body_dict)
|
'Token expiration should be maintained after re-auth & validation.'
| def _maintain_token_expiration(self):
| r = self.controller.authenticate({}, auth={'passwordCredentials': {'username': self.user_foo['name'], 'password': self.user_foo['password']}})
unscoped_token_id = r['access']['token']['id']
original_expiration = r['access']['token']['expires']
time.sleep(0.5)
r = self.controller.validate_token(dict(... |
'Setup for v3 Restful Test Cases.
If a child class wants to create their own sample data
and provide their own auth data to obtain tokens, then
load_sample_data should be set to false.'
| def setUp(self, load_sample_data=True):
| self.config([test.etcdir('keystone.conf.sample'), test.testsdir('test_overrides.conf'), test.testsdir('backend_sql.conf'), test.testsdir('backend_sql_disk.conf')])
sql_util.setup_test_database()
self.load_backends()
if load_sample_data:
self.domain_id = uuid.uuid4().hex
self.domain = sel... |
'Populates a ref with attributes common to all API entities.'
| def new_ref(self):
| return {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'enabled': True}
|
'Translates XML responses to dicts.
This implies that we only have to write assertions for JSON.'
| def admin_request(self, *args, **kwargs):
| r = super(RestfulTestCase, self).admin_request(*args, **kwargs)
if (r.getheader('Content-Type') == 'application/xml'):
r.body = serializer.from_xml(etree.tostring(r.body))
return r
|
'Convenience method so that we can test authenticated requests.'
| def get_scoped_token(self):
| r = self.admin_request(method='POST', path='/v3/auth/tokens', body={'auth': {'identity': {'methods': ['password'], 'password': {'user': {'name': self.user['name'], 'password': self.user['password'], 'domain': {'id': self.user['domain_id']}}}}, 'scope': {'project': {'id': self.project['id']}}}})
return r.gethead... |
'Request the specific token we want.'
| def get_requested_token(self, auth):
| r = self.admin_request(method='POST', path='/v3/auth/tokens', body=auth)
return r.getheader('X-Subject-Token')
|
'Make assertions common to all API list responses.
If a reference is provided, it\'s ID will be searched for in the
response, and asserted to be equal.'
| def assertValidListResponse(self, resp, key, entity_validator, ref=None, expected_length=None):
| entities = resp.body.get(key)
self.assertIsNotNone(entities)
if (expected_length is not None):
self.assertEqual(len(entities), expected_length)
elif (ref is not None):
self.assertTrue(len(entities))
self.assertValidListLinks(resp.body.get('links'))
for entity in entities:
... |
'Make assertions common to all API responses.'
| def assertValidResponse(self, resp, key, entity_validator, *args, **kwargs):
| entity = resp.body.get(key)
self.assertIsNotNone(entity)
self.assertValidEntity(entity, *args, **kwargs)
entity_validator(entity, *args, **kwargs)
return entity
|
'Make assertions common to all API entities.
If a reference is provided, the entity will also be compared against
the reference.'
| def assertValidEntity(self, entity, ref=None):
| keys = ['name', 'description', 'enabled']
for k in (['id'] + keys):
msg = ('%s unexpectedly None in %s' % (k, entity))
self.assertIsNotNone(entity.get(k), msg)
self.assertIsNotNone(entity.get('links'))
self.assertIsNotNone(entity['links'].get('self'))
self.assertIn((CONF.... |
'Assert that two tokens are equal.
Compare two tokens except for their ids. This also truncates
the time in the comparison.'
| def assertEqualTokens(self, a, b):
| def normalize(token):
del token['token']['expires_at']
del token['token']['issued_at']
return token
a_expires_at = self.assertValidISO8601ExtendedFormatDatetime(a['token']['expires_at'])
b_expires_at = self.assertValidISO8601ExtendedFormatDatetime(b['token']['expires_at'])
self.a... |
'Build auth dictionary.
It will create an auth dictionary based on all the arguments
that it receives.'
| def build_authentication_request(self, token=None, user_id=None, username=None, user_domain_id=None, user_domain_name=None, password=None, **kwargs):
| auth_data = {}
auth_data['identity'] = {'methods': []}
if token:
auth_data['identity']['methods'].append('token')
auth_data['identity']['token'] = self.build_token_auth(token)
if (user_id or username):
auth_data['identity']['methods'].append('password')
auth_data['identit... |
'Regression test for building the tree names'
| def test_build_tree(self):
| user_api = identity_ldap.UserApi(CONF)
self.assertTrue(user_api)
self.assertEquals(user_api.tree_dn, CONF.ldap.user_tree_dn)
|
'Kill running servers and release references to avoid leaks.'
| def tearDown(self):
| self.public_server.kill()
self.admin_server.kill()
self.public_server = None
self.admin_server = None
super(RestfulTestCase, self).tearDown()
|
'Perform request and fetch httplib.HTTPResponse from the server.'
| def request(self, host='0.0.0.0', port=80, method='GET', path='/', headers=None, body=None, expected_status=None):
| headers = ({} if (not headers) else headers)
connection = httplib.HTTPConnection(host, port, timeout=100000)
connection.request(method, path, body, headers)
response = connection.getresponse()
response.body = response.read()
connection.close()
if expected_status:
self.assertResponseS... |
'Asserts that a status code lies inside the 2xx range.
:param response: :py:class:`httplib.HTTPResponse` to be
verified to have a status code between 200 and 299.
example::
>>> self.assertResponseSuccessful(response, 203)'
| def assertResponseSuccessful(self, response):
| self.assertTrue(((response.status >= 200) and (response.status <= 299)), ('Status code %d is outside of the expected range (2xx)\n\n%s' % (response.status, response.body)))
|
'Asserts a specific status code on the response.
:param response: :py:class:`httplib.HTTPResponse`
:param assert_status: The specific ``status`` result expected
example::
>>> self.assertResponseStatus(response, 203)'
| def assertResponseStatus(self, response, expected_status):
| self.assertEqual(response.status, expected_status, ('Status code %s is not %s, as expected)\n\n%s' % (response.status, expected_status, response.body)))
|
'Ensures that response headers appear as expected.'
| def assertValidResponseHeaders(self, response):
| self.assertIn('X-Auth-Token', response.getheader('Vary'))
|
'Attempt to encode JSON and XML automatically.'
| def _to_content_type(self, body, headers, content_type=None):
| content_type = (content_type or self.content_type)
if (content_type == 'json'):
headers['Accept'] = 'application/json'
if body:
headers['Content-Type'] = 'application/json'
return jsonutils.dumps(body)
elif (content_type == 'xml'):
headers['Accept'] = 'applica... |
'Attempt to decode JSON and XML automatically, if detected.'
| def _from_content_type(self, response, content_type=None):
| content_type = (content_type or self.content_type)
response.raw = response.body
if ((response.body is not None) and response.body.strip()):
header = response.getheader('Content-Type', None)
self.assertIn(content_type, header)
if (content_type == 'json'):
response.body = j... |
'Serializes/deserializes json/xml as request/response body.
.. WARNING::
* Existing Accept header will be overwritten.
* Existing Content-Type header will be overwritten.'
| def restful_request(self, method='GET', headers=None, body=None, token=None, content_type=None, **kwargs):
| headers = ({} if (not headers) else headers)
if (token is not None):
headers['X-Auth-Token'] = token
body = self._to_content_type(body, headers, content_type)
response = self.request(method=method, headers=headers, body=body, **kwargs)
self._from_content_type(response, content_type)
if (... |
'Convenience method so that we can test authenticated requests.'
| def get_scoped_token(self):
| r = self.public_request(method='POST', path='/v2.0/tokens', body={'auth': {'passwordCredentials': {'username': self.user_foo['name'], 'password': self.user_foo['password']}, 'tenantId': self.tenant_bar['id']}})
return self._get_token_id(r)
|
'Helper method to return a token ID from a response.
This needs to be overridden by child classes for on their content type.'
| def _get_token_id(self, r):
| raise NotImplementedError()
|
'Applicable to XML and JSON.'
| def assertValidError(self, error):
| self.assertIsNotNone(error.get('code'))
self.assertIsNotNone(error.get('title'))
self.assertIsNotNone(error.get('message'))
|
'Applicable to XML and JSON.
However, navigating links and media-types differs between content
types so they need to be validated separately.'
| def assertValidVersion(self, version):
| self.assertIsNotNone(version)
self.assertIsNotNone(version.get('id'))
self.assertIsNotNone(version.get('status'))
self.assertIsNotNone(version.get('updated'))
|
'Applicable to XML and JSON.
However, navigating extension links differs between content types.
They need to be validated separately with assertValidExtensionLink.'
| def assertValidExtension(self, extension):
| self.assertIsNotNone(extension)
self.assertIsNotNone(extension.get('name'))
self.assertIsNotNone(extension.get('namespace'))
self.assertIsNotNone(extension.get('alias'))
self.assertIsNotNone(extension.get('updated'))
|
'Applicable to XML and JSON.'
| def assertValidExtensionLink(self, link):
| self.assertIsNotNone(link.get('rel'))
self.assertIsNotNone(link.get('type'))
self.assertIsNotNone(link.get('href'))
|
'Applicable to XML and JSON.'
| def assertValidTenant(self, tenant):
| self.assertIsNotNone(tenant.get('id'))
self.assertIsNotNone(tenant.get('name'))
|
'Applicable to XML and JSON.'
| def assertValidUser(self, user):
| self.assertIsNotNone(user.get('id'))
self.assertIsNotNone(user.get('name'))
|
'Applicable to XML and JSON.'
| def assertValidRole(self, tenant):
| self.assertIsNotNone(tenant.get('id'))
self.assertIsNotNone(tenant.get('name'))
|
'The same call as above, except using HEAD.
There\'s no response to validate here, but this is included for the
sake of completely covering the core API.'
| def test_validate_token_head(self):
| token = self.get_scoped_token()
self.admin_request(method='HEAD', path=('/v2.0/tokens/%(token_id)s' % {'token_id': token}), token=token, expected_status=204)
|
'This triggers assertValidErrorResponse by convention.'
| def test_error_response(self):
| self.public_request(path='/v2.0/tenants', expected_status=401)
|
'Applicable only to JSON.'
| def _get_token_id(self, r):
| return r.body['access']['token']['id']
|
'Service CRUD should 401 without an X-Auth-Token (bug 1006822).'
| def test_service_crud_requires_auth(self):
| service_path = ('/v2.0/OS-KSADM/services/%s' % uuid.uuid4().hex)
service_body = {'OS-KSADM:service': {'name': uuid.uuid4().hex, 'type': uuid.uuid4().hex}}
r = self.admin_request(method='GET', path='/v2.0/OS-KSADM/services', expected_status=401)
self.assertValidErrorResponse(r)
r = self.admin_request... |
'User role list should 401 without an X-Auth-Token (bug 1006815).'
| def test_user_role_list_requires_auth(self):
| path = ('/v2.0/tenants/%(tenant_id)s/users/%(user_id)s/roles' % {'tenant_id': uuid.uuid4().hex, 'user_id': uuid.uuid4().hex})
r = self.admin_request(path=path, expected_status=401)
self.assertValidErrorResponse(r)
|
'Helper method to build an namespaced element name.'
| def _tag(self, tag_name, xmlns=None):
| return ('{%(ns)s}%(tag)s' % {'ns': (xmlns or self.xmlns), 'tag': tag_name})
|
'Raise if we see a keyword arg called \'condition\' or \'methods\''
| def test_keyword_arg_condition_or_methods(self):
| modules = [admin_crud_core, ec2_core, s3_core, stats_core, user_crud_core, identity_core, service]
for module in modules:
filename = module.__file__
if filename.endswith('.pyc'):
filename = filename[:(-1)]
with open(filename) as fil:
source = fil.read()
mo... |
'Clients requesting XML should get what they ask for.'
| def test_client_wants_xml_back(self):
| body = '{"container": {"attribute": "value"}}'
req = make_request(body=body, method='POST', accept='application/xml')
middleware.XmlBodyMiddleware(None).process_request(req)
resp = make_response(body=body)
middleware.XmlBodyMiddleware(None).process_response(req, resp)
self.assertEqual(resp... |
'Clients requesting JSON should definitely not get XML back.'
| def test_client_wants_json_back(self):
| body = '{"container": {"attribute": "value"}}'
req = make_request(body=body, method='POST', accept='application/json')
middleware.XmlBodyMiddleware(None).process_request(req)
resp = make_response(body=body)
middleware.XmlBodyMiddleware(None).process_response(req, resp)
self.assertNotIn('ap... |
'If client does not specify an Accept header, default to JSON.'
| def test_client_fails_to_specify_accept(self):
| body = '{"container": {"attribute": "value"}}'
req = make_request(body=body, method='POST')
middleware.XmlBodyMiddleware(None).process_request(req)
resp = make_response(body=body)
middleware.XmlBodyMiddleware(None).process_response(req, resp)
self.assertNotIn('application/xml', resp.conten... |
'XML requests should be replaced by JSON requests.'
| def test_xml_replaced_by_json(self):
| req = make_request(body='<container><element attribute="value" /></container>', content_type='application/xml', method='POST')
middleware.XmlBodyMiddleware(None).process_request(req)
self.assertTrue(req.content_type, 'application/json')
self.assertTrue(jsonutils.loads(req.body))
|
'JSON-only requests should be unnaffected by the XML middleware.'
| def test_json_unnaffected(self):
| content_type = 'application/json'
body = '{"container": {"attribute": "value"}}'
req = make_request(body=body, content_type=content_type, method='POST')
middleware.XmlBodyMiddleware(None).process_request(req)
self.assertEqual(req.body, body)
self.assertEqual(req.content_type, content_type)... |
'Setup for Token Revoking Test Cases.
As well as the usual housekeeping, create a set of domains,
users, groups, roles and projects for the subsequent tests:
- Two domains: A & B
- DomainA has user1, domainB has user2 and user3
- DomainA has group1 and group2, domainB has group3
- User1 has a role on domainA
- Two proj... | def setUp(self):
| super(TestTokenRevoking, self).setUp()
self.domainA = self.new_domain_ref()
domainA_ref = self.identity_api.create_domain(self.domainA['id'], self.domainA)
self.domainB = self.new_domain_ref()
domainB_ref = self.identity_api.create_domain(self.domainB['id'], self.domainB)
self.projectA = self.ne... |
'Test deleting a user grant revokes token.
Test Plan:
- Get a token for user1, scoped to ProjectA
- Delete the grant user1 has on ProjectA
- Check token is no longer valid'
| def test_deleting_user_grant_revokes_token(self):
| auth_data = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id'])
resp = self.post('/auth/tokens', body=auth_data)
token = resp.getheader('X-Subject-Token')
self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_statu... |
'Test creating a user grant revokes token.
Test Plan:
- Get a token for user1, scoped to ProjectA
- Create a grant for user1 on DomainB
- Check token is no longer valid'
| def test_creating_user_grant_revokes_token(self):
| auth_data = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id'])
resp = self.post('/auth/tokens', body=auth_data)
token = resp.getheader('X-Subject-Token')
self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_statu... |
'Test deleting a group grant revokes tokens.
Test Plan:
- Get a token for user1, scoped to ProjectA
- Get a token for user2, scoped to ProjectA
- Get a token for user3, scoped to ProjectA
- Delete the grant group1 has on ProjectA
- Check tokens for user1 & user2 are no longer valid,
since user1 and user2 are members of... | def test_deleting_group_grant_revokes_tokens(self):
| auth_data = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id'])
resp = self.post('/auth/tokens', body=auth_data)
token1 = resp.getheader('X-Subject-Token')
auth_data = self.build_authentication_request(user_id=self.user2['id'], pas... |
'Test creating a group grant revokes token.
Test Plan:
- Get a token for user1, scoped to ProjectA
- Create a grant for group1 on DomainB
- Check token is no longer valid'
| def test_creating_group_grant_revokes_token(self):
| auth_data = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id'])
resp = self.post('/auth/tokens', body=auth_data)
token = resp.getheader('X-Subject-Token')
self.head('/auth/tokens', headers={'X-Subject-Token': token}, expected_statu... |
'Test add/removal to/from group revokes token.
Test Plan:
- Get a token for user1, scoped to ProjectA
- Get a token for user2, scoped to ProjectA
- Remove user1 from group1
- Check token for user1 is no longer valid
- Check token for user2 is still valid, even though
user2 is also part of group1
- Add user2 to group2
-... | def test_group_membership_changes_revokes_token(self):
| auth_data = self.build_authentication_request(user_id=self.user1['id'], password=self.user1['password'], project_id=self.projectA['id'])
resp = self.post('/auth/tokens', body=auth_data)
token1 = resp.getheader('X-Subject-Token')
auth_data = self.build_authentication_request(user_id=self.user2['id'], pas... |
'Everything callable in the exception module should be renderable.
... except for the base error class (exception.Error), which is not
user-facing.
This test provides a custom message to bypass docstring parsing, which
should be tested separately.'
| def test_all_json_renderings(self):
| for cls in [x for x in exception.__dict__.values() if callable(x)]:
if ((cls is not exception.Error) and isinstance(cls, exception.Error)):
self.assertValidJsonRendering(cls(message='Overriden.'))
|
'Make sure both public and admin API work with ipv6.'
| def test_ipv6_ok(self):
| self.public_server = self.serveapp('keystone', name='main', host='::1', port=0)
self.admin_server = self.serveapp('keystone', name='admin', host='::1', port=0)
conn = httplib.HTTPConnection('::1', CONF.admin_port)
conn.request('GET', '/')
resp = conn.getresponse()
self.assertEqual(resp.status, 3... |
'POST /policies'
| def test_create_policy(self):
| ref = self.new_policy_ref()
r = self.post('/policies', body={'policy': ref})
return self.assertValidPolicyResponse(r, ref)
|
'GET /policies'
| def test_list_policies(self):
| r = self.get('/policies')
self.assertValidPolicyListResponse(r, ref=self.policy)
|
'GET /policies (xml data)'
| def test_list_policies_xml(self):
| r = self.get('/policies', content_type='xml')
self.assertValidPolicyListResponse(r, ref=self.policy)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.