diff options
Diffstat (limited to 'keystoneclient/tests')
53 files changed, 695 insertions, 299 deletions
diff --git a/keystoneclient/tests/apiclient/test_exceptions.py b/keystoneclient/tests/apiclient/test_exceptions.py index 3f730cc..2c6c4b1 100644 --- a/keystoneclient/tests/apiclient/test_exceptions.py +++ b/keystoneclient/tests/apiclient/test_exceptions.py @@ -39,7 +39,7 @@ class ExceptionsArgsTest(utils.TestCase): json_data=json_data), method, url) - self.assertTrue(isinstance(ex, ex_cls)) + self.assertIsInstance(ex, ex_cls) self.assertEqual(ex.message, json_data["error"]["message"]) self.assertEqual(ex.details, json_data["error"]["details"]) self.assertEqual(ex.method, method) diff --git a/keystoneclient/tests/auth/__init__.py b/keystoneclient/tests/auth/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/keystoneclient/tests/auth/__init__.py diff --git a/keystoneclient/tests/client_fixtures.py b/keystoneclient/tests/client_fixtures.py index 2ed0506..6960355 100644 --- a/keystoneclient/tests/client_fixtures.py +++ b/keystoneclient/tests/client_fixtures.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -99,14 +97,19 @@ class Examples(fixtures.Fixture): self.v3_UUID_TOKEN_BIND = '2f61f73e1c854cbb9534c487f9bd63c2' self.v3_UUID_TOKEN_UNKNOWN_BIND = '7ed9781b62cd4880b8d8c6788ab1d1e2' - self.REVOKED_TOKEN_HASH = utils.hash_signed_token(self.REVOKED_TOKEN) + revoked_token = self.REVOKED_TOKEN + if isinstance(revoked_token, six.text_type): + revoked_token = revoked_token.encode('utf-8') + self.REVOKED_TOKEN_HASH = utils.hash_signed_token(revoked_token) self.REVOKED_TOKEN_LIST = ( {'revoked': [{'id': self.REVOKED_TOKEN_HASH, 'expires': timeutils.utcnow()}]}) self.REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(self.REVOKED_TOKEN_LIST) - self.REVOKED_v3_TOKEN_HASH = utils.hash_signed_token( - self.REVOKED_v3_TOKEN) + revoked_v3_token = self.REVOKED_v3_TOKEN + if isinstance(revoked_v3_token, six.text_type): + revoked_v3_token = revoked_v3_token.encode('utf-8') + self.REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(revoked_v3_token) self.REVOKED_v3_TOKEN_LIST = ( {'revoked': [{'id': self.REVOKED_v3_TOKEN_HASH, 'expires': timeutils.utcnow()}]}) diff --git a/keystoneclient/tests/fakes.py b/keystoneclient/tests/fakes.py index 941f9e4..d04ad8c 100644 --- a/keystoneclient/tests/fakes.py +++ b/keystoneclient/tests/fakes.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/generic/test_client.py b/keystoneclient/tests/generic/test_client.py new file mode 100644 index 0000000..1ea67cb --- /dev/null +++ b/keystoneclient/tests/generic/test_client.py @@ -0,0 +1,67 @@ +# Copyright 2014 OpenStack Foundation +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import httpretty + +from keystoneclient.generic import client +from keystoneclient.openstack.common import jsonutils +from keystoneclient.tests import utils + +BASE_HOST = 'http://keystone.example.com' +BASE_URL = "%s:5000/" % BASE_HOST +V2_URL = "%sv2.0" % BASE_URL + +EXTENSION_NAMESPACE = "http://docs.openstack.org/identity/api/ext/OS-FAKE/v1.0" +EXTENSION_DESCRIBED = {"href": "https://github.com/openstack/identity-api", + "rel": "describedby", + "type": "text/html"} + +EXTENSION_ALIAS_FOO = "OS-FAKE-FOO" +EXTENSION_NAME_FOO = "OpenStack Keystone Fake Extension Foo" +EXTENSION_FOO = {"alias": EXTENSION_ALIAS_FOO, + "description": "Fake Foo extension to V2.0 API.", + "links": [EXTENSION_DESCRIBED], + "name": EXTENSION_NAME_FOO, + "namespace": EXTENSION_NAMESPACE, + "updated": '2014-01-08T00:00:00Z'} + +EXTENSION_ALIAS_BAR = "OS-FAKE-BAR" +EXTENSION_NAME_BAR = "OpenStack Keystone Fake Extension Bar" +EXTENSION_BAR = {"alias": EXTENSION_ALIAS_BAR, + "description": "Fake Bar extension to V2.0 API.", + "links": [EXTENSION_DESCRIBED], + "name": EXTENSION_NAME_BAR, + "namespace": EXTENSION_NAMESPACE, + "updated": '2014-01-08T00:00:00Z'} + + +def _create_extension_list(extensions): + return jsonutils.dumps({'extensions': {'values': extensions}}) + + +EXTENSION_LIST = _create_extension_list([EXTENSION_FOO, EXTENSION_BAR]) + + +@httpretty.activate +class ClientDiscoveryTests(utils.TestCase): + + def test_discover_extensions_v2(self): + httpretty.register_uri(httpretty.GET, "%s/extensions" % V2_URL, + body=EXTENSION_LIST) + extensions = client.Client().discover_extensions(url=V2_URL) + self.assertIn(EXTENSION_ALIAS_FOO, extensions) + self.assertEqual(extensions[EXTENSION_ALIAS_FOO], EXTENSION_NAME_FOO) + self.assertIn(EXTENSION_ALIAS_BAR, extensions) + self.assertEqual(extensions[EXTENSION_ALIAS_BAR], EXTENSION_NAME_BAR) diff --git a/keystoneclient/tests/generic/test_shell.py b/keystoneclient/tests/generic/test_shell.py index d6679f5..e30b056 100644 --- a/keystoneclient/tests/generic/test_shell.py +++ b/keystoneclient/tests/generic/test_shell.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2014 OpenStack Foundation # All Rights Reserved. # diff --git a/keystoneclient/tests/test_auth_token_middleware.py b/keystoneclient/tests/test_auth_token_middleware.py index ae68d23..0bb9248 100644 --- a/keystoneclient/tests/test_auth_token_middleware.py +++ b/keystoneclient/tests/test_auth_token_middleware.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -16,20 +14,20 @@ import calendar import datetime -import iso8601 import os import shutil import stat import sys import tempfile -import testtools import time import uuid import fixtures import httpretty +import iso8601 import mock import testresources +import testtools import webob from keystoneclient.common import cms @@ -178,16 +176,11 @@ class TimezoneFixture(fixtures.Fixture): time.tzset() -class FakeSwiftOldMemcacheClient(memorycache.Client): - # NOTE(vish,chmou): old swift memcache uses param timeout instead of time - def set(self, key, value, timeout=0, min_compress_len=0): - sup = super(FakeSwiftOldMemcacheClient, self) - sup.set(key, value, timeout, min_compress_len) - - class FakeApp(object): """This represents a WSGI app protected by the auth_token middleware.""" + SUCCESS = b'SUCCESS' + def __init__(self, expected_env=None): self.expected_env = dict(EXPECTED_V2_DEFAULT_ENV_RESPONSE) @@ -199,7 +192,7 @@ class FakeApp(object): assert env[k] == v, '%s != %s' % (env[k], v) resp = webob.Response() - resp.body = 'SUCCESS' + resp.body = FakeApp.SUCCESS return resp(env, start_response) @@ -378,6 +371,7 @@ class DiabloAuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, httpretty.httpretty.reset() httpretty.enable() + self.addCleanup(httpretty.disable) httpretty.register_uri(httpretty.GET, "%s/" % BASE_URI, @@ -397,10 +391,6 @@ class DiabloAuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, self.set_middleware() - def tearDown(self): - httpretty.disable() - super(DiabloAuthTokenMiddlewareTest, self).tearDown() - def test_valid_diablo_response(self): req = webob.Request.blank('/') req.headers['X-Auth-Token'] = self.token_id @@ -465,7 +455,7 @@ class CommonAuthTokenMiddlewareTest(object): self.assertTrue(req.headers.get('X-Service-Catalog')) else: self.assertNotIn('X-Service-Catalog', req.headers) - self.assertEqual(body, ['SUCCESS']) + self.assertEqual(body, [FakeApp.SUCCESS]) self.assertIn('keystone.token_info', req.environ) def test_valid_uuid_request(self): @@ -734,11 +724,6 @@ class CommonAuthTokenMiddlewareTest(object): mock_utcnow.return_value = expired self.assertIsNone(self._get_cached_token(token)) - def test_old_swift_memcache_set_expired(self): - extra_conf = {'cache': 'swift.cache'} - extra_environ = {'swift.cache': FakeSwiftOldMemcacheClient()} - self.test_memcache_set_expired(extra_conf, extra_environ) - def test_swift_memcache_set_expired(self): extra_conf = {'cache': 'swift.cache'} extra_environ = {'swift.cache': memorycache.Client()} @@ -790,7 +775,7 @@ class CommonAuthTokenMiddlewareTest(object): 'memcache_secret_key': 'mysecret' } self.set_middleware(conf=conf) - token = 'my_token' + token = b'my_token' some_time_later = timeutils.utcnow() + datetime.timedelta(hours=4) expires = timeutils.strtime(some_time_later) data = ('this_data', expires) @@ -806,7 +791,7 @@ class CommonAuthTokenMiddlewareTest(object): 'memcache_secret_key': 'mysecret' } self.set_middleware(conf=conf) - token = 'my_token' + token = b'my_token' some_time_later = timeutils.utcnow() + datetime.timedelta(hours=4) expires = timeutils.strtime(some_time_later) data = ('this_data', expires) @@ -933,7 +918,7 @@ class CommonAuthTokenMiddlewareTest(object): if success: self.assertEqual(self.response_status, 200) - self.assertEqual(body, ['SUCCESS']) + self.assertEqual(body, [FakeApp.SUCCESS]) self.assertIn('keystone.token_info', req.environ) self.assert_valid_last_url(token) else: @@ -1083,6 +1068,7 @@ class CertDownloadMiddlewareTest(BaseAuthTokenMiddlewareTest, def setUp(self): super(CertDownloadMiddlewareTest, self).setUp() self.base_dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.base_dir) self.cert_dir = os.path.join(self.base_dir, 'certs') os.mkdir(self.cert_dir) conf = { @@ -1091,11 +1077,7 @@ class CertDownloadMiddlewareTest(BaseAuthTokenMiddlewareTest, self.set_middleware(conf=conf) httpretty.enable() - - def tearDown(self): - httpretty.disable() - shutil.rmtree(self.base_dir) - super(CertDownloadMiddlewareTest, self).tearDown() + self.addCleanup(httpretty.disable) # Usually we supply a signed_dir with pre-installed certificates, # so invocation of /usr/bin/openssl succeeds. This time we give it @@ -1226,6 +1208,7 @@ class v2AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, httpretty.httpretty.reset() httpretty.enable() + self.addCleanup(httpretty.disable) httpretty.register_uri(httpretty.GET, "%s/" % BASE_URI, @@ -1257,10 +1240,6 @@ class v2AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, self.set_middleware() - def tearDown(self): - httpretty.disable() - super(v2AuthTokenMiddlewareTest, self).tearDown() - def assert_unscoped_default_tenant_auto_scopes(self, token): """Unscoped v2 requests with a default tenant should "auto-scope." @@ -1271,7 +1250,7 @@ class v2AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, req.headers['X-Auth-Token'] = token body = self.middleware(req.environ, self.start_fake_response) self.assertEqual(self.response_status, 200) - self.assertEqual(body, ['SUCCESS']) + self.assertEqual(body, [FakeApp.SUCCESS]) self.assertIn('keystone.token_info', req.environ) def assert_valid_last_url(self, token_id): @@ -1310,7 +1289,7 @@ class v2AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, body = self.middleware(req.environ, self.start_fake_response) self.assertEqual(self.response_status, 200) self.assertFalse(req.headers.get('X-Service-Catalog')) - self.assertEqual(body, ['SUCCESS']) + self.assertEqual(body, [FakeApp.SUCCESS]) class CrossVersionAuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, @@ -1411,6 +1390,7 @@ class v3AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, httpretty.httpretty.reset() httpretty.enable() + self.addCleanup(httpretty.disable) httpretty.register_uri(httpretty.GET, "%s" % BASE_URI, @@ -1435,10 +1415,6 @@ class v3AuthTokenMiddlewareTest(BaseAuthTokenMiddlewareTest, self.set_middleware() - def tearDown(self): - httpretty.disable() - super(v3AuthTokenMiddlewareTest, self).tearDown() - def token_response(self, request, uri, headers): auth_id = request.headers.get('X-Auth-Token') token_id = request.headers.get('X-Subject-Token') @@ -1516,9 +1492,6 @@ class TokenExpirationTest(BaseAuthTokenMiddlewareTest): self.one_hour_earlier = timeutils.isotime(self.now + self.delta, subsecond=True) - def tearDown(self): - super(TokenExpirationTest, self).tearDown() - def create_v2_token_fixture(self, expires=None): v2_fixture = { 'access': { diff --git a/keystoneclient/tests/test_base.py b/keystoneclient/tests/test_base.py index 46e3dd2..7f60ce9 100644 --- a/keystoneclient/tests/test_base.py +++ b/keystoneclient/tests/test_base.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -146,8 +144,8 @@ class ManagerTest(utils.TestCase): self.client.patch = self.mox.CreateMockAnything() self.client.put = self.mox.CreateMockAnything() self.client.patch( - self.url, body=self.body, management=False).AndReturn( - (None, self.body)) + self.url, body=self.body, management=False).AndReturn((None, + self.body)) self.client.put(self.url, body=None, management=True).AndReturn( (None, self.body)) self.mox.ReplayAll() diff --git a/keystoneclient/tests/test_cms.py b/keystoneclient/tests/test_cms.py index 8160505..dbb8706 100644 --- a/keystoneclient/tests/test_cms.py +++ b/keystoneclient/tests/test_cms.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/test_discovery.py b/keystoneclient/tests/test_discovery.py index 2a3e7e8..5b9e24d 100644 --- a/keystoneclient/tests/test_discovery.py +++ b/keystoneclient/tests/test_discovery.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -23,6 +21,7 @@ from keystoneclient.tests import utils from keystoneclient.v2_0 import client as v2_client from keystoneclient.v3 import client as v3_client + BASE_HOST = 'http://keystone.example.com' BASE_URL = "%s:5000/" % BASE_HOST UPDATED = '2013-03-06T00:00:00Z' diff --git a/keystoneclient/tests/test_ec2utils.py b/keystoneclient/tests/test_ec2utils.py index d4346a4..ff4aee3 100644 --- a/keystoneclient/tests/test_ec2utils.py +++ b/keystoneclient/tests/test_ec2utils.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -29,9 +27,6 @@ class Ec2SignerTest(testtools.TestCase): self.secret = '89cdf9e94e2643cab35b8b8ac5a51f83' self.signer = utils.Ec2Signer(self.secret) - def tearDown(self): - super(Ec2SignerTest, self).tearDown() - def test_v4_creds_header(self): auth_str = 'AWS4-HMAC-SHA256 blah' credentials = {'host': '127.0.0.1', diff --git a/keystoneclient/tests/test_http.py b/keystoneclient/tests/test_http.py index 85bdc68..e089b7c 100644 --- a/keystoneclient/tests/test_http.py +++ b/keystoneclient/tests/test_http.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -14,8 +12,9 @@ # License for the specific language governing permissions and limitations # under the License. -import httpretty import logging + +import httpretty import six from testtools import matchers @@ -24,6 +23,7 @@ from keystoneclient import httpclient from keystoneclient import session from keystoneclient.tests import utils + RESPONSE_BODY = '{"hi": "there"}' @@ -114,7 +114,7 @@ class ClientTest(utils.TestCase): cl.post("/hi", body=[1, 2, 3]) self.assertEqual(httpretty.last_request().method, 'POST') - self.assertEqual(httpretty.last_request().body, '[1, 2, 3]') + self.assertEqual(httpretty.last_request().body, b'[1, 2, 3]') self.assertRequestHeaderEqual('X-Auth-Token', 'token') self.assertRequestHeaderEqual('Content-Type', 'application/json') diff --git a/keystoneclient/tests/test_https.py b/keystoneclient/tests/test_https.py index b4a955b..729f014 100644 --- a/keystoneclient/tests/test_https.py +++ b/keystoneclient/tests/test_https.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -13,13 +11,13 @@ # under the License. import mock - import requests from keystoneclient import httpclient from keystoneclient import session from keystoneclient.tests import utils + FAKE_RESPONSE = utils.TestResponse({ "status_code": 200, "text": '{"hi": "there"}', @@ -50,10 +48,7 @@ class ClientTest(utils.TestCase): self.request_patcher = mock.patch.object(requests, 'request', self.mox.CreateMockAnything()) self.request_patcher.start() - - def tearDown(self): - self.request_patcher.stop() - super(ClientTest, self).tearDown() + self.addCleanup(self.request_patcher.stop) @mock.patch.object(session.requests.Session, 'request') def test_get(self, MOCK_REQUEST): diff --git a/keystoneclient/tests/test_keyring.py b/keystoneclient/tests/test_keyring.py index a44d432..50dfb2b 100644 --- a/keystoneclient/tests/test_keyring.py +++ b/keystoneclient/tests/test_keyring.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -28,6 +26,7 @@ try: except ImportError: keyring = None + PROJECT_SCOPED_TOKEN = client_fixtures.PROJECT_SCOPED_TOKEN # These mirror values from PROJECT_SCOPED_TOKEN diff --git a/keystoneclient/tests/test_memcache_crypt.py b/keystoneclient/tests/test_memcache_crypt.py index 500a509..be07b24 100644 --- a/keystoneclient/tests/test_memcache_crypt.py +++ b/keystoneclient/tests/test_memcache_crypt.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -12,6 +10,7 @@ # License for the specific language governing permissions and limitations # under the License. +import six import testtools from keystoneclient.middleware import memcache_crypt @@ -19,7 +18,7 @@ from keystoneclient.middleware import memcache_crypt class MemcacheCryptPositiveTests(testtools.TestCase): def _setup_keys(self, strategy): - return memcache_crypt.derive_keys('token', 'secret', strategy) + return memcache_crypt.derive_keys(b'token', b'secret', strategy) def test_constant_time_compare(self): # make sure it works as a compare, the "constant time" aspect @@ -32,8 +31,18 @@ class MemcacheCryptPositiveTests(testtools.TestCase): self.assertFalse(ctc('abc', 'abc\x00')) self.assertFalse(ctc('', 'abc')) + # For Python 3, we want to test these functions with both str and bytes + # as input. + if six.PY3: + self.assertTrue(ctc(b'abcd', b'abcd')) + self.assertTrue(ctc(b'', b'')) + self.assertFalse(ctc(b'abcd', b'efgh')) + self.assertFalse(ctc(b'abc', b'abcd')) + self.assertFalse(ctc(b'abc', b'abc\x00')) + self.assertFalse(ctc(b'', b'abc')) + def test_derive_keys(self): - keys = memcache_crypt.derive_keys('token', 'secret', 'strategy') + keys = self._setup_keys(b'strategy') self.assertEqual(len(keys['ENCRYPTION']), len(keys['CACHE_KEY'])) self.assertEqual(len(keys['CACHE_KEY']), @@ -43,20 +52,20 @@ class MemcacheCryptPositiveTests(testtools.TestCase): self.assertIn('strategy', keys.keys()) def test_key_strategy_diff(self): - k1 = self._setup_keys('MAC') - k2 = self._setup_keys('ENCRYPT') + k1 = self._setup_keys(b'MAC') + k2 = self._setup_keys(b'ENCRYPT') self.assertNotEqual(k1, k2) def test_sign_data(self): - keys = self._setup_keys('MAC') - sig = memcache_crypt.sign_data(keys['MAC'], 'data') + keys = self._setup_keys(b'MAC') + sig = memcache_crypt.sign_data(keys['MAC'], b'data') self.assertEqual(len(sig), memcache_crypt.DIGEST_LENGTH_B64) def test_encryption(self): - keys = self._setup_keys('ENCRYPT') + keys = self._setup_keys(b'ENCRYPT') # what you put in is what you get out - for data in ['data', '1234567890123456', '\x00\xFF' * 13 - ] + [chr(x % 256) * x for x in range(768)]: + for data in [b'data', b'1234567890123456', b'\x00\xFF' * 13 + ] + [six.int2byte(x % 256) * x for x in range(768)]: crypt = memcache_crypt.encrypt_data(keys['ENCRYPTION'], data) decrypt = memcache_crypt.decrypt_data(keys['ENCRYPTION'], crypt) self.assertEqual(data, decrypt) @@ -65,12 +74,12 @@ class MemcacheCryptPositiveTests(testtools.TestCase): keys['ENCRYPTION'], crypt[:-1]) def test_protect_wrappers(self): - data = 'My Pretty Little Data' - for strategy in ['MAC', 'ENCRYPT']: + data = b'My Pretty Little Data' + for strategy in [b'MAC', b'ENCRYPT']: keys = self._setup_keys(strategy) protected = memcache_crypt.protect_data(keys, data) self.assertNotEqual(protected, data) - if strategy == 'ENCRYPT': + if strategy == b'ENCRYPT': self.assertNotIn(data, protected) unprotected = memcache_crypt.unprotect_data(keys, protected) self.assertEqual(data, unprotected) diff --git a/keystoneclient/tests/test_s3_token_middleware.py b/keystoneclient/tests/test_s3_token_middleware.py new file mode 100644 index 0000000..c3272cc --- /dev/null +++ b/keystoneclient/tests/test_s3_token_middleware.py @@ -0,0 +1,236 @@ +# Copyright 2012 OpenStack Foundation +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import httpretty +import mock +import requests +import six +import testtools +import webob + +from keystoneclient.middleware import s3_token +from keystoneclient.openstack.common import jsonutils +from keystoneclient.tests import utils + + +GOOD_RESPONSE = {'access': {'token': {'id': 'TOKEN_ID', + 'tenant': {'id': 'TENANT_ID'}}}} + + +class FakeApp(object): + """This represents a WSGI app protected by the auth_token middleware.""" + def __call__(self, env, start_response): + resp = webob.Response() + resp.environ = env + return resp(env, start_response) + + +class S3TokenMiddlewareTestBase(utils.TestCase): + + TEST_PROTOCOL = 'https' + TEST_HOST = 'fakehost' + TEST_PORT = 35357 + TEST_URL = '%s://%s:%d/v2.0/s3tokens' % (TEST_PROTOCOL, + TEST_HOST, + TEST_PORT) + + def setUp(self): + super(S3TokenMiddlewareTestBase, self).setUp() + + self.conf = { + 'auth_host': self.TEST_HOST, + 'auth_port': self.TEST_PORT, + 'auth_protocol': self.TEST_PROTOCOL, + } + + httpretty.reset() + httpretty.enable() + self.addCleanup(httpretty.disable) + + def start_fake_response(self, status, headers): + self.response_status = int(status.split(' ', 1)[0]) + self.response_headers = dict(headers) + + +class S3TokenMiddlewareTestGood(S3TokenMiddlewareTestBase): + + def setUp(self): + super(S3TokenMiddlewareTestGood, self).setUp() + self.middleware = s3_token.S3Token(FakeApp(), self.conf) + + httpretty.register_uri(httpretty.POST, self.TEST_URL, + status=201, body=jsonutils.dumps(GOOD_RESPONSE)) + + # Ignore the request and pass to the next middleware in the + # pipeline if no path has been specified. + def test_no_path_request(self): + req = webob.Request.blank('/') + self.middleware(req.environ, self.start_fake_response) + self.assertEqual(self.response_status, 200) + + # Ignore the request and pass to the next middleware in the + # pipeline if no Authorization header has been specified + def test_without_authorization(self): + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + self.middleware(req.environ, self.start_fake_response) + self.assertEqual(self.response_status, 200) + + def test_without_auth_storage_token(self): + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'badboy' + self.middleware(req.environ, self.start_fake_response) + self.assertEqual(self.response_status, 200) + + def test_authorized(self): + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'access:signature' + req.headers['X-Storage-Token'] = 'token' + req.get_response(self.middleware) + self.assertTrue(req.path.startswith('/v1/AUTH_TENANT_ID')) + self.assertEqual(req.headers['X-Auth-Token'], 'TOKEN_ID') + + def test_authorized_http(self): + self.middleware = ( + s3_token.filter_factory({'auth_protocol': 'http', + 'auth_host': self.TEST_HOST, + 'auth_port': self.TEST_PORT})(FakeApp())) + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'access:signature' + req.headers['X-Storage-Token'] = 'token' + req.get_response(self.middleware) + self.assertTrue(req.path.startswith('/v1/AUTH_TENANT_ID')) + self.assertEqual(req.headers['X-Auth-Token'], 'TOKEN_ID') + + def test_authorization_nova_toconnect(self): + req = webob.Request.blank('/v1/AUTH_swiftint/c/o') + req.headers['Authorization'] = 'access:FORCED_TENANT_ID:signature' + req.headers['X-Storage-Token'] = 'token' + req.get_response(self.middleware) + path = req.environ['PATH_INFO'] + self.assertTrue(path.startswith('/v1/AUTH_FORCED_TENANT_ID')) + + @mock.patch.object(requests, 'post') + def test_insecure(self, MOCK_REQUEST): + self.middleware = ( + s3_token.filter_factory({'insecure': True})(FakeApp())) + + text_return_value = jsonutils.dumps(GOOD_RESPONSE) + if six.PY3: + text_return_value = text_return_value.encode() + MOCK_REQUEST.return_value = utils.TestResponse({ + 'status_code': 201, + 'text': text_return_value}) + + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'access:signature' + req.headers['X-Storage-Token'] = 'token' + req.get_response(self.middleware) + + self.assertTrue(MOCK_REQUEST.called) + mock_args, mock_kwargs = MOCK_REQUEST.call_args + self.assertIs(mock_kwargs['verify'], False) + + +class S3TokenMiddlewareTestBad(S3TokenMiddlewareTestBase): + def setUp(self): + super(S3TokenMiddlewareTestBad, self).setUp() + self.middleware = s3_token.S3Token(FakeApp(), self.conf) + + def test_unauthorized_token(self): + ret = {"error": + {"message": "EC2 access key not found.", + "code": 401, + "title": "Unauthorized"}} + httpretty.register_uri(httpretty.POST, self.TEST_URL, + status=403, body=jsonutils.dumps(ret)) + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'access:signature' + req.headers['X-Storage-Token'] = 'token' + resp = req.get_response(self.middleware) + s3_denied_req = self.middleware.deny_request('AccessDenied') + self.assertEqual(resp.body, s3_denied_req.body) + self.assertEqual(resp.status_int, s3_denied_req.status_int) + + def test_bogus_authorization(self): + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'badboy' + req.headers['X-Storage-Token'] = 'token' + resp = req.get_response(self.middleware) + self.assertEqual(resp.status_int, 400) + s3_invalid_req = self.middleware.deny_request('InvalidURI') + self.assertEqual(resp.body, s3_invalid_req.body) + self.assertEqual(resp.status_int, s3_invalid_req.status_int) + + def test_fail_to_connect_to_keystone(self): + with mock.patch.object(self.middleware, '_json_request') as o: + s3_invalid_req = self.middleware.deny_request('InvalidURI') + o.side_effect = s3_token.ServiceError(s3_invalid_req) + + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'access:signature' + req.headers['X-Storage-Token'] = 'token' + resp = req.get_response(self.middleware) + self.assertEqual(resp.body, s3_invalid_req.body) + self.assertEqual(resp.status_int, s3_invalid_req.status_int) + + def test_bad_reply(self): + httpretty.register_uri(httpretty.POST, self.TEST_URL, + status=201, body="<badreply>") + + req = webob.Request.blank('/v1/AUTH_cfa/c/o') + req.headers['Authorization'] = 'access:signature' + req.headers['X-Storage-Token'] = 'token' + resp = req.get_response(self.middleware) + s3_invalid_req = self.middleware.deny_request('InvalidURI') + self.assertEqual(resp.body, s3_invalid_req.body) + self.assertEqual(resp.status_int, s3_invalid_req.status_int) + + +class S3TokenMiddlewareTestUtil(testtools.TestCase): + def test_split_path_failed(self): + self.assertRaises(ValueError, s3_token.split_path, '') + self.assertRaises(ValueError, s3_token.split_path, '/') + self.assertRaises(ValueError, s3_token.split_path, '//') + self.assertRaises(ValueError, s3_token.split_path, '//a') + self.assertRaises(ValueError, s3_token.split_path, '/a/c') + self.assertRaises(ValueError, s3_token.split_path, '//c') + self.assertRaises(ValueError, s3_token.split_path, '/a/c/') + self.assertRaises(ValueError, s3_token.split_path, '/a//') + self.assertRaises(ValueError, s3_token.split_path, '/a', 2) + self.assertRaises(ValueError, s3_token.split_path, '/a', 2, 3) + self.assertRaises(ValueError, s3_token.split_path, '/a', 2, 3, True) + self.assertRaises(ValueError, s3_token.split_path, '/a/c/o/r', 3, 3) + self.assertRaises(ValueError, s3_token.split_path, '/a', 5, 4) + + def test_split_path_success(self): + self.assertEqual(s3_token.split_path('/a'), ['a']) + self.assertEqual(s3_token.split_path('/a/'), ['a']) + self.assertEqual(s3_token.split_path('/a/c', 2), ['a', 'c']) + self.assertEqual(s3_token.split_path('/a/c/o', 3), ['a', 'c', 'o']) + self.assertEqual(s3_token.split_path('/a/c/o/r', 3, 3, True), + ['a', 'c', 'o/r']) + self.assertEqual(s3_token.split_path('/a/c', 2, 3, True), + ['a', 'c', None]) + self.assertEqual(s3_token.split_path('/a/c/', 2), ['a', 'c']) + self.assertEqual(s3_token.split_path('/a/c/', 2, 3), ['a', 'c', '']) + + def test_split_path_invalid_path(self): + try: + s3_token.split_path('o\nn e', 2) + except ValueError as err: + self.assertEqual(str(err), 'Invalid path: o%0An%20e') + try: + s3_token.split_path('o\nn e', 2, 3, True) + except ValueError as err: + self.assertEqual(str(err), 'Invalid path: o%0An%20e') diff --git a/keystoneclient/tests/test_session.py b/keystoneclient/tests/test_session.py index 0edaac4..5f2c42c 100644 --- a/keystoneclient/tests/test_session.py +++ b/keystoneclient/tests/test_session.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -16,7 +14,9 @@ import httpretty import mock import requests +import six +from keystoneclient.auth import base from keystoneclient import exceptions from keystoneclient import session as client_session from keystoneclient.tests import utils @@ -140,6 +140,25 @@ class SessionTests(utils.TestCase): self.assertRaises(exceptions.InternalServerError, session.get, self.TEST_URL) + @httpretty.activate + def test_session_debug_output(self): + session = client_session.Session(verify=False) + headers = {'HEADERA': 'HEADERVALB'} + body = 'BODYRESPONSE' + data = 'BODYDATA' + self.stub_url(httpretty.POST, body=body) + session.post(self.TEST_URL, headers=headers, data=data) + + self.assertIn('curl', self.logger.output) + self.assertIn('POST', self.logger.output) + self.assertIn('--insecure', self.logger.output) + self.assertIn(body, self.logger.output) + self.assertIn("'%s'" % data, self.logger.output) + + for k, v in six.iteritems(headers): + self.assertIn(k, self.logger.output) + self.assertIn(v, self.logger.output) + class RedirectTests(utils.TestCase): @@ -222,3 +241,77 @@ class RedirectTests(utils.TestCase): for r, s in zip(req_resp.history, ses_resp.history): self.assertEqual(r.url, s.url) self.assertEqual(r.status_code, s.status_code) + + +class ConstructSessionFromArgsTests(utils.TestCase): + + KEY = 'keyfile' + CERT = 'certfile' + CACERT = 'cacert-path' + + def _s(self, k=None, **kwargs): + k = k or kwargs + return client_session.Session.construct(k) + + def test_verify(self): + self.assertFalse(self._s(insecure=True).verify) + self.assertTrue(self._s(verify=True, insecure=True).verify) + self.assertFalse(self._s(verify=False, insecure=True).verify) + self.assertEqual(self._s(cacert=self.CACERT).verify, self.CACERT) + + def test_cert(self): + tup = (self.CERT, self.KEY) + self.assertEqual(self._s(cert=tup).cert, tup) + self.assertEqual(self._s(cert=self.CERT, key=self.KEY).cert, tup) + self.assertIsNone(self._s(key=self.KEY).cert) + + def test_pass_through(self): + value = 42 # only a number because timeout needs to be + for key in ['timeout', 'session', 'original_ip', 'user_agent']: + args = {key: value} + self.assertEqual(getattr(self._s(args), key), value) + self.assertNotIn(key, args) + + +class AuthPlugin(base.BaseAuthPlugin): + """Very simple debug authentication plugin. + + Takes Parameters such that it can throw exceptions at the right times. + """ + + TEST_TOKEN = 'aToken' + + def __init__(self, token=TEST_TOKEN): + self.token = token + + def get_token(self, session): + return self.token + + +class SessionAuthTests(utils.TestCase): + + TEST_URL = 'http://127.0.0.1:5000/' + TEST_JSON = {'hello': 'world'} + + @httpretty.activate + def test_auth_plugin_default_with_plugin(self): + self.stub_url('GET', base_url=self.TEST_URL, json=self.TEST_JSON) + + # if there is an auth_plugin then it should default to authenticated + auth = AuthPlugin() + sess = client_session.Session(auth=auth) + resp = sess.get(self.TEST_URL) + self.assertDictEqual(resp.json(), self.TEST_JSON) + + self.assertRequestHeaderEqual('X-Auth-Token', AuthPlugin.TEST_TOKEN) + + @httpretty.activate + def test_auth_plugin_disable(self): + self.stub_url('GET', base_url=self.TEST_URL, json=self.TEST_JSON) + + auth = AuthPlugin() + sess = client_session.Session(auth=auth) + resp = sess.get(self.TEST_URL, authenticated=False) + self.assertDictEqual(resp.json(), self.TEST_JSON) + + self.assertRequestHeaderEqual('X-Auth-Token', None) diff --git a/keystoneclient/tests/test_shell.py b/keystoneclient/tests/test_shell.py index 3e76d8c..2bf5eb8 100644 --- a/keystoneclient/tests/test_shell.py +++ b/keystoneclient/tests/test_shell.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -62,6 +60,10 @@ class ShellTest(utils.TestCase): def setUp(self): super(ShellTest, self).setUp() + for var in os.environ: + if var.startswith("OS_"): + self.useFixture(fixtures.EnvironmentVariable(var, "")) + for var in self.FAKE_ENV: self.useFixture(fixtures.EnvironmentVariable(var, self.FAKE_ENV[var])) diff --git a/keystoneclient/tests/test_utils.py b/keystoneclient/tests/test_utils.py index 18554c1..27d3c8d 100644 --- a/keystoneclient/tests/test_utils.py +++ b/keystoneclient/tests/test_utils.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -14,7 +12,6 @@ import sys -import mock import six from keystoneclient import exceptions @@ -108,12 +105,9 @@ class PrintTestCase(test_utils.TestCase): super(PrintTestCase, self).setUp() self.old_stdout = sys.stdout self.stdout = six.moves.cStringIO() + self.addCleanup(setattr, self, 'stdout', None) sys.stdout = self.stdout - - def tearDown(self): - super(PrintTestCase, self).tearDown() - sys.stdout = self.old_stdout - self.stdout = None + self.addCleanup(setattr, sys, 'stdout', self.old_stdout) def test_print_list_unicode(self): name = u'\u540d\u5b57' @@ -121,24 +115,19 @@ class PrintTestCase(test_utils.TestCase): # NOTE(Jeffrey4l) If the text's encode is proper, this method will not # raise UnicodeEncodeError exceptions utils.print_list(objs, ['name']) - self.assertIn(name, self.stdout.getvalue().decode('utf8')) - - @mock.patch('keystoneclient.openstack.common.strutils.safe_encode') - def test_print_list_unicode_without_encode(self, safe_encode_mock): - safe_encode_mock.side_effect = lambda x, *args, **kwargs: x - - name = u'\u540d\u5b57' - objs = [FakeObject(name)] - self.assertRaises(UnicodeEncodeError, utils.print_list, objs, ['name']) + output = self.stdout.getvalue() + # In Python 2, output will be bytes, while in Python 3, it will not. + # Let's decode the value if needed. + if isinstance(output, six.binary_type): + output = output.decode('utf-8') + self.assertIn(name, output) def test_print_dict_unicode(self): name = u'\u540d\u5b57' utils.print_dict({'name': name}) - self.assertIn(name, self.stdout.getvalue().decode('utf8')) - - @mock.patch('keystoneclient.openstack.common.strutils.safe_encode') - def test_print_dict_unicode_without_encode(self, safe_encode_mock): - safe_encode_mock.side_effect = lambda x, *args, **kwargs: x - - name = u'\u540d\u5b57' - self.assertRaises(UnicodeEncodeError, utils.print_dict, {'name': name}) + output = self.stdout.getvalue() + # In Python 2, output will be bytes, while in Python 3, it will not. + # Let's decode the value if needed. + if isinstance(output, six.binary_type): + output = output.decode('utf-8') + self.assertIn(name, output) diff --git a/keystoneclient/tests/utils.py b/keystoneclient/tests/utils.py index ec54671..3256dd3 100644 --- a/keystoneclient/tests/utils.py +++ b/keystoneclient/tests/utils.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -12,13 +10,16 @@ # License for the specific language governing permissions and limitations # under the License. +import logging import sys import time +import fixtures import httpretty import mock from mox3 import mox import requests +import six from six.moves.urllib import parse as urlparse import testtools @@ -39,6 +40,7 @@ class TestCase(testtools.TestCase): def setUp(self): super(TestCase, self).setUp() self.mox = mox.Mox() + self.logger = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG)) self.time_patcher = mock.patch.object(time, 'time', lambda: 1234) self.time_patcher.start() @@ -64,11 +66,15 @@ class TestCase(testtools.TestCase): httpretty.register_uri(method, url, **kwargs) def assertRequestBodyIs(self, body=None, json=None): + last_request_body = httpretty.last_request().body + if six.PY3: + last_request_body = last_request_body.decode('utf-8') + if json: - val = jsonutils.loads(httpretty.last_request().body) + val = jsonutils.loads(last_request_body) self.assertEqual(json, val) elif body: - self.assertEqual(body, httpretty.last_request().body) + self.assertEqual(body, last_request_body) def assertQueryStringIs(self, qs=''): """Verify the QueryString matches what is expected. @@ -78,6 +84,13 @@ class TestCase(testtools.TestCase): expected = urlparse.parse_qs(qs) self.assertEqual(expected, httpretty.last_request().querystring) + def assertQueryStringContains(self, **kwargs): + qs = httpretty.last_request().querystring + + for k, v in six.iteritems(kwargs): + self.assertIn(k, qs) + self.assertIn(v, qs[k]) + def assertRequestHeaderEqual(self, name, val): """Verify that the last request made contains a header and its value diff --git a/keystoneclient/tests/v2_0/client_fixtures.py b/keystoneclient/tests/v2_0/client_fixtures.py index 5735fd4..37f4fc1 100644 --- a/keystoneclient/tests/v2_0/client_fixtures.py +++ b/keystoneclient/tests/v2_0/client_fixtures.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -27,49 +25,53 @@ UNSCOPED_TOKEN = { } } +_TENANT_ID = '225da22d3ce34b15877ea70b2a575f58' + PROJECT_SCOPED_TOKEN = { 'access': { 'serviceCatalog': [{ 'endpoints': [{ - 'adminURL': 'http://admin:8776/v1/225da22d3ce34b15877ea70b2a575f58', - 'internalURL': - 'http://internal:8776/v1/225da22d3ce34b15877ea70b2a575f58', - 'publicURL': - 'http://public.com:8776/v1/225da22d3ce34b15877ea70b2a575f58', - 'region': 'RegionOne' + 'adminURL': 'http://admin:8776/v1/%s' % _TENANT_ID, + 'internalURL': 'http://internal:8776/v1/%s' % _TENANT_ID, + 'publicURL': 'http://public.com:8776/v1/%s' % _TENANT_ID, + 'region': 'RegionOne' }], 'endpoints_links': [], 'name': 'Volume Service', 'type': 'volume'}, {'endpoints': [{ - 'adminURL': 'http://admin:9292/v1', - 'internalURL': 'http://internal:9292/v1', - 'publicURL': 'http://public.com:9292/v1', - 'region': 'RegionOne'}], + 'adminURL': 'http://admin:9292/v1', + 'internalURL': 'http://internal:9292/v1', + 'publicURL': 'http://public.com:9292/v1', + 'region': 'RegionOne' + }], 'endpoints_links': [], 'name': 'Image Service', 'type': 'image'}, {'endpoints': [{ -'adminURL': 'http://admin:8774/v2/225da22d3ce34b15877ea70b2a575f58', -'internalURL': 'http://internal:8774/v2/225da22d3ce34b15877ea70b2a575f58', -'publicURL': 'http://public.com:8774/v2/225da22d3ce34b15877ea70b2a575f58', -'region': 'RegionOne'}], + 'adminURL': 'http://admin:8774/v2/%s' % _TENANT_ID, + 'internalURL': 'http://internal:8774/v2/%s' % _TENANT_ID, + 'publicURL': 'http://public.com:8774/v2/%s' % _TENANT_ID, + 'region': 'RegionOne' + }], 'endpoints_links': [], 'name': 'Compute Service', 'type': 'compute'}, {'endpoints': [{ -'adminURL': 'http://admin:8773/services/Admin', -'internalURL': 'http://internal:8773/services/Cloud', -'publicURL': 'http://public.com:8773/services/Cloud', -'region': 'RegionOne'}], + 'adminURL': 'http://admin:8773/services/Admin', + 'internalURL': 'http://internal:8773/services/Cloud', + 'publicURL': 'http://public.com:8773/services/Cloud', + 'region': 'RegionOne' + }], 'endpoints_links': [], 'name': 'EC2 Service', 'type': 'ec2'}, {'endpoints': [{ -'adminURL': 'http://admin:35357/v2.0', -'internalURL': 'http://internal:5000/v2.0', -'publicURL': 'http://public.com:5000/v2.0', -'region': 'RegionOne'}], + 'adminURL': 'http://admin:35357/v2.0', + 'internalURL': 'http://internal:5000/v2.0', + 'publicURL': 'http://public.com:5000/v2.0', + 'region': 'RegionOne' + }], 'endpoints_links': [], 'name': 'Identity Service', 'type': 'identity'}], diff --git a/keystoneclient/tests/v2_0/fakes.py b/keystoneclient/tests/v2_0/fakes.py index 55442a4..c8de539 100644 --- a/keystoneclient/tests/v2_0/fakes.py +++ b/keystoneclient/tests/v2_0/fakes.py @@ -99,7 +99,7 @@ class FakeHTTPClient(fakes.FakeClient): {"tenantId": "1", "id": "3", "name": "Member"}], - "name": "joeuser"}} + "name": "joeuser"}} } ] return (200, body) @@ -116,11 +116,10 @@ class FakeHTTPClient(fakes.FakeClient): {"name": "joeuser", "tenantName": "customer-x", "id": "1", - "roles": [ - {"serviceId": "1", - "id": "3", - "name": "Member"}], - "tenantId": "1"}} + "roles": [{"serviceId": "1", + "id": "3", + "name": "Member"}], + "tenantId": "1"}} } ] return (200, body) @@ -183,28 +182,30 @@ class FakeHTTPClient(fakes.FakeClient): def get(self, **kw): body = { "version": { - "id": "v2.0", - "status": "beta", - "updated": "2011-11-19T00:00:00Z", - "links": [ - {"rel": "self", - "href": "http://127.0.0.1:35357/v2.0/"}, - {"rel": "describedby", - "type": "text/html", - "href": "http://docs.openstack.org/" - "api/openstack-identity-service/2.0/content/"}, - {"rel": "describedby", - "type": "application/pdf", - "href": "http://docs.openstack.org/api/" - "openstack-identity-service/2.0/identity-dev-guide-2.0.pdf"}, - {"rel": "describedby", - "type": "application/vnd.sun.wadl+xml", - "href": "http://127.0.0.1:35357/v2.0/identity-admin.wadl"}], - "media-types": [ - {"base": "application/xml", - "type": "application/vnd.openstack.identity-v2.0+xml"}, - {"base": "application/json", - "type": "application/vnd.openstack.identity-v2.0+json"}] + "id": "v2.0", + "status": "beta", + "updated": "2011-11-19T00:00:00Z", + "links": [ + {"rel": "self", + "href": "http://127.0.0.1:35357/v2.0/"}, + {"rel": "describedby", + "type": "text/html", + "href": "http://docs.openstack.org/" + "api/openstack-identity-service/2.0/content/"}, + {"rel": "describedby", + "type": "application/pdf", + "href": "http://docs.openstack.org/api/" + "openstack-identity-service/2.0/" + "identity-dev-guide-2.0.pdf"}, + {"rel": "describedby", + "type": "application/vnd.sun.wadl+xml", + "href": + "http://127.0.0.1:35357/v2.0/identity-admin.wadl"}], + "media-types": [ + {"base": "application/xml", + "type": "application/vnd.openstack.identity-v2.0+xml"}, + {"base": "application/json", + "type": "application/vnd.openstack.identity-v2.0+json"}] } } return (200, body) @@ -418,14 +419,14 @@ class FakeHTTPClient(fakes.FakeClient): def get_OS_KSADM_services(self, **kw): body = { "OS-KSADM:services": [ - {"description": None, - "type": "compute", - "id": "1", - "name": "service1"}, - {"description": None, - "type": "identity", - "id": "2", - "name": "service2"}] + {"description": None, + "type": "compute", + "id": "1", + "name": "service1"}, + {"description": None, + "type": "identity", + "id": "2", + "name": "service2"}] } return (200, body) diff --git a/keystoneclient/tests/v2_0/test_access.py b/keystoneclient/tests/v2_0/test_access.py index 6aacf2d..548edcf 100644 --- a/keystoneclient/tests/v2_0/test_access.py +++ b/keystoneclient/tests/v2_0/test_access.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -22,6 +20,7 @@ from keystoneclient.tests import client_fixtures as token_data from keystoneclient.tests.v2_0 import client_fixtures from keystoneclient.tests.v2_0 import utils + UNSCOPED_TOKEN = client_fixtures.UNSCOPED_TOKEN PROJECT_SCOPED_TOKEN = client_fixtures.PROJECT_SCOPED_TOKEN @@ -43,6 +42,8 @@ class AccessInfoTest(utils.TestCase, testresources.ResourcedTestCase): self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') + self.assertEqual(auth_ref.role_names, []) + self.assertEqual(auth_ref.tenant_name, None) self.assertEqual(auth_ref.tenant_id, None) @@ -83,6 +84,8 @@ class AccessInfoTest(utils.TestCase, testresources.ResourcedTestCase): self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') + self.assertEqual(auth_ref.role_names, ['Member']) + self.assertEqual(auth_ref.tenant_name, 'exampleproject') self.assertEqual(auth_ref.tenant_id, '225da22d3ce34b15877ea70b2a575f58') @@ -115,6 +118,7 @@ class AccessInfoTest(utils.TestCase, testresources.ResourcedTestCase): self.assertEqual(auth_ref.project_domain_name, 'Default') self.assertEqual(auth_ref.user_domain_id, 'default') self.assertEqual(auth_ref.user_domain_name, 'Default') + self.assertEqual(auth_ref.role_names, ['role1', 'role2']) self.assertFalse(auth_ref.scoped) def test_grizzly_token(self): @@ -128,6 +132,7 @@ class AccessInfoTest(utils.TestCase, testresources.ResourcedTestCase): self.assertEqual(auth_ref.project_domain_name, 'Default') self.assertEqual(auth_ref.user_domain_id, 'default') self.assertEqual(auth_ref.user_domain_name, 'Default') + self.assertEqual(auth_ref.role_names, ['role1', 'role2']) def load_tests(loader, tests, pattern): diff --git a/keystoneclient/tests/v2_0/test_auth.py b/keystoneclient/tests/v2_0/test_auth.py index 98a3380..52379ae 100644 --- a/keystoneclient/tests/v2_0/test_auth.py +++ b/keystoneclient/tests/v2_0/test_auth.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -16,6 +14,7 @@ import datetime import json import httpretty +import six from keystoneclient import exceptions from keystoneclient.openstack.common import jsonutils @@ -170,7 +169,10 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase): cl = client.Client(auth_url=self.TEST_URL, token=fake_token) - body = jsonutils.loads(httpretty.last_request().body) + body = httpretty.last_request().body + if six.PY3: + body = body.decode('utf-8') + body = jsonutils.loads(body) self.assertEqual(body['auth']['token']['id'], fake_token) resp, body = cl.get(fake_url) diff --git a/keystoneclient/tests/v2_0/test_client.py b/keystoneclient/tests/v2_0/test_client.py index b7f5354..d96eeb8 100644 --- a/keystoneclient/tests/v2_0/test_client.py +++ b/keystoneclient/tests/v2_0/test_client.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v2_0/test_discovery.py b/keystoneclient/tests/v2_0/test_discovery.py index 2ad23c7..a3192c9 100644 --- a/keystoneclient/tests/v2_0/test_discovery.py +++ b/keystoneclient/tests/v2_0/test_discovery.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v2_0/test_ec2.py b/keystoneclient/tests/v2_0/test_ec2.py index dc67bdb..dbdaadd 100644 --- a/keystoneclient/tests/v2_0/test_ec2.py +++ b/keystoneclient/tests/v2_0/test_ec2.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -40,7 +38,7 @@ class EC2Tests(utils.TestCase): 'OS-EC2'], json=resp_body) cred = self.client.ec2.create(user_id, tenant_id) - self.assertTrue(isinstance(cred, ec2.EC2)) + self.assertIsInstance(cred, ec2.EC2) self.assertEqual(cred.tenant_id, tenant_id) self.assertEqual(cred.enabled, True) self.assertEqual(cred.access, 'access') @@ -64,7 +62,7 @@ class EC2Tests(utils.TestCase): 'OS-EC2', 'access'], json=resp_body) cred = self.client.ec2.get(user_id, 'access') - self.assertTrue(isinstance(cred, ec2.EC2)) + self.assertIsInstance(cred, ec2.EC2) self.assertEqual(cred.tenant_id, tenant_id) self.assertEqual(cred.enabled, True) self.assertEqual(cred.access, 'access') diff --git a/keystoneclient/tests/v2_0/test_endpoints.py b/keystoneclient/tests/v2_0/test_endpoints.py index d0f85e7..66513eb 100644 --- a/keystoneclient/tests/v2_0/test_endpoints.py +++ b/keystoneclient/tests/v2_0/test_endpoints.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -71,7 +69,7 @@ class EndpointTests(utils.TestCase): internalurl=req_body['endpoint']['internalurl'], service_id=req_body['endpoint']['service_id'] ) - self.assertTrue(isinstance(endpoint, endpoints.Endpoint)) + self.assertIsInstance(endpoint, endpoints.Endpoint) self.assertRequestBodyIs(json=req_body) @httpretty.activate @@ -84,5 +82,5 @@ class EndpointTests(utils.TestCase): self.stub_url(httpretty.GET, ['endpoints'], json=self.TEST_ENDPOINTS) endpoint_list = self.client.endpoints.list() - [self.assertTrue(isinstance(r, endpoints.Endpoint)) + [self.assertIsInstance(r, endpoints.Endpoint) for r in endpoint_list] diff --git a/keystoneclient/tests/v2_0/test_roles.py b/keystoneclient/tests/v2_0/test_roles.py index 72b4d44..358d7a4 100644 --- a/keystoneclient/tests/v2_0/test_roles.py +++ b/keystoneclient/tests/v2_0/test_roles.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -53,7 +51,7 @@ class RoleTests(utils.TestCase): role = self.client.roles.create(req_body['role']['name']) self.assertRequestBodyIs(json=req_body) - self.assertTrue(isinstance(role, roles.Role)) + self.assertIsInstance(role, roles.Role) self.assertEqual(role.id, 3) self.assertEqual(role.name, req_body['role']['name']) @@ -68,7 +66,7 @@ class RoleTests(utils.TestCase): json={'role': self.TEST_ROLES['roles']['values'][0]}) role = self.client.roles.get(1) - self.assertTrue(isinstance(role, roles.Role)) + self.assertIsInstance(role, roles.Role) self.assertEqual(role.id, 1) self.assertEqual(role.name, 'admin') @@ -78,7 +76,7 @@ class RoleTests(utils.TestCase): json=self.TEST_ROLES) role_list = self.client.roles.list() - [self.assertTrue(isinstance(r, roles.Role)) for r in role_list] + [self.assertIsInstance(r, roles.Role) for r in role_list] @httpretty.activate def test_roles_for_user(self): @@ -86,7 +84,7 @@ class RoleTests(utils.TestCase): json=self.TEST_ROLES) role_list = self.client.roles.roles_for_user('foo') - [self.assertTrue(isinstance(r, roles.Role)) for r in role_list] + [self.assertIsInstance(r, roles.Role) for r in role_list] @httpretty.activate def test_roles_for_user_tenant(self): @@ -94,7 +92,7 @@ class RoleTests(utils.TestCase): 'roles'], json=self.TEST_ROLES) role_list = self.client.roles.roles_for_user('foo', 'barrr') - [self.assertTrue(isinstance(r, roles.Role)) for r in role_list] + [self.assertIsInstance(r, roles.Role) for r in role_list] @httpretty.activate def test_add_user_role(self): diff --git a/keystoneclient/tests/v2_0/test_service_catalog.py b/keystoneclient/tests/v2_0/test_service_catalog.py index 2379016..21f2b88 100644 --- a/keystoneclient/tests/v2_0/test_service_catalog.py +++ b/keystoneclient/tests/v2_0/test_service_catalog.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v2_0/test_services.py b/keystoneclient/tests/v2_0/test_services.py index 0b539a9..8123102 100644 --- a/keystoneclient/tests/v2_0/test_services.py +++ b/keystoneclient/tests/v2_0/test_services.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -63,7 +61,7 @@ class ServiceTests(utils.TestCase): req_body['OS-KSADM:service']['name'], req_body['OS-KSADM:service']['type'], req_body['OS-KSADM:service']['description']) - self.assertTrue(isinstance(service, services.Service)) + self.assertIsInstance(service, services.Service) self.assertEqual(service.id, 3) self.assertEqual(service.name, req_body['OS-KSADM:service']['name']) self.assertRequestBodyIs(json=req_body) @@ -83,7 +81,7 @@ class ServiceTests(utils.TestCase): json={'OS-KSADM:service': test_services}) service = self.client.services.get(1) - self.assertTrue(isinstance(service, services.Service)) + self.assertIsInstance(service, services.Service) self.assertEqual(service.id, 1) self.assertEqual(service.name, 'nova') self.assertEqual(service.type, 'compute') @@ -94,5 +92,5 @@ class ServiceTests(utils.TestCase): json=self.TEST_SERVICES) service_list = self.client.services.list() - [self.assertTrue(isinstance(r, services.Service)) + [self.assertIsInstance(r, services.Service) for r in service_list] diff --git a/keystoneclient/tests/v2_0/test_shell.py b/keystoneclient/tests/v2_0/test_shell.py index 3ae49e5..645ab65 100644 --- a/keystoneclient/tests/v2_0/test_shell.py +++ b/keystoneclient/tests/v2_0/test_shell.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v2_0/test_tenants.py b/keystoneclient/tests/v2_0/test_tenants.py index be25514..60e1c05 100644 --- a/keystoneclient/tests/v2_0/test_tenants.py +++ b/keystoneclient/tests/v2_0/test_tenants.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -82,7 +80,7 @@ class TenantTests(utils.TestCase): req_body['tenant']['enabled'], extravalue01=req_body['tenant']['extravalue01'], name="dont overwrite priors") - self.assertTrue(isinstance(tenant, tenants.Tenant)) + self.assertIsInstance(tenant, tenants.Tenant) self.assertEqual(tenant.id, 4) self.assertEqual(tenant.name, "tenantX") self.assertEqual(tenant.description, "Like tenant 9, but better.") @@ -125,7 +123,7 @@ class TenantTests(utils.TestCase): self.stub_url(httpretty.GET, ['tenants', '1'], json=resp) t = self.client.tenants.get(1) - self.assertTrue(isinstance(t, tenants.Tenant)) + self.assertIsInstance(t, tenants.Tenant) self.assertEqual(t.id, 1) self.assertEqual(t.name, 'admin') @@ -134,7 +132,7 @@ class TenantTests(utils.TestCase): self.stub_url(httpretty.GET, ['tenants'], json=self.TEST_TENANTS) tenant_list = self.client.tenants.list() - [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list] + [self.assertIsInstance(t, tenants.Tenant) for t in tenant_list] @httpretty.activate def test_list_limit(self): @@ -142,7 +140,7 @@ class TenantTests(utils.TestCase): tenant_list = self.client.tenants.list(limit=1) self.assertQueryStringIs('limit=1') - [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list] + [self.assertIsInstance(t, tenants.Tenant) for t in tenant_list] @httpretty.activate def test_list_marker(self): @@ -150,7 +148,7 @@ class TenantTests(utils.TestCase): tenant_list = self.client.tenants.list(marker=1) self.assertQueryStringIs('marker=1') - [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list] + [self.assertIsInstance(t, tenants.Tenant) for t in tenant_list] @httpretty.activate def test_list_limit_marker(self): @@ -158,7 +156,7 @@ class TenantTests(utils.TestCase): tenant_list = self.client.tenants.list(limit=1, marker=1) self.assertQueryStringIs('marker=1&limit=1') - [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list] + [self.assertIsInstance(t, tenants.Tenant) for t in tenant_list] @httpretty.activate def test_update(self): @@ -191,7 +189,7 @@ class TenantTests(utils.TestCase): req_body['tenant']['enabled'], extravalue01=req_body['tenant']['extravalue01'], name="dont overwrite priors") - self.assertTrue(isinstance(tenant, tenants.Tenant)) + self.assertIsInstance(tenant, tenants.Tenant) self.assertRequestBodyIs(json=req_body) self.assertEqual(tenant.id, 4) self.assertEqual(tenant.name, "tenantX") @@ -223,7 +221,7 @@ class TenantTests(utils.TestCase): req_body['tenant']['name'], req_body['tenant']['description'], req_body['tenant']['enabled']) - self.assertTrue(isinstance(tenant, tenants.Tenant)) + self.assertIsInstance(tenant, tenants.Tenant) self.assertRequestBodyIs(json=req_body) self.assertEqual(tenant.id, 4) self.assertEqual(tenant.name, "tenantX") @@ -263,7 +261,7 @@ class TenantTests(utils.TestCase): tenant = self.client.tenants.resource_class(self.client.tenants, req_body['tenant']) tenant.add_user('foo', 'barrr') - self.assertTrue(isinstance(tenant, tenants.Tenant)) + self.assertIsInstance(tenant, tenants.Tenant) @httpretty.activate def test_tenant_remove_user(self): @@ -284,4 +282,4 @@ class TenantTests(utils.TestCase): tenant = self.client.tenants.resource_class(self.client.tenants, req_body['tenant']) tenant.remove_user('foo', 'barrr') - self.assertTrue(isinstance(tenant, tenants.Tenant)) + self.assertIsInstance(tenant, tenants.Tenant) diff --git a/keystoneclient/tests/v2_0/test_tokens.py b/keystoneclient/tests/v2_0/test_tokens.py index b623ada..3352b42 100644 --- a/keystoneclient/tests/v2_0/test_tokens.py +++ b/keystoneclient/tests/v2_0/test_tokens.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v2_0/test_users.py b/keystoneclient/tests/v2_0/test_users.py index d11e038..25dba42 100644 --- a/keystoneclient/tests/v2_0/test_users.py +++ b/keystoneclient/tests/v2_0/test_users.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -70,7 +68,7 @@ class UserTests(utils.TestCase): req_body['user']['email'], tenant_id=req_body['user']['tenantId'], enabled=req_body['user']['enabled']) - self.assertTrue(isinstance(user, users.User)) + self.assertIsInstance(user, users.User) self.assertEqual(user.id, 3) self.assertEqual(user.name, "gabriel") self.assertEqual(user.email, "test@example.com") @@ -105,7 +103,7 @@ class UserTests(utils.TestCase): req_body['user']['password'], tenant_id=req_body['user']['tenantId'], enabled=req_body['user']['enabled']) - self.assertTrue(isinstance(user, users.User)) + self.assertIsInstance(user, users.User) self.assertEqual(user.id, 3) self.assertEqual(user.name, "gabriel") self.assertRequestBodyIs(json=req_body) @@ -121,7 +119,7 @@ class UserTests(utils.TestCase): json={'user': self.TEST_USERS['users']['values'][0]}) u = self.client.users.get(1) - self.assertTrue(isinstance(u, users.User)) + self.assertIsInstance(u, users.User) self.assertEqual(u.id, 1) self.assertEqual(u.name, 'admin') @@ -130,7 +128,7 @@ class UserTests(utils.TestCase): self.stub_url(httpretty.GET, ['users'], json=self.TEST_USERS) user_list = self.client.users.list() - [self.assertTrue(isinstance(u, users.User)) for u in user_list] + [self.assertIsInstance(u, users.User) for u in user_list] @httpretty.activate def test_list_limit(self): @@ -139,7 +137,7 @@ class UserTests(utils.TestCase): user_list = self.client.users.list(limit=1) self.assertEqual(httpretty.last_request().querystring, {'limit': ['1']}) - [self.assertTrue(isinstance(u, users.User)) for u in user_list] + [self.assertIsInstance(u, users.User) for u in user_list] @httpretty.activate def test_list_marker(self): @@ -148,7 +146,7 @@ class UserTests(utils.TestCase): user_list = self.client.users.list(marker='foo') self.assertDictEqual(httpretty.last_request().querystring, {'marker': ['foo']}) - [self.assertTrue(isinstance(u, users.User)) for u in user_list] + [self.assertIsInstance(u, users.User) for u in user_list] @httpretty.activate def test_list_limit_marker(self): @@ -158,7 +156,7 @@ class UserTests(utils.TestCase): self.assertDictEqual(httpretty.last_request().querystring, {'marker': ['foo'], 'limit': ['1']}) - [self.assertTrue(isinstance(u, users.User)) for u in user_list] + [self.assertIsInstance(u, users.User) for u in user_list] @httpretty.activate def test_update(self): diff --git a/keystoneclient/tests/v2_0/utils.py b/keystoneclient/tests/v2_0/utils.py index 238543f..f4c8911 100644 --- a/keystoneclient/tests/v2_0/utils.py +++ b/keystoneclient/tests/v2_0/utils.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -17,6 +15,7 @@ import httpretty from keystoneclient.tests import utils from keystoneclient.v2_0 import client + TestResponse = utils.TestResponse diff --git a/keystoneclient/tests/v3/client_fixtures.py b/keystoneclient/tests/v3/client_fixtures.py index 8970dee..08dd267 100644 --- a/keystoneclient/tests/v3/client_fixtures.py +++ b/keystoneclient/tests/v3/client_fixtures.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -128,6 +126,22 @@ DOMAIN_SCOPED_TOKEN = { }, 'id': 'c4da488862bd435c9e6c0275a0d0e49a', 'name': 'exampleuser', + 'roles': [ + { + "id": "76e72a", + "links": { + "self": "http://identity:35357/v3/roles/76e72a" + }, + "name": "admin" + }, + { + "id": "f4f392", + "links": { + "self": "http://identity:35357/v3/roles/f4f392" + }, + "name": "member" + } + ], }, 'domain': { 'id': '8e9283b7ba0b1038840c3842058b86ab', @@ -231,6 +245,22 @@ PROJECT_SCOPED_TOKEN = { }, 'id': 'c4da488862bd435c9e6c0275a0d0e49a', 'name': 'exampleuser', + 'roles': [ + { + "id": "76e72a", + "links": { + "self": "http://identity:35357/v3/roles/76e72a" + }, + "name": "admin" + }, + { + "id": "f4f392", + "links": { + "self": "http://identity:35357/v3/roles/f4f392" + }, + "name": "member" + } + ], }, 'project': { 'domain': { @@ -269,7 +299,23 @@ AUTH_RESPONSE_BODY = { 'name': 'aDomain' }, 'id': '567', - 'name': 'test' + 'name': 'test', + 'roles': [ + { + "id": "76e72a", + "links": { + "self": "http://identity:35357/v3/roles/76e72a" + }, + "name": "admin" + }, + { + "id": "f4f392", + "links": { + "self": "http://identity:35357/v3/roles/f4f392" + }, + "name": "member" + } + ], }, 'issued_at': '2010-10-31T03:32:15-05:00', 'catalog': [{ diff --git a/keystoneclient/tests/v3/test_access.py b/keystoneclient/tests/v3/test_access.py index 1ade338..dfc7b3c 100644 --- a/keystoneclient/tests/v3/test_access.py +++ b/keystoneclient/tests/v3/test_access.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -19,6 +17,7 @@ from keystoneclient.openstack.common import timeutils from keystoneclient.tests.v3 import client_fixtures from keystoneclient.tests.v3 import utils + TOKEN_RESPONSE = utils.TestResponse({ "headers": client_fixtures.AUTH_RESPONSE_HEADERS }) @@ -42,6 +41,8 @@ class AccessInfoTest(utils.TestCase): self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') + self.assertEqual(auth_ref.role_names, []) + self.assertIsNone(auth_ref.project_name) self.assertIsNone(auth_ref.project_id) @@ -84,6 +85,8 @@ class AccessInfoTest(utils.TestCase): self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') + self.assertEqual(auth_ref.role_names, ['admin', 'member']) + self.assertEqual(auth_ref.domain_name, 'anotherdomain') self.assertEqual(auth_ref.domain_id, '8e9283b7ba0b1038840c3842058b86ab') @@ -115,6 +118,8 @@ class AccessInfoTest(utils.TestCase): self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') + self.assertEqual(auth_ref.role_names, ['admin', 'member']) + self.assertIsNone(auth_ref.domain_name) self.assertIsNone(auth_ref.domain_id) diff --git a/keystoneclient/tests/v3/test_auth.py b/keystoneclient/tests/v3/test_auth.py index 9c02970..f4397c1 100644 --- a/keystoneclient/tests/v3/test_auth.py +++ b/keystoneclient/tests/v3/test_auth.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -13,6 +11,7 @@ # under the License. import httpretty +import six from keystoneclient import exceptions from keystoneclient.openstack.common import jsonutils @@ -237,7 +236,10 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase): cl = client.Client(auth_url=self.TEST_URL, token=fake_token) - body = jsonutils.loads(httpretty.last_request().body) + body = httpretty.last_request().body + if six.PY3: + body = body.decode('utf-8') + body = jsonutils.loads(body) self.assertEqual(body['auth']['identity']['token']['id'], fake_token) resp, body = cl.get(fake_url) diff --git a/keystoneclient/tests/v3/test_client.py b/keystoneclient/tests/v3/test_client.py index f9f63e0..1ea14d4 100644 --- a/keystoneclient/tests/v3/test_client.py +++ b/keystoneclient/tests/v3/test_client.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_credentials.py b/keystoneclient/tests/v3/test_credentials.py index be99033..d6ad455 100644 --- a/keystoneclient/tests/v3/test_credentials.py +++ b/keystoneclient/tests/v3/test_credentials.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_discover.py b/keystoneclient/tests/v3/test_discover.py index 56040f1..19be82d 100644 --- a/keystoneclient/tests/v3/test_discover.py +++ b/keystoneclient/tests/v3/test_discover.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_domains.py b/keystoneclient/tests/v3/test_domains.py index f70c67d..5482107 100644 --- a/keystoneclient/tests/v3/test_domains.py +++ b/keystoneclient/tests/v3/test_domains.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_endpoints.py b/keystoneclient/tests/v3/test_endpoints.py index 050a646..5319373 100644 --- a/keystoneclient/tests/v3/test_endpoints.py +++ b/keystoneclient/tests/v3/test_endpoints.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_groups.py b/keystoneclient/tests/v3/test_groups.py index 62d3667..74a4a4c 100644 --- a/keystoneclient/tests/v3/test_groups.py +++ b/keystoneclient/tests/v3/test_groups.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -46,7 +44,7 @@ class GroupTests(utils.TestCase, utils.CrudTests): returned_list = self.manager.list(user=user_id) self.assertEqual(len(ref_list), len(returned_list)) - [self.assertTrue(isinstance(r, self.model)) for r in returned_list] + [self.assertIsInstance(r, self.model) for r in returned_list] @httpretty.activate def test_list_groups_for_domain(self): @@ -59,7 +57,7 @@ class GroupTests(utils.TestCase, utils.CrudTests): returned_list = self.manager.list(domain=domain_id) self.assertTrue(len(ref_list), len(returned_list)) - [self.assertTrue(isinstance(r, self.model)) for r in returned_list] + [self.assertIsInstance(r, self.model) for r in returned_list] self.assertEqual(httpretty.last_request().querystring, {'domain_id': [domain_id]}) diff --git a/keystoneclient/tests/v3/test_policies.py b/keystoneclient/tests/v3/test_policies.py index a692d1c..45bce71 100644 --- a/keystoneclient/tests/v3/test_policies.py +++ b/keystoneclient/tests/v3/test_policies.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_projects.py b/keystoneclient/tests/v3/test_projects.py index 79bf1b9..1d4b2d7 100644 --- a/keystoneclient/tests/v3/test_projects.py +++ b/keystoneclient/tests/v3/test_projects.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -46,7 +44,7 @@ class ProjectTests(utils.TestCase, utils.CrudTests): returned_list = self.manager.list(user=user_id) self.assertEqual(len(ref_list), len(returned_list)) - [self.assertTrue(isinstance(r, self.model)) for r in returned_list] + [self.assertIsInstance(r, self.model) for r in returned_list] @httpretty.activate def test_list_projects_for_domain(self): @@ -58,7 +56,7 @@ class ProjectTests(utils.TestCase, utils.CrudTests): returned_list = self.manager.list(domain=domain_id) self.assertEqual(len(ref_list), len(returned_list)) - [self.assertTrue(isinstance(r, self.model)) for r in returned_list] + [self.assertIsInstance(r, self.model) for r in returned_list] self.assertEqual(httpretty.last_request().querystring, {'domain_id': [domain_id]}) diff --git a/keystoneclient/tests/v3/test_roles.py b/keystoneclient/tests/v3/test_roles.py index cc120e2..9e3b817 100644 --- a/keystoneclient/tests/v3/test_roles.py +++ b/keystoneclient/tests/v3/test_roles.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -70,7 +68,7 @@ class RoleTests(utils.TestCase, utils.CrudTests): self.stub_entity(httpretty.GET, ['domains', domain_id, 'users', user_id, - self.collection_key], entity=ref_list) + self.collection_key], entity=ref_list) self.manager.list(domain=domain_id, user=user_id) diff --git a/keystoneclient/tests/v3/test_service_catalog.py b/keystoneclient/tests/v3/test_service_catalog.py index a82b9c1..87853e1 100644 --- a/keystoneclient/tests/v3/test_service_catalog.py +++ b/keystoneclient/tests/v3/test_service_catalog.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_services.py b/keystoneclient/tests/v3/test_services.py index 5b0e91d..d271afe 100644 --- a/keystoneclient/tests/v3/test_services.py +++ b/keystoneclient/tests/v3/test_services.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at diff --git a/keystoneclient/tests/v3/test_trusts.py b/keystoneclient/tests/v3/test_trusts.py index 9c3d953..90d2196 100644 --- a/keystoneclient/tests/v3/test_trusts.py +++ b/keystoneclient/tests/v3/test_trusts.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 -# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at diff --git a/keystoneclient/tests/v3/test_users.py b/keystoneclient/tests/v3/test_users.py index e2ee121..613e6c9 100644 --- a/keystoneclient/tests/v3/test_users.py +++ b/keystoneclient/tests/v3/test_users.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -65,7 +63,7 @@ class UserTests(utils.TestCase, utils.CrudTests): returned_list = self.manager.list(group=group_id) self.assertEqual(len(ref_list), len(returned_list)) - [self.assertTrue(isinstance(r, self.model)) for r in returned_list] + [self.assertIsInstance(r, self.model) for r in returned_list] @httpretty.activate def test_check_user_in_group(self): @@ -115,7 +113,7 @@ class UserTests(utils.TestCase, utils.CrudTests): params = utils.parameterize(param_ref) returned = self.manager.create(**params) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in ref: self.assertEqual( getattr(returned, attr), @@ -142,7 +140,7 @@ class UserTests(utils.TestCase, utils.CrudTests): params = utils.parameterize(param_ref) returned = self.manager.create(**params) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in ref: self.assertEqual( getattr(returned, attr), @@ -168,7 +166,7 @@ class UserTests(utils.TestCase, utils.CrudTests): params = utils.parameterize(param_ref) returned = self.manager.update(ref['id'], **params) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in ref: self.assertEqual( getattr(returned, attr), @@ -192,7 +190,7 @@ class UserTests(utils.TestCase, utils.CrudTests): params = utils.parameterize(param_ref) returned = self.manager.update(ref['id'], **params) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in ref: self.assertEqual( getattr(returned, attr), diff --git a/keystoneclient/tests/v3/utils.py b/keystoneclient/tests/v3/utils.py index 1935691..f7b776b 100644 --- a/keystoneclient/tests/v3/utils.py +++ b/keystoneclient/tests/v3/utils.py @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at @@ -21,6 +19,7 @@ from keystoneclient.openstack.common import jsonutils from keystoneclient.tests import utils from keystoneclient.v3 import client + TestResponse = utils.TestResponse @@ -154,6 +153,7 @@ class CrudTests(object): def new_ref(self, **kwargs): kwargs.setdefault('id', uuid.uuid4().hex) + kwargs.setdefault(uuid.uuid4().hex, uuid.uuid4().hex) return kwargs def encode(self, entity): @@ -201,7 +201,7 @@ class CrudTests(object): self.stub_entity(httpretty.POST, entity=req_ref, status=201) returned = self.manager.create(**parameterize(manager_ref)) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in req_ref: self.assertEqual( getattr(returned, attr), @@ -216,17 +216,14 @@ class CrudTests(object): self.stub_entity(httpretty.GET, id=ref['id'], entity=ref) returned = self.manager.get(ref['id']) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in ref: self.assertEqual( getattr(returned, attr), ref[attr], 'Expected different %s' % attr) - @httpretty.activate - def test_list(self, ref_list=None, expected_path=None, **filter_kwargs): - ref_list = ref_list or [self.new_ref(), self.new_ref()] - + def _get_expected_path(self, expected_path=None): if not expected_path: if self.path_prefix: expected_path = 'v3/%s/%s' % (self.path_prefix, @@ -234,13 +231,33 @@ class CrudTests(object): else: expected_path = 'v3/%s' % self.collection_key + return expected_path + + @httpretty.activate + def test_list(self, ref_list=None, expected_path=None, **filter_kwargs): + ref_list = ref_list or [self.new_ref(), self.new_ref()] + expected_path = self._get_expected_path(expected_path) + httpretty.register_uri(httpretty.GET, urlparse.urljoin(self.TEST_URL, expected_path), body=jsonutils.dumps(self.encode(ref_list))) returned_list = self.manager.list(**filter_kwargs) self.assertEqual(len(ref_list), len(returned_list)) - [self.assertTrue(isinstance(r, self.model)) for r in returned_list] + [self.assertIsInstance(r, self.model) for r in returned_list] + + @httpretty.activate + def test_list_params(self): + ref_list = [self.new_ref()] + filter_kwargs = {uuid.uuid4().hex: uuid.uuid4().hex} + expected_path = self._get_expected_path() + + httpretty.register_uri(httpretty.GET, + urlparse.urljoin(self.TEST_URL, expected_path), + body=jsonutils.dumps(self.encode(ref_list))) + + self.manager.list(**filter_kwargs) + self.assertQueryStringContains(**filter_kwargs) @httpretty.activate def test_find(self, ref=None): @@ -250,7 +267,7 @@ class CrudTests(object): self.stub_entity(httpretty.GET, entity=ref_list) returned = self.manager.find(name=getattr(ref, 'name', None)) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in ref: self.assertEqual( getattr(returned, attr), @@ -276,7 +293,7 @@ class CrudTests(object): req_ref.pop('id') returned = self.manager.update(ref['id'], **parameterize(req_ref)) - self.assertTrue(isinstance(returned, self.model)) + self.assertIsInstance(returned, self.model) for attr in ref: self.assertEqual( getattr(returned, attr), |
