Convert tests to HTTPretty and reorganize

There are a lot of problems with the current means of mocking. Most
annoyingly is that we cannot differ the call to the request library by
even a single optional header or whitespace difference without breaking
the mock. HTTPretty does a better job of this because it only cares
about what is transmitted over the socket.

Rewrite tests so that they no longer do string comparisons of JSON encoded
dictionaries. This meant that they had to order the dictionary before
encoding and would fail tests where the ordering was not followed.

In the process of this I reorganized the inheritance of the
utils.TestCase object so that there is a clear separation between the
data stored on the V2 and V3 base test objects.

Change-Id: I590df65adb1d2177b4be4e016708db05131b6880
This commit is contained in:
Jamie Lennox
2013-08-29 16:16:56 +10:00
committed by Jamie Lennox
parent 86c4c2d57b
commit ceb65b04e3
35 changed files with 897 additions and 2080 deletions

View File

@@ -13,6 +13,7 @@
# under the License. # under the License.
from keystoneclient import base from keystoneclient import base
from keystoneclient.v2_0 import client
from keystoneclient.v2_0 import roles from keystoneclient.v2_0 import roles
from tests import utils from tests import utils
@@ -35,6 +36,12 @@ class BaseTest(utils.TestCase):
self.assertEqual(base.getid(TmpObject), 4) self.assertEqual(base.getid(TmpObject), 4)
def test_resource_lazy_getattr(self): def test_resource_lazy_getattr(self):
self.client = client.Client(username=self.TEST_USER,
token=self.TEST_TOKEN,
tenant_name=self.TEST_TENANT_NAME,
auth_url='http://127.0.0.1:5000',
endpoint='http://127.0.0.1:5000')
self.client.get = self.mox.CreateMockAnything() self.client.get = self.mox.CreateMockAnything()
self.client.get('/OS-KSADM/roles/1').AndRaise(AttributeError) self.client.get('/OS-KSADM/roles/1').AndRaise(AttributeError)
self.mox.ReplayAll() self.mox.ReplayAll()
@@ -78,6 +85,11 @@ class ManagerTest(utils.TestCase):
def setUp(self): def setUp(self):
super(ManagerTest, self).setUp() super(ManagerTest, self).setUp()
self.client = client.Client(username=self.TEST_USER,
token=self.TEST_TOKEN,
tenant_name=self.TEST_TENANT_NAME,
auth_url='http://127.0.0.1:5000',
endpoint='http://127.0.0.1:5000')
self.mgr = base.Manager(self.client) self.mgr = base.Manager(self.client)
self.mgr.resource_class = base.Resource self.mgr.resource_class = base.Resource

View File

@@ -14,11 +14,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import json
import mock
import httpretty import httpretty
import requests
import testtools import testtools
from testtools import matchers from testtools import matchers
@@ -26,12 +22,7 @@ from keystoneclient import exceptions
from keystoneclient import httpclient from keystoneclient import httpclient
from tests import utils from tests import utils
RESPONSE_BODY = '{"hi": "there"}'
FAKE_RESPONSE = utils.TestResponse({
"status_code": 200,
"text": '{"hi": "there"}',
})
MOCK_REQUEST = mock.Mock(return_value=(FAKE_RESPONSE))
def get_client(): def get_client():
@@ -61,6 +52,8 @@ class FakeLog(object):
class ClientTest(utils.TestCase): class ClientTest(utils.TestCase):
TEST_URL = 'http://127.0.0.1:5000/hi'
def test_unauthorized_client_requests(self): def test_unauthorized_client_requests(self):
cl = get_client() cl = get_client()
self.assertRaises(exceptions.AuthorizationFailure, cl.get, '/hi') self.assertRaises(exceptions.AuthorizationFailure, cl.get, '/hi')
@@ -68,34 +61,34 @@ class ClientTest(utils.TestCase):
self.assertRaises(exceptions.AuthorizationFailure, cl.put, '/hi') self.assertRaises(exceptions.AuthorizationFailure, cl.put, '/hi')
self.assertRaises(exceptions.AuthorizationFailure, cl.delete, '/hi') self.assertRaises(exceptions.AuthorizationFailure, cl.delete, '/hi')
@httpretty.activate
def test_get(self): def test_get(self):
cl = get_authed_client() cl = get_authed_client()
with mock.patch.object(requests, "request", MOCK_REQUEST): self.stub_url(httpretty.GET, body=RESPONSE_BODY)
with mock.patch('time.time', mock.Mock(return_value=1234)):
resp, body = cl.get("/hi")
headers = {"X-Auth-Token": "token",
"User-Agent": httpclient.USER_AGENT}
MOCK_REQUEST.assert_called_with(
"GET",
"http://127.0.0.1:5000/hi",
headers=headers,
**self.TEST_REQUEST_BASE)
# Automatic JSON parsing
self.assertEqual(body, {"hi": "there"})
resp, body = cl.get("/hi")
self.assertEqual(httpretty.last_request().method, 'GET')
self.assertEqual(httpretty.last_request().path, '/hi')
req_headers = httpretty.last_request().headers
self.assertEqual(req_headers.getheader('X-Auth-Token'), 'token')
self.assertEqual(req_headers.getheader('User-Agent'),
httpclient.USER_AGENT)
# Automatic JSON parsing
self.assertEqual(body, {"hi": "there"})
@httpretty.activate
def test_get_error_with_plaintext_resp(self): def test_get_error_with_plaintext_resp(self):
cl = get_authed_client() cl = get_authed_client()
self.stub_url(httpretty.GET, status=400,
body='Some evil plaintext string')
fake_err_response = utils.TestResponse({ self.assertRaises(exceptions.BadRequest, cl.get, '/hi')
"status_code": 400,
"text": 'Some evil plaintext string',
})
err_MOCK_REQUEST = mock.Mock(return_value=(fake_err_response))
with mock.patch.object(requests, "request", err_MOCK_REQUEST):
self.assertRaises(exceptions.BadRequest, cl.get, '/hi')
@httpretty.activate
def test_get_error_with_json_resp(self): def test_get_error_with_json_resp(self):
cl = get_authed_client() cl = get_authed_client()
err_response = { err_response = {
@@ -105,53 +98,45 @@ class ClientTest(utils.TestCase):
"message": "Error message string" "message": "Error message string"
} }
} }
fake_err_response = utils.TestResponse({ self.stub_url(httpretty.GET, status=400, json=err_response)
"status_code": 400, exc_raised = False
"text": json.dumps(err_response), try:
"headers": {"Content-Type": "application/json"}, cl.get('/hi')
}) except exceptions.BadRequest as exc:
err_MOCK_REQUEST = mock.Mock(return_value=(fake_err_response)) exc_raised = True
self.assertEqual(exc.message, "Error message string")
with mock.patch.object(requests, "request", err_MOCK_REQUEST): self.assertTrue(exc_raised, 'Exception not raised.')
exc_raised = False
try:
cl.get('/hi')
except exceptions.BadRequest as exc:
exc_raised = True
self.assertEqual(exc.message, "Error message string")
self.assertTrue(exc_raised, 'Exception not raised.')
@httpretty.activate
def test_post(self): def test_post(self):
cl = get_authed_client() cl = get_authed_client()
with mock.patch.object(requests, "request", MOCK_REQUEST): self.stub_url(httpretty.POST)
cl.post("/hi", body=[1, 2, 3]) cl.post("/hi", body=[1, 2, 3])
headers = {
"X-Auth-Token": "token",
"Content-Type": "application/json",
"User-Agent": httpclient.USER_AGENT
}
MOCK_REQUEST.assert_called_with(
"POST",
"http://127.0.0.1:5000/hi",
headers=headers,
data='[1, 2, 3]',
**self.TEST_REQUEST_BASE)
self.assertEqual(httpretty.last_request().method, 'POST')
self.assertEqual(httpretty.last_request().body, '[1, 2, 3]')
req_headers = httpretty.last_request().headers
self.assertEqual(req_headers.getheader('X-Auth-Token'), 'token')
self.assertEqual(req_headers.getheader('Content-Type'),
'application/json')
self.assertEqual(req_headers.getheader('User-Agent'),
httpclient.USER_AGENT)
@httpretty.activate
def test_forwarded_for(self): def test_forwarded_for(self):
ORIGINAL_IP = "10.100.100.1" ORIGINAL_IP = "10.100.100.1"
cl = httpclient.HTTPClient(username="username", password="password", cl = httpclient.HTTPClient(username="username", password="password",
tenant_id="tenant", auth_url="auth_test", tenant_id="tenant", auth_url="auth_test",
original_ip=ORIGINAL_IP) original_ip=ORIGINAL_IP)
with mock.patch.object(requests, "request", MOCK_REQUEST): self.stub_url(httpretty.GET)
cl.request('/', 'GET')
args, kwargs = MOCK_REQUEST.call_args cl.request(self.TEST_URL, 'GET')
self.assertIn( self.assertEqual(httpretty.last_request().headers['Forwarded'],
('Forwarded', "for=%s;by=%s" % (ORIGINAL_IP, "for=%s;by=%s" % (ORIGINAL_IP, httpclient.USER_AGENT))
httpclient.USER_AGENT)),
kwargs['headers'].items())
def test_client_deprecated(self): def test_client_deprecated(self):
# Can resolve symbols from the keystoneclient.client module. # Can resolve symbols from the keystoneclient.client module.
@@ -174,11 +159,6 @@ class BasicRequestTests(testtools.TestCase):
def setUp(self): def setUp(self):
super(BasicRequestTests, self).setUp() super(BasicRequestTests, self).setUp()
self.logger = FakeLog() self.logger = FakeLog()
httpretty.enable()
def tearDown(self):
httpretty.disable()
super(BasicRequestTests, self).tearDown()
def request(self, method='GET', response='Test Response', status=200, def request(self, method='GET', response='Test Response', status=200,
url=None, **kwargs): url=None, **kwargs):
@@ -190,10 +170,7 @@ class BasicRequestTests(testtools.TestCase):
return httpclient.request(url, method, debug=True, return httpclient.request(url, method, debug=True,
logger=self.logger, **kwargs) logger=self.logger, **kwargs)
@property @httpretty.activate
def last_request(self):
return httpretty.httpretty.last_request
def test_basic_params(self): def test_basic_params(self):
method = 'GET' method = 'GET'
response = 'Test Response' response = 'Test Response'
@@ -201,7 +178,7 @@ class BasicRequestTests(testtools.TestCase):
self.request(method=method, status=status, response=response) self.request(method=method, status=status, response=response)
self.assertEqual(self.last_request.method, method) self.assertEqual(httpretty.last_request().method, method)
self.assertThat(self.logger.debug_log, matchers.Contains('curl')) self.assertThat(self.logger.debug_log, matchers.Contains('curl'))
self.assertThat(self.logger.debug_log, matchers.Contains('-X %s' % self.assertThat(self.logger.debug_log, matchers.Contains('-X %s' %
@@ -211,18 +188,20 @@ class BasicRequestTests(testtools.TestCase):
self.assertThat(self.logger.debug_log, matchers.Contains(str(status))) self.assertThat(self.logger.debug_log, matchers.Contains(str(status)))
self.assertThat(self.logger.debug_log, matchers.Contains(response)) self.assertThat(self.logger.debug_log, matchers.Contains(response))
@httpretty.activate
def test_headers(self): def test_headers(self):
headers = {'key': 'val', 'test': 'other'} headers = {'key': 'val', 'test': 'other'}
self.request(headers=headers) self.request(headers=headers)
for k, v in headers.iteritems(): for k, v in headers.iteritems():
self.assertEqual(self.last_request.headers[k], v) self.assertEqual(httpretty.last_request().headers[k], v)
for header in headers.iteritems(): for header in headers.iteritems():
self.assertThat(self.logger.debug_log, self.assertThat(self.logger.debug_log,
matchers.Contains('-H "%s: %s"' % header)) matchers.Contains('-H "%s: %s"' % header))
@httpretty.activate
def test_body(self): def test_body(self):
data = "BODY DATA" data = "BODY DATA"
self.request(response=data) self.request(response=data)

View File

@@ -12,7 +12,6 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import mock import mock
import requests import requests
@@ -20,13 +19,15 @@ import requests
from keystoneclient import httpclient from keystoneclient import httpclient
from tests import utils from tests import utils
FAKE_RESPONSE = utils.TestResponse({ FAKE_RESPONSE = utils.TestResponse({
"status_code": 200, "status_code": 200,
"text": '{"hi": "there"}', "text": '{"hi": "there"}',
}) })
MOCK_REQUEST = mock.Mock(return_value=(FAKE_RESPONSE)) MOCK_REQUEST = mock.Mock(return_value=(FAKE_RESPONSE))
REQUEST_URL = 'https://127.0.0.1:5000/hi'
RESPONSE_BODY = '{"hi": "there"}'
def get_client(): def get_client():
cl = httpclient.HTTPClient(username="username", password="password", cl = httpclient.HTTPClient(username="username", password="password",
@@ -44,44 +45,49 @@ def get_authed_client():
class ClientTest(utils.TestCase): class ClientTest(utils.TestCase):
def setUp(self):
super(ClientTest, self).setUp()
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()
def test_get(self): def test_get(self):
cl = get_authed_client() cl = get_authed_client()
with mock.patch.object(requests, "request", MOCK_REQUEST): with mock.patch.object(requests, "request", MOCK_REQUEST):
with mock.patch('time.time', mock.Mock(return_value=1234)): resp, body = cl.get("/hi")
resp, body = cl.get("/hi")
headers = {"X-Auth-Token": "token", # this may become too tightly couple later
"User-Agent": httpclient.USER_AGENT} mock_args, mock_kwargs = MOCK_REQUEST.call_args
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['cert'] = ('cert.pem', 'key.pem') self.assertEqual(mock_args[0], 'GET')
kwargs['verify'] = 'ca.pem' self.assertEqual(mock_args[1], REQUEST_URL)
MOCK_REQUEST.assert_called_with( self.assertEqual(mock_kwargs['headers']['X-Auth-Token'], 'token')
"GET", self.assertEqual(mock_kwargs['cert'], ('cert.pem', 'key.pem'))
"https://127.0.0.1:5000/hi", self.assertEqual(mock_kwargs['verify'], 'ca.pem')
headers=headers,
**kwargs) # Automatic JSON parsing
# Automatic JSON parsing self.assertEqual(body, {"hi": "there"})
self.assertEqual(body, {"hi": "there"})
def test_post(self): def test_post(self):
cl = get_authed_client() cl = get_authed_client()
with mock.patch.object(requests, "request", MOCK_REQUEST): with mock.patch.object(requests, "request", MOCK_REQUEST):
cl.post("/hi", body=[1, 2, 3]) cl.post("/hi", body=[1, 2, 3])
headers = {
"X-Auth-Token": "token", # this may become too tightly couple later
"Content-Type": "application/json", mock_args, mock_kwargs = MOCK_REQUEST.call_args
"User-Agent": httpclient.USER_AGENT
} self.assertEqual(mock_args[0], 'POST')
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.assertEqual(mock_args[1], REQUEST_URL)
kwargs['cert'] = ('cert.pem', 'key.pem') self.assertEqual(mock_kwargs['data'], '[1, 2, 3]')
kwargs['verify'] = 'ca.pem' self.assertEqual(mock_kwargs['headers']['X-Auth-Token'], 'token')
MOCK_REQUEST.assert_called_with( self.assertEqual(mock_kwargs['cert'], ('cert.pem', 'key.pem'))
"POST", self.assertEqual(mock_kwargs['verify'], 'ca.pem')
"https://127.0.0.1:5000/hi",
headers=headers,
data='[1, 2, 3]',
**kwargs)
def test_post_auth(self): def test_post_auth(self):
with mock.patch.object(requests, "request", MOCK_REQUEST): with mock.patch.object(requests, "request", MOCK_REQUEST):
@@ -92,17 +98,13 @@ class ClientTest(utils.TestCase):
cl.management_url = "https://127.0.0.1:5000" cl.management_url = "https://127.0.0.1:5000"
cl.auth_token = "token" cl.auth_token = "token"
cl.post("/hi", body=[1, 2, 3]) cl.post("/hi", body=[1, 2, 3])
headers = {
"X-Auth-Token": "token", # this may become too tightly couple later
"Content-Type": "application/json", mock_args, mock_kwargs = MOCK_REQUEST.call_args
"User-Agent": httpclient.USER_AGENT
} self.assertEqual(mock_args[0], 'POST')
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.assertEqual(mock_args[1], REQUEST_URL)
kwargs['cert'] = ('cert.pem', 'key.pem') self.assertEqual(mock_kwargs['data'], '[1, 2, 3]')
kwargs['verify'] = 'ca.pem' self.assertEqual(mock_kwargs['headers']['X-Auth-Token'], 'token')
MOCK_REQUEST.assert_called_with( self.assertEqual(mock_kwargs['cert'], ('cert.pem', 'key.pem'))
"POST", self.assertEqual(mock_kwargs['verify'], 'ca.pem')
"https://127.0.0.1:5000/hi",
headers=headers,
data='[1, 2, 3]',
**kwargs)

View File

@@ -12,14 +12,16 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import sys
import time import time
import httpretty
import mock import mock
from mox3 import mox from mox3 import mox
import requests import requests
import testtools import testtools
from keystoneclient.v2_0 import client from keystoneclient.openstack.common import jsonutils
class TestCase(testtools.TestCase): class TestCase(testtools.TestCase):
@@ -29,110 +31,63 @@ class TestCase(testtools.TestCase):
TEST_TENANT_NAME = 'aTenant' TEST_TENANT_NAME = 'aTenant'
TEST_TOKEN = 'aToken' TEST_TOKEN = 'aToken'
TEST_USER = 'test' TEST_USER = 'test'
TEST_ROOT_URL = 'http://127.0.0.1:5000/'
TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v2.0')
TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/'
TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v2.0')
TEST_REQUEST_BASE = {
'verify': True,
}
TEST_SERVICE_CATALOG = [{ TEST_ROOT_URL = 'http://127.0.0.1:5000/'
"endpoints": [{
"adminURL": "http://cdn.admin-nets.local:8774/v1.0",
"region": "RegionOne",
"internalURL": "http://127.0.0.1:8774/v1.0",
"publicURL": "http://cdn.admin-nets.local:8774/v1.0/"
}],
"type": "nova_compat",
"name": "nova_compat"
}, {
"endpoints": [{
"adminURL": "http://nova/novapi/admin",
"region": "RegionOne",
"internalURL": "http://nova/novapi/internal",
"publicURL": "http://nova/novapi/public"
}],
"type": "compute",
"name": "nova"
}, {
"endpoints": [{
"adminURL": "http://glance/glanceapi/admin",
"region": "RegionOne",
"internalURL": "http://glance/glanceapi/internal",
"publicURL": "http://glance/glanceapi/public"
}],
"type": "image",
"name": "glance"
}, {
"endpoints": [{
"adminURL": "http://127.0.0.1:35357/v2.0",
"region": "RegionOne",
"internalURL": "http://127.0.0.1:5000/v2.0",
"publicURL": "http://127.0.0.1:5000/v2.0"
}],
"type": "identity",
"name": "keystone"
}, {
"endpoints": [{
"adminURL": "http://swift/swiftapi/admin",
"region": "RegionOne",
"internalURL": "http://swift/swiftapi/internal",
"publicURL": "http://swift/swiftapi/public"
}],
"type": "object-store",
"name": "swift"
}]
def setUp(self): def setUp(self):
super(TestCase, self).setUp() super(TestCase, self).setUp()
self.mox = mox.Mox() self.mox = mox.Mox()
self.request_patcher = mock.patch.object(requests, 'request', self.time_patcher = mock.patch.object(time, 'time', lambda: 1234)
self.mox.CreateMockAnything())
self.time_patcher = mock.patch.object(time, 'time',
lambda: 1234)
self.request_patcher.start()
self.time_patcher.start() self.time_patcher.start()
self.client = client.Client(username=self.TEST_USER,
token=self.TEST_TOKEN,
tenant_name=self.TEST_TENANT_NAME,
auth_url=self.TEST_URL,
endpoint=self.TEST_URL)
def tearDown(self): def tearDown(self):
self.request_patcher.stop()
self.time_patcher.stop() self.time_patcher.stop()
self.mox.UnsetStubs() self.mox.UnsetStubs()
self.mox.VerifyAll() self.mox.VerifyAll()
super(TestCase, self).tearDown() super(TestCase, self).tearDown()
def stub_url(self, method, parts=None, base_url=None, json=None, **kwargs):
if not base_url:
base_url = self.TEST_URL
class UnauthenticatedTestCase(testtools.TestCase): if json:
"""Class used as base for unauthenticated calls.""" kwargs['body'] = jsonutils.dumps(json)
TEST_ROOT_URL = 'http://127.0.0.1:5000/' kwargs['content_type'] = 'application/json'
TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v2.0')
TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/'
TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v2.0')
TEST_REQUEST_BASE = {
'verify': True,
}
def setUp(self): if parts:
super(UnauthenticatedTestCase, self).setUp() url = '/'.join([p.strip('/') for p in [base_url] + parts])
self.mox = mox.Mox() else:
self.request_patcher = mock.patch.object(requests, 'request', url = base_url
self.mox.CreateMockAnything())
self.time_patcher = mock.patch.object(time, 'time',
lambda: 1234)
self.request_patcher.start()
self.time_patcher.start()
def tearDown(self): httpretty.register_uri(method, url, **kwargs)
self.request_patcher.stop()
self.time_patcher.stop() def assertRequestBodyIs(self, body=None, json=None):
self.mox.UnsetStubs() if json:
self.mox.VerifyAll() val = jsonutils.loads(httpretty.last_request().body)
super(UnauthenticatedTestCase, self).tearDown() self.assertEqual(json, val)
elif body:
self.assertEqual(body, httpretty.last_request().body)
def assertQueryStringIs(self, val):
self.assertEqual(httpretty.last_request().querystring, val)
if tuple(sys.version_info)[0:2] < (2, 7):
def assertDictEqual(self, d1, d2, msg=None):
# Simple version taken from 2.7
self.assertIsInstance(d1, dict,
'First argument is not a dictionary')
self.assertIsInstance(d2, dict,
'Second argument is not a dictionary')
if d1 != d2:
if msg:
self.fail(msg)
else:
standardMsg = '%r != %r' % (d1, d2)
self.fail(standardMsg)
TestCase.assertDictEqual = assertDictEqual
class TestResponse(requests.Response): class TestResponse(requests.Response):

View File

@@ -16,7 +16,7 @@
import urlparse import urlparse
from tests import fakes from tests import fakes
from tests import utils from tests.v2_0 import utils
class FakeHTTPClient(fakes.FakeClient): class FakeHTTPClient(fakes.FakeClient):

View File

@@ -17,8 +17,8 @@ import datetime
from keystoneclient import access from keystoneclient import access
from keystoneclient.openstack.common import timeutils from keystoneclient.openstack.common import timeutils
from tests import client_fixtures as token_data from tests import client_fixtures as token_data
from tests import utils
from tests.v2_0 import client_fixtures from tests.v2_0 import client_fixtures
from tests.v2_0 import utils
UNSCOPED_TOKEN = client_fixtures.UNSCOPED_TOKEN UNSCOPED_TOKEN = client_fixtures.UNSCOPED_TOKEN
PROJECT_SCOPED_TOKEN = client_fixtures.PROJECT_SCOPED_TOKEN PROJECT_SCOPED_TOKEN = client_fixtures.PROJECT_SCOPED_TOKEN

View File

@@ -12,17 +12,15 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import datetime import datetime
import json import json
import requests import httpretty
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.openstack.common import timeutils from keystoneclient.openstack.common import timeutils
from keystoneclient.v2_0 import client from keystoneclient.v2_0 import client
from tests.v2_0 import utils
from tests import utils
class AuthenticateAgainstKeystoneTests(utils.TestCase): class AuthenticateAgainstKeystoneTests(utils.TestCase):
@@ -52,76 +50,50 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
"tenantId": self.TEST_TENANT_ID, "tenantId": self.TEST_TENANT_ID,
}, },
} }
self.TEST_REQUEST_HEADERS = {
'Content-Type': 'application/json',
'User-Agent': 'python-keystoneclient',
}
@httpretty.activate
def test_authenticate_success_expired(self): def test_authenticate_success_expired(self):
# Build an expired token # Build an expired token
self.TEST_RESPONSE_DICT['access']['token']['expires'] = \ self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
(timeutils.utcnow() - datetime.timedelta(1)).isoformat() (timeutils.utcnow() - datetime.timedelta(1)).isoformat()
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) exp_resp = httpretty.Response(body=json.dumps(self.TEST_RESPONSE_DICT),
kwargs['headers'] = self.TEST_REQUEST_HEADERS content_type='application/json')
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_URL + "/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(tenant_id=self.TEST_TENANT_ID,
auth_url=self.TEST_URL,
username=self.TEST_USER,
password=self.TEST_TOKEN)
self.assertEqual(cs.management_url,
self.TEST_RESPONSE_DICT["access"]["serviceCatalog"][3]
['endpoints'][0]["adminURL"])
# Build a new response # Build a new response
self.mox.ResetAll()
TEST_TOKEN = "abcdef" TEST_TOKEN = "abcdef"
self.TEST_RESPONSE_DICT['access']['token']['expires'] = \ self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
'2020-01-01T00:00:10.000123Z' '2020-01-01T00:00:10.000123Z'
self.TEST_RESPONSE_DICT['access']['token']['id'] = TEST_TOKEN self.TEST_RESPONSE_DICT['access']['token']['id'] = TEST_TOKEN
resp = utils.TestResponse({ new_resp = httpretty.Response(body=json.dumps(self.TEST_RESPONSE_DICT),
"status_code": 200, content_type='application/json')
"text": json.dumps(self.TEST_RESPONSE_DICT),
}) # return expired first, and then the new response
requests.request('POST', self.stub_auth(responses=[exp_resp, new_resp])
self.TEST_URL + "/tokens",
**kwargs).AndReturn((resp)) cs = client.Client(tenant_id=self.TEST_TENANT_ID,
self.mox.ReplayAll() auth_url=self.TEST_URL,
username=self.TEST_USER,
password=self.TEST_TOKEN)
self.assertEqual(cs.management_url,
self.TEST_RESPONSE_DICT["access"]["serviceCatalog"][3]
['endpoints'][0]["adminURL"])
self.assertEqual(cs.auth_token, TEST_TOKEN) self.assertEqual(cs.auth_token, TEST_TOKEN)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_failure(self): def test_authenticate_failure(self):
_auth = 'auth' _auth = 'auth'
_cred = 'passwordCredentials' _cred = 'passwordCredentials'
_pass = 'password' _pass = 'password'
self.TEST_REQUEST_BODY[_auth][_cred][_pass] = 'bad_key' self.TEST_REQUEST_BODY[_auth][_cred][_pass] = 'bad_key'
resp = utils.TestResponse({ error = {"unauthorized": {"message": "Unauthorized",
"status_code": 401, "code": "401"}}
"text": json.dumps({
"unauthorized": {
"message": "Unauthorized",
"code": "401",
},
}),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(status=401, json=error)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_URL + "/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
# Workaround for issue with assertRaises on python2.6 # Workaround for issue with assertRaises on python2.6
# where with assertRaises(exceptions.Unauthorized): doesn't work # where with assertRaises(exceptions.Unauthorized): doesn't work
@@ -133,39 +105,15 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
auth_url=self.TEST_URL) auth_url=self.TEST_URL)
self.assertRaises(exceptions.Unauthorized, client_create_wrapper) self.assertRaises(exceptions.Unauthorized, client_create_wrapper)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_auth_redirect(self): def test_auth_redirect(self):
correct_response = json.dumps(self.TEST_RESPONSE_DICT) self.stub_auth(status=305, body='Use Proxy',
dict_responses = [ location=self.TEST_ADMIN_URL + "/tokens")
{
"headers": {
'location': self.TEST_ADMIN_URL + "/tokens",
},
"status_code": 305,
"text": "Use proxy",
},
{
"headers": {},
"status_code": 200,
"text": correct_response,
},
]
responses = [(utils.TestResponse(resp))
for resp in dict_responses]
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(base_url=self.TEST_ADMIN_URL,
kwargs['headers'] = self.TEST_REQUEST_HEADERS json=self.TEST_RESPONSE_DICT)
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_URL + "/tokens",
**kwargs).AndReturn(responses[0])
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_ADMIN_URL + "/tokens",
**kwargs).AndReturn(responses[1])
self.mox.ReplayAll()
cs = client.Client(username=self.TEST_USER, cs = client.Client(username=self.TEST_USER,
password=self.TEST_TOKEN, password=self.TEST_TOKEN,
@@ -177,20 +125,11 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
['endpoints'][0]["adminURL"]) ['endpoints'][0]["adminURL"])
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_DICT["access"]["token"]["id"]) self.TEST_RESPONSE_DICT["access"]["token"]["id"])
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_password_scoped(self): def test_authenticate_success_password_scoped(self):
resp = utils.TestResponse({ self.stub_auth(json=self.TEST_RESPONSE_DICT)
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_URL + "/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(username=self.TEST_USER, cs = client.Client(username=self.TEST_USER,
password=self.TEST_TOKEN, password=self.TEST_TOKEN,
@@ -201,22 +140,14 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
['endpoints'][0]["adminURL"]) ['endpoints'][0]["adminURL"])
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_DICT["access"]["token"]["id"]) self.TEST_RESPONSE_DICT["access"]["token"]["id"])
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_password_unscoped(self): def test_authenticate_success_password_unscoped(self):
del self.TEST_RESPONSE_DICT['access']['serviceCatalog'] del self.TEST_RESPONSE_DICT['access']['serviceCatalog']
del self.TEST_REQUEST_BODY['auth']['tenantId'] del self.TEST_REQUEST_BODY['auth']['tenantId']
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_URL + "/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(username=self.TEST_USER, cs = client.Client(username=self.TEST_USER,
password=self.TEST_TOKEN, password=self.TEST_TOKEN,
@@ -224,23 +155,13 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_DICT["access"]["token"]["id"]) self.TEST_RESPONSE_DICT["access"]["token"]["id"])
self.assertFalse('serviceCatalog' in cs.service_catalog.catalog) self.assertFalse('serviceCatalog' in cs.service_catalog.catalog)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_token_scoped(self): def test_authenticate_success_token_scoped(self):
del self.TEST_REQUEST_BODY['auth']['passwordCredentials'] del self.TEST_REQUEST_BODY['auth']['passwordCredentials']
self.TEST_REQUEST_BODY['auth']['token'] = {'id': self.TEST_TOKEN} self.TEST_REQUEST_BODY['auth']['token'] = {'id': self.TEST_TOKEN}
self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN self.stub_auth(json=self.TEST_RESPONSE_DICT)
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_URL + "/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(token=self.TEST_TOKEN, cs = client.Client(token=self.TEST_TOKEN,
tenant_id=self.TEST_TENANT_ID, tenant_id=self.TEST_TENANT_ID,
@@ -250,28 +171,20 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
['endpoints'][0]["adminURL"]) ['endpoints'][0]["adminURL"])
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_DICT["access"]["token"]["id"]) self.TEST_RESPONSE_DICT["access"]["token"]["id"])
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_token_unscoped(self): def test_authenticate_success_token_unscoped(self):
del self.TEST_REQUEST_BODY['auth']['passwordCredentials'] del self.TEST_REQUEST_BODY['auth']['passwordCredentials']
del self.TEST_REQUEST_BODY['auth']['tenantId'] del self.TEST_REQUEST_BODY['auth']['tenantId']
del self.TEST_RESPONSE_DICT['access']['serviceCatalog'] del self.TEST_RESPONSE_DICT['access']['serviceCatalog']
self.TEST_REQUEST_BODY['auth']['token'] = {'id': self.TEST_TOKEN} self.TEST_REQUEST_BODY['auth']['token'] = {'id': self.TEST_TOKEN}
self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
requests.request('POST',
self.TEST_URL + "/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(token=self.TEST_TOKEN, cs = client.Client(token=self.TEST_TOKEN,
auth_url=self.TEST_URL) auth_url=self.TEST_URL)
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_DICT["access"]["token"]["id"]) self.TEST_RESPONSE_DICT["access"]["token"]["id"])
self.assertFalse('serviceCatalog' in cs.service_catalog.catalog) self.assertFalse('serviceCatalog' in cs.service_catalog.catalog)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

View File

@@ -13,98 +13,91 @@
# under the License. # under the License.
import json import json
import mock
import requests import httpretty
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.v2_0 import client from keystoneclient.v2_0 import client
from tests import utils
from tests.v2_0 import client_fixtures from tests.v2_0 import client_fixtures
from tests.v2_0 import utils
class KeystoneClientTest(utils.TestCase): class KeystoneClientTest(utils.TestCase):
def setUp(self):
super(KeystoneClientTest, self).setUp()
scoped_fake_resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(client_fixtures.PROJECT_SCOPED_TOKEN)
})
self.scoped_mock_req = mock.Mock(return_value=scoped_fake_resp)
unscoped_fake_resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(client_fixtures.UNSCOPED_TOKEN)
})
self.unscoped_mock_req = mock.Mock(return_value=unscoped_fake_resp)
@httpretty.activate
def test_unscoped_init(self): def test_unscoped_init(self):
with mock.patch.object(requests, "request", self.unscoped_mock_req): self.stub_auth(json=client_fixtures.UNSCOPED_TOKEN)
c = client.Client(username='exampleuser',
password='password',
auth_url='http://somewhere/')
self.assertIsNotNone(c.auth_ref)
self.assertFalse(c.auth_ref.scoped)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertFalse(c.auth_ref.project_scoped)
self.assertIsNone(c.auth_ref.trust_id)
self.assertFalse(c.auth_ref.trust_scoped)
c = client.Client(username='exampleuser',
password='password',
auth_url=self.TEST_URL)
self.assertIsNotNone(c.auth_ref)
self.assertFalse(c.auth_ref.scoped)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertFalse(c.auth_ref.project_scoped)
self.assertIsNone(c.auth_ref.trust_id)
self.assertFalse(c.auth_ref.trust_scoped)
@httpretty.activate
def test_scoped_init(self): def test_scoped_init(self):
with mock.patch.object(requests, "request", self.scoped_mock_req): self.stub_auth(json=client_fixtures.PROJECT_SCOPED_TOKEN)
c = client.Client(username='exampleuser',
password='password',
tenant_name='exampleproject',
auth_url='http://somewhere/')
self.assertIsNotNone(c.auth_ref)
self.assertTrue(c.auth_ref.scoped)
self.assertTrue(c.auth_ref.project_scoped)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertIsNone(c.auth_ref.trust_id)
self.assertFalse(c.auth_ref.trust_scoped)
c = client.Client(username='exampleuser',
password='password',
tenant_name='exampleproject',
auth_url=self.TEST_URL)
self.assertIsNotNone(c.auth_ref)
self.assertTrue(c.auth_ref.scoped)
self.assertTrue(c.auth_ref.project_scoped)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertIsNone(c.auth_ref.trust_id)
self.assertFalse(c.auth_ref.trust_scoped)
@httpretty.activate
def test_auth_ref_load(self): def test_auth_ref_load(self):
with mock.patch.object(requests, "request", self.scoped_mock_req): self.stub_auth(json=client_fixtures.PROJECT_SCOPED_TOKEN)
cl = client.Client(username='exampleuser',
password='password',
tenant_name='exampleproject',
auth_url='http://somewhere/')
cache = json.dumps(cl.auth_ref)
new_client = client.Client(auth_ref=json.loads(cache))
self.assertIsNotNone(new_client.auth_ref)
self.assertTrue(new_client.auth_ref.scoped)
self.assertTrue(new_client.auth_ref.project_scoped)
self.assertFalse(new_client.auth_ref.domain_scoped)
self.assertIsNone(new_client.auth_ref.trust_id)
self.assertFalse(new_client.auth_ref.trust_scoped)
self.assertEquals(new_client.username, 'exampleuser')
self.assertIsNone(new_client.password)
self.assertEqual(new_client.management_url,
'http://admin:35357/v2.0')
cl = client.Client(username='exampleuser',
password='password',
tenant_name='exampleproject',
auth_url=self.TEST_URL)
cache = json.dumps(cl.auth_ref)
new_client = client.Client(auth_ref=json.loads(cache))
self.assertIsNotNone(new_client.auth_ref)
self.assertTrue(new_client.auth_ref.scoped)
self.assertTrue(new_client.auth_ref.project_scoped)
self.assertFalse(new_client.auth_ref.domain_scoped)
self.assertIsNone(new_client.auth_ref.trust_id)
self.assertFalse(new_client.auth_ref.trust_scoped)
self.assertEquals(new_client.username, 'exampleuser')
self.assertIsNone(new_client.password)
self.assertEqual(new_client.management_url,
'http://admin:35357/v2.0')
@httpretty.activate
def test_auth_ref_load_with_overridden_arguments(self): def test_auth_ref_load_with_overridden_arguments(self):
with mock.patch.object(requests, "request", self.scoped_mock_req): self.stub_auth(json=client_fixtures.PROJECT_SCOPED_TOKEN)
cl = client.Client(username='exampleuser',
password='password', cl = client.Client(username='exampleuser',
tenant_name='exampleproject', password='password',
auth_url='http://somewhere/') tenant_name='exampleproject',
cache = json.dumps(cl.auth_ref) auth_url=self.TEST_URL)
new_auth_url = "http://new-public:5000/v2.0" cache = json.dumps(cl.auth_ref)
new_client = client.Client(auth_ref=json.loads(cache), new_auth_url = "http://new-public:5000/v2.0"
auth_url=new_auth_url) new_client = client.Client(auth_ref=json.loads(cache),
self.assertIsNotNone(new_client.auth_ref) auth_url=new_auth_url)
self.assertTrue(new_client.auth_ref.scoped) self.assertIsNotNone(new_client.auth_ref)
self.assertTrue(new_client.auth_ref.scoped) self.assertTrue(new_client.auth_ref.scoped)
self.assertTrue(new_client.auth_ref.project_scoped) self.assertTrue(new_client.auth_ref.scoped)
self.assertFalse(new_client.auth_ref.domain_scoped) self.assertTrue(new_client.auth_ref.project_scoped)
self.assertIsNone(new_client.auth_ref.trust_id) self.assertFalse(new_client.auth_ref.domain_scoped)
self.assertFalse(new_client.auth_ref.trust_scoped) self.assertIsNone(new_client.auth_ref.trust_id)
self.assertEquals(new_client.auth_url, new_auth_url) self.assertFalse(new_client.auth_ref.trust_scoped)
self.assertEquals(new_client.username, 'exampleuser') self.assertEquals(new_client.auth_url, new_auth_url)
self.assertIsNone(new_client.password) self.assertEquals(new_client.username, 'exampleuser')
self.assertEqual(new_client.management_url, self.assertIsNone(new_client.password)
'http://admin:35357/v2.0') self.assertEqual(new_client.management_url,
'http://admin:35357/v2.0')
def test_init_err_no_auth_url(self): def test_init_err_no_auth_url(self):
self.assertRaises(exceptions.AuthorizationFailure, self.assertRaises(exceptions.AuthorizationFailure,

View File

@@ -12,12 +12,10 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import requests
from keystoneclient.generic import client from keystoneclient.generic import client
from tests import utils from tests.v2_0 import utils
class DiscoverKeystoneTests(utils.UnauthenticatedTestCase): class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
@@ -55,23 +53,11 @@ class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
}], }],
}, },
} }
self.TEST_REQUEST_HEADERS = {
'User-Agent': 'python-keystoneclient',
'Accept': 'application/json',
}
@httpretty.activate
def test_get_versions(self): def test_get_versions(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, base_url=self.TEST_ROOT_URL,
"status_code": 200, json=self.TEST_RESPONSE_DICT)
"text": json.dumps(self.TEST_RESPONSE_DICT),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
self.TEST_ROOT_URL,
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client() cs = client.Client()
versions = cs.discover(self.TEST_ROOT_URL) versions = cs.discover(self.TEST_ROOT_URL)
@@ -83,17 +69,10 @@ class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
self.TEST_RESPONSE_DICT['versions']['values'][0]['links'][0] self.TEST_RESPONSE_DICT['versions']['values'][0]['links'][0]
['href']) ['href'])
@httpretty.activate
def test_get_version_local(self): def test_get_version_local(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, base_url="http://localhost:35357/",
"status_code": 200, json=self.TEST_RESPONSE_DICT)
"text": json.dumps(self.TEST_RESPONSE_DICT),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
"http://localhost:35357",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client() cs = client.Client()
versions = cs.discover() versions = cs.discover()

View File

@@ -12,29 +12,15 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import urlparse
import requests
from keystoneclient.v2_0 import ec2 from keystoneclient.v2_0 import ec2
from tests import utils from tests.v2_0 import utils
class EC2Tests(utils.TestCase): class EC2Tests(utils.TestCase):
def setUp(self):
super(EC2Tests, self).setUp()
self.TEST_REQUEST_HEADERS = {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_POST_HEADERS = {
'Content-Type': 'application/json',
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
@httpretty.activate
def test_create(self): def test_create(self):
user_id = 'usr' user_id = 'usr'
tenant_id = 'tnt' tenant_id = 'tnt'
@@ -50,20 +36,8 @@ class EC2Tests(utils.TestCase):
"enabled": True, "enabled": True,
} }
} }
resp = utils.TestResponse({ self.stub_url(httpretty.POST, ['users', user_id, 'credentials',
"status_code": 200, 'OS-EC2'], json=resp_body)
"text": json.dumps(resp_body),
})
url = urlparse.urljoin(self.TEST_URL,
'v2.0/users/%s/credentials/OS-EC2' % user_id)
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
url,
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cred = self.client.ec2.create(user_id, tenant_id) cred = self.client.ec2.create(user_id, tenant_id)
self.assertTrue(isinstance(cred, ec2.EC2)) self.assertTrue(isinstance(cred, ec2.EC2))
@@ -71,7 +45,9 @@ class EC2Tests(utils.TestCase):
self.assertEqual(cred.enabled, True) self.assertEqual(cred.enabled, True)
self.assertEqual(cred.access, 'access') self.assertEqual(cred.access, 'access')
self.assertEqual(cred.secret, 'secret') self.assertEqual(cred.secret, 'secret')
self.assertRequestBodyIs(json=req_body)
@httpretty.activate
def test_get(self): def test_get(self):
user_id = 'usr' user_id = 'usr'
tenant_id = 'tnt' tenant_id = 'tnt'
@@ -84,20 +60,8 @@ class EC2Tests(utils.TestCase):
"enabled": True, "enabled": True,
} }
} }
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['users', user_id, 'credentials',
"status_code": 200, 'OS-EC2', 'access'], json=resp_body)
"text": json.dumps(resp_body),
})
url = urlparse.urljoin(self.TEST_URL,
'v2.0/users/%s/credentials/OS-EC2/%s' %
(user_id, 'access'))
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
url,
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cred = self.client.ec2.get(user_id, 'access') cred = self.client.ec2.get(user_id, 'access')
self.assertTrue(isinstance(cred, ec2.EC2)) self.assertTrue(isinstance(cred, ec2.EC2))
@@ -106,6 +70,7 @@ class EC2Tests(utils.TestCase):
self.assertEqual(cred.access, 'access') self.assertEqual(cred.access, 'access')
self.assertEqual(cred.secret, 'secret') self.assertEqual(cred.secret, 'secret')
@httpretty.activate
def test_list(self): def test_list(self):
user_id = 'usr' user_id = 'usr'
tenant_id = 'tnt' tenant_id = 'tnt'
@@ -129,20 +94,8 @@ class EC2Tests(utils.TestCase):
] ]
} }
} }
self.stub_url(httpretty.GET, ['users', user_id, 'credentials',
resp = utils.TestResponse({ 'OS-EC2'], json=resp_body)
"status_code": 200,
"text": json.dumps(resp_body),
})
url = urlparse.urljoin(self.TEST_URL,
'v2.0/users/%s/credentials/OS-EC2' % user_id)
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
url,
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
creds = self.client.ec2.list(user_id) creds = self.client.ec2.list(user_id)
self.assertTrue(len(creds), 2) self.assertTrue(len(creds), 2)
@@ -153,22 +106,10 @@ class EC2Tests(utils.TestCase):
self.assertEqual(cred.access, 'access') self.assertEqual(cred.access, 'access')
self.assertEqual(cred.secret, 'secret') self.assertEqual(cred.secret, 'secret')
@httpretty.activate
def test_delete(self): def test_delete(self):
user_id = 'usr' user_id = 'usr'
access = 'access' access = 'access'
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['users', user_id, 'credentials',
"status_code": 204, 'OS-EC2', access], status=204)
"text": "",
})
url = urlparse.urljoin(self.TEST_URL,
'v2.0/users/%s/credentials/OS-EC2/%s' %
(user_id, access))
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
url,
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.ec2.delete(user_id, access) self.client.ec2.delete(user_id, access)

View File

@@ -12,28 +12,15 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import urlparse
import requests
from keystoneclient.v2_0 import endpoints from keystoneclient.v2_0 import endpoints
from tests import utils from tests.v2_0 import utils
class EndpointTests(utils.TestCase): class EndpointTests(utils.TestCase):
def setUp(self): def setUp(self):
super(EndpointTests, self).setUp() super(EndpointTests, self).setUp()
self.TEST_REQUEST_HEADERS = {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_POST_HEADERS = {
'Content-Type': 'application/json',
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_ENDPOINTS = { self.TEST_ENDPOINTS = {
'endpoints': [ 'endpoints': [
{ {
@@ -53,6 +40,7 @@ class EndpointTests(utils.TestCase):
] ]
} }
@httpretty.activate
def test_create(self): def test_create(self):
req_body = { req_body = {
"endpoint": { "endpoint": {
@@ -74,19 +62,7 @@ class EndpointTests(utils.TestCase):
} }
} }
resp = utils.TestResponse({ self.stub_url(httpretty.POST, ['endpoints'], json=resp_body)
"status_code": 200,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
urlparse.urljoin(self.TEST_URL,
'v2.0/endpoints'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
endpoint = self.client.endpoints.create( endpoint = self.client.endpoints.create(
region=req_body['endpoint']['region'], region=req_body['endpoint']['region'],
@@ -96,35 +72,16 @@ class EndpointTests(utils.TestCase):
service_id=req_body['endpoint']['service_id'] service_id=req_body['endpoint']['service_id']
) )
self.assertTrue(isinstance(endpoint, endpoints.Endpoint)) self.assertTrue(isinstance(endpoint, endpoints.Endpoint))
self.assertRequestBodyIs(json=req_body)
@httpretty.activate
def test_delete(self): def test_delete(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['endpoints', '8f953'], status=204)
"status_code": 204,
"text": "",
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL,
'v2.0/endpoints/8f953'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.endpoints.delete('8f953') self.client.endpoints.delete('8f953')
@httpretty.activate
def test_list(self): def test_list(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['endpoints'], json=self.TEST_ENDPOINTS)
"status_code": 200,
"text": json.dumps(self.TEST_ENDPOINTS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/endpoints'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
endpoint_list = self.client.endpoints.list() endpoint_list = self.client.endpoints.list()
[self.assertTrue(isinstance(r, endpoints.Endpoint)) [self.assertTrue(isinstance(r, endpoints.Endpoint))

View File

@@ -12,28 +12,15 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import urlparse
import requests
from keystoneclient.v2_0 import roles from keystoneclient.v2_0 import roles
from tests import utils from tests.v2_0 import utils
class RoleTests(utils.TestCase): class RoleTests(utils.TestCase):
def setUp(self): def setUp(self):
super(RoleTests, self).setUp() super(RoleTests, self).setUp()
self.TEST_REQUEST_HEADERS = {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_POST_HEADERS = {
'Content-Type': 'application/json',
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_ROLES = { self.TEST_ROLES = {
"roles": { "roles": {
"values": [ "values": [
@@ -49,6 +36,7 @@ class RoleTests(utils.TestCase):
}, },
} }
@httpretty.activate
def test_create(self): def test_create(self):
req_body = { req_body = {
"role": { "role": {
@@ -61,173 +49,76 @@ class RoleTests(utils.TestCase):
"id": 3, "id": 3,
} }
} }
resp = utils.TestResponse({ self.stub_url(httpretty.POST, ['OS-KSADM', 'roles'], json=resp_body)
"status_code": 200,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/roles'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
role = self.client.roles.create(req_body['role']['name']) role = self.client.roles.create(req_body['role']['name'])
self.assertRequestBodyIs(json=req_body)
self.assertTrue(isinstance(role, roles.Role)) self.assertTrue(isinstance(role, roles.Role))
self.assertEqual(role.id, 3) self.assertEqual(role.id, 3)
self.assertEqual(role.name, req_body['role']['name']) self.assertEqual(role.name, req_body['role']['name'])
@httpretty.activate
def test_delete(self): def test_delete(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['OS-KSADM', 'roles', '1'], status=204)
"status_code": 204,
"text": "",
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/roles/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.roles.delete(1) self.client.roles.delete(1)
@httpretty.activate
def test_get(self): def test_get(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['OS-KSADM', 'roles', '1'],
"status_code": 200, json={'role': self.TEST_ROLES['roles']['values'][0]})
"text": json.dumps({
'role': self.TEST_ROLES['roles']['values'][0],
}),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/roles/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
role = self.client.roles.get(1) role = self.client.roles.get(1)
self.assertTrue(isinstance(role, roles.Role)) self.assertTrue(isinstance(role, roles.Role))
self.assertEqual(role.id, 1) self.assertEqual(role.id, 1)
self.assertEqual(role.name, 'admin') self.assertEqual(role.name, 'admin')
@httpretty.activate
def test_list(self): def test_list(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['OS-KSADM', 'roles'],
"status_code": 200, json=self.TEST_ROLES)
"text": json.dumps(self.TEST_ROLES),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/roles'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
role_list = self.client.roles.list() role_list = self.client.roles.list()
[self.assertTrue(isinstance(r, roles.Role)) for r in role_list] [self.assertTrue(isinstance(r, roles.Role)) for r in role_list]
@httpretty.activate
def test_roles_for_user(self): def test_roles_for_user(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['users', 'foo', 'roles'],
"status_code": 200, json=self.TEST_ROLES)
"text": json.dumps(self.TEST_ROLES),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/users/foo/roles'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
role_list = self.client.roles.roles_for_user('foo') role_list = self.client.roles.roles_for_user('foo')
[self.assertTrue(isinstance(r, roles.Role)) for r in role_list] [self.assertTrue(isinstance(r, roles.Role)) for r in role_list]
@httpretty.activate
def test_roles_for_user_tenant(self): def test_roles_for_user_tenant(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['tenants', 'barrr', 'users', 'foo',
"status_code": 200, 'roles'], json=self.TEST_ROLES)
"text": json.dumps(self.TEST_ROLES),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/barrr/users/foo/roles'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
role_list = self.client.roles.roles_for_user('foo', 'barrr') role_list = self.client.roles.roles_for_user('foo', 'barrr')
[self.assertTrue(isinstance(r, roles.Role)) for r in role_list] [self.assertTrue(isinstance(r, roles.Role)) for r in role_list]
@httpretty.activate
def test_add_user_role(self): def test_add_user_role(self):
resp = utils.TestResponse({ self.stub_url(httpretty.PUT, ['users', 'foo', 'roles', 'OS-KSADM',
"status_code": 204, 'barrr'], status=204)
"text": '',
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('PUT',
urlparse.urljoin(self.TEST_URL,
'v2.0/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.roles.add_user_role('foo', 'barrr') self.client.roles.add_user_role('foo', 'barrr')
@httpretty.activate
def test_add_user_role_tenant(self): def test_add_user_role_tenant(self):
resp = utils.TestResponse({ self.stub_url(httpretty.PUT, ['tenants', '4', 'users', 'foo', 'roles',
"status_code": 204, 'OS-KSADM', 'barrr'], status=204)
"text": '',
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('PUT',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.roles.add_user_role('foo', 'barrr', '4') self.client.roles.add_user_role('foo', 'barrr', '4')
@httpretty.activate
def test_remove_user_role(self): def test_remove_user_role(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['users', 'foo', 'roles', 'OS-KSADM',
"status_code": 204, 'barrr'], status=204)
"text": '',
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL,
'v2.0/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.roles.remove_user_role('foo', 'barrr') self.client.roles.remove_user_role('foo', 'barrr')
@httpretty.activate
def test_remove_user_role_tenant(self): def test_remove_user_role_tenant(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['tenants', '4', 'users', 'foo',
"status_code": 204, 'roles', 'OS-KSADM', 'barrr'],
"text": '', status=204)
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.roles.remove_user_role('foo', 'barrr', '4') self.client.roles.remove_user_role('foo', 'barrr', '4')

View File

@@ -17,8 +17,8 @@ import copy
from keystoneclient import access from keystoneclient import access
from keystoneclient import exceptions from keystoneclient import exceptions
from tests import utils
from tests.v2_0 import client_fixtures from tests.v2_0 import client_fixtures
from tests.v2_0 import utils
class ServiceCatalogTest(utils.TestCase): class ServiceCatalogTest(utils.TestCase):

View File

@@ -12,28 +12,15 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import urlparse
import requests
from keystoneclient.v2_0 import services from keystoneclient.v2_0 import services
from tests import utils from tests.v2_0 import utils
class ServiceTests(utils.TestCase): class ServiceTests(utils.TestCase):
def setUp(self): def setUp(self):
super(ServiceTests, self).setUp() super(ServiceTests, self).setUp()
self.TEST_REQUEST_HEADERS = {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_POST_HEADERS = {
'Content-Type': 'application/json',
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_SERVICES = { self.TEST_SERVICES = {
"OS-KSADM:services": { "OS-KSADM:services": {
"values": [ "values": [
@@ -53,6 +40,7 @@ class ServiceTests(utils.TestCase):
}, },
} }
@httpretty.activate
def test_create(self): def test_create(self):
req_body = { req_body = {
"OS-KSADM:service": { "OS-KSADM:service": {
@@ -69,19 +57,7 @@ class ServiceTests(utils.TestCase):
"id": 3, "id": 3,
} }
} }
resp = utils.TestResponse({ self.stub_url(httpretty.POST, ['OS-KSADM', 'services'], json=resp_body)
"status_code": 200,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/services'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
service = self.client.services.create( service = self.client.services.create(
req_body['OS-KSADM:service']['name'], req_body['OS-KSADM:service']['name'],
@@ -90,37 +66,21 @@ class ServiceTests(utils.TestCase):
self.assertTrue(isinstance(service, services.Service)) self.assertTrue(isinstance(service, services.Service))
self.assertEqual(service.id, 3) self.assertEqual(service.id, 3)
self.assertEqual(service.name, req_body['OS-KSADM:service']['name']) self.assertEqual(service.name, req_body['OS-KSADM:service']['name'])
self.assertRequestBodyIs(json=req_body)
@httpretty.activate
def test_delete(self): def test_delete(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['OS-KSADM', 'services', '1'],
"status_code": 200, status=204)
"text": "",
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/services/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.services.delete(1) self.client.services.delete(1)
@httpretty.activate
def test_get(self): def test_get(self):
test_services = self.TEST_SERVICES['OS-KSADM:services']['values'][0] test_services = self.TEST_SERVICES['OS-KSADM:services']['values'][0]
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps({'OS-KSADM:service': test_services}),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_url(httpretty.GET, ['OS-KSADM', 'services', '1'],
kwargs['headers'] = self.TEST_REQUEST_HEADERS json={'OS-KSADM:service': test_services})
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/services/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
service = self.client.services.get(1) service = self.client.services.get(1)
self.assertTrue(isinstance(service, services.Service)) self.assertTrue(isinstance(service, services.Service))
@@ -128,19 +88,10 @@ class ServiceTests(utils.TestCase):
self.assertEqual(service.name, 'nova') self.assertEqual(service.name, 'nova')
self.assertEqual(service.type, 'compute') self.assertEqual(service.type, 'compute')
@httpretty.activate
def test_list(self): def test_list(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['OS-KSADM', 'services'],
"status_code": 200, json=self.TEST_SERVICES)
"text": json.dumps(self.TEST_SERVICES),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/OS-KSADM/services'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
service_list = self.client.services.list() service_list = self.client.services.list()
[self.assertTrue(isinstance(r, services.Service)) [self.assertTrue(isinstance(r, services.Service))

View File

@@ -21,8 +21,8 @@ from testtools import matchers
from keystoneclient import httpclient from keystoneclient import httpclient
from tests import utils
from tests.v2_0 import fakes from tests.v2_0 import fakes
from tests.v2_0 import utils
DEFAULT_USERNAME = 'username' DEFAULT_USERNAME = 'username'

View File

@@ -12,29 +12,16 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import urlparse
import requests
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.v2_0 import tenants from keystoneclient.v2_0 import tenants
from tests import utils from tests.v2_0 import utils
class TenantTests(utils.TestCase): class TenantTests(utils.TestCase):
def setUp(self): def setUp(self):
super(TenantTests, self).setUp() super(TenantTests, self).setUp()
self.TEST_REQUEST_HEADERS = {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_POST_HEADERS = {
'Content-Type': 'application/json',
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_TENANTS = { self.TEST_TENANTS = {
"tenants": { "tenants": {
"values": [ "values": [
@@ -68,6 +55,7 @@ class TenantTests(utils.TestCase):
}, },
} }
@httpretty.activate
def test_create(self): def test_create(self):
req_body = { req_body = {
"tenant": { "tenant": {
@@ -86,18 +74,8 @@ class TenantTests(utils.TestCase):
"extravalue01": "metadata01", "extravalue01": "metadata01",
} }
} }
resp = utils.TestResponse({ self.stub_url(httpretty.POST, ['tenants'], json=resp_body)
"status_code": 200,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
urlparse.urljoin(self.TEST_URL, 'v2.0/tenants'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
tenant = self.client.tenants.create( tenant = self.client.tenants.create(
req_body['tenant']['name'], req_body['tenant']['name'],
req_body['tenant']['description'], req_body['tenant']['description'],
@@ -109,7 +87,9 @@ class TenantTests(utils.TestCase):
self.assertEqual(tenant.name, "tenantX") self.assertEqual(tenant.name, "tenantX")
self.assertEqual(tenant.description, "Like tenant 9, but better.") self.assertEqual(tenant.description, "Like tenant 9, but better.")
self.assertEqual(tenant.extravalue01, "metadata01") self.assertEqual(tenant.extravalue01, "metadata01")
self.assertRequestBodyIs(json=req_body)
@httpretty.activate
def test_duplicate_create(self): def test_duplicate_create(self):
req_body = { req_body = {
"tenant": { "tenant": {
@@ -125,18 +105,7 @@ class TenantTests(utils.TestCase):
"title": "Conflict", "title": "Conflict",
} }
} }
resp = utils.TestResponse({ self.stub_url(httpretty.POST, ['tenants'], status=409, json=resp_body)
"status_code": 409,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
urlparse.urljoin(self.TEST_URL, 'v2.0/tenants'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
def create_duplicate_tenant(): def create_duplicate_tenant():
self.client.tenants.create(req_body['tenant']['name'], self.client.tenants.create(req_body['tenant']['name'],
@@ -145,108 +114,53 @@ class TenantTests(utils.TestCase):
self.assertRaises(exceptions.Conflict, create_duplicate_tenant) self.assertRaises(exceptions.Conflict, create_duplicate_tenant)
@httpretty.activate
def test_delete(self): def test_delete(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['tenants', '1'], status=204)
"status_code": 204,
"text": "",
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL, 'v2.0/tenants/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.tenants.delete(1) self.client.tenants.delete(1)
@httpretty.activate
def test_get(self): def test_get(self):
resp = utils.TestResponse({ resp = {'tenant': self.TEST_TENANTS['tenants']['values'][2]}
"status_code": 200, self.stub_url(httpretty.GET, ['tenants', '1'], json=resp)
"text": json.dumps({
'tenant': self.TEST_TENANTS['tenants']['values'][2],
}),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL, 'v2.0/tenants/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
t = self.client.tenants.get(1) t = self.client.tenants.get(1)
self.assertTrue(isinstance(t, tenants.Tenant)) self.assertTrue(isinstance(t, tenants.Tenant))
self.assertEqual(t.id, 1) self.assertEqual(t.id, 1)
self.assertEqual(t.name, 'admin') self.assertEqual(t.name, 'admin')
@httpretty.activate
def test_list(self): def test_list(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['tenants'], json=self.TEST_TENANTS)
"status_code": 200,
"text": json.dumps(self.TEST_TENANTS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL, 'v2.0/tenants'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
tenant_list = self.client.tenants.list() tenant_list = self.client.tenants.list()
[self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list] [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list]
@httpretty.activate
def test_list_limit(self): def test_list_limit(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['tenants'], json=self.TEST_TENANTS)
"status_code": 200,
"text": json.dumps(self.TEST_TENANTS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants?limit=1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
tenant_list = self.client.tenants.list(limit=1) tenant_list = self.client.tenants.list(limit=1)
self.assertQueryStringIs({'limit': ['1']})
[self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list] [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list]
@httpretty.activate
def test_list_marker(self): def test_list_marker(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['tenants'], json=self.TEST_TENANTS)
"status_code": 200,
"text": json.dumps(self.TEST_TENANTS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants?marker=1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
tenant_list = self.client.tenants.list(marker=1) tenant_list = self.client.tenants.list(marker=1)
self.assertQueryStringIs({'marker': ['1']})
[self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list] [self.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list]
@httpretty.activate
def test_list_limit_marker(self): def test_list_limit_marker(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['tenants'], json=self.TEST_TENANTS)
"status_code": 200,
"text": json.dumps(self.TEST_TENANTS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants?marker=1&limit=1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
tenant_list = self.client.tenants.list(limit=1, marker=1) 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.assertTrue(isinstance(t, tenants.Tenant)) for t in tenant_list]
@httpretty.activate
def test_update(self): def test_update(self):
req_body = { req_body = {
"tenant": { "tenant": {
@@ -267,19 +181,8 @@ class TenantTests(utils.TestCase):
"extravalue01": "metadataChanged", "extravalue01": "metadataChanged",
}, },
} }
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_url(httpretty.POST, ['tenants', '4'], json=resp_body)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
tenant = self.client.tenants.update( tenant = self.client.tenants.update(
req_body['tenant']['id'], req_body['tenant']['id'],
@@ -289,12 +192,14 @@ class TenantTests(utils.TestCase):
extravalue01=req_body['tenant']['extravalue01'], extravalue01=req_body['tenant']['extravalue01'],
name="dont overwrite priors") name="dont overwrite priors")
self.assertTrue(isinstance(tenant, tenants.Tenant)) self.assertTrue(isinstance(tenant, tenants.Tenant))
self.assertRequestBodyIs(json=req_body)
self.assertEqual(tenant.id, 4) self.assertEqual(tenant.id, 4)
self.assertEqual(tenant.name, "tenantX") self.assertEqual(tenant.name, "tenantX")
self.assertEqual(tenant.description, "I changed you!") self.assertEqual(tenant.description, "I changed you!")
self.assertFalse(tenant.enabled) self.assertFalse(tenant.enabled)
self.assertEqual(tenant.extravalue01, "metadataChanged") self.assertEqual(tenant.extravalue01, "metadataChanged")
@httpretty.activate
def test_update_empty_description(self): def test_update_empty_description(self):
req_body = { req_body = {
"tenant": { "tenant": {
@@ -312,63 +217,40 @@ class TenantTests(utils.TestCase):
"description": "", "description": "",
}, },
} }
resp = utils.TestResponse({ self.stub_url(httpretty.POST, ['tenants', '4'], json=resp_body)
"status_code": 200,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request('POST',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
tenant = self.client.tenants.update(req_body['tenant']['id'], tenant = self.client.tenants.update(req_body['tenant']['id'],
req_body['tenant']['name'], req_body['tenant']['name'],
req_body['tenant']['description'], req_body['tenant']['description'],
req_body['tenant']['enabled']) req_body['tenant']['enabled'])
self.assertTrue(isinstance(tenant, tenants.Tenant)) self.assertTrue(isinstance(tenant, tenants.Tenant))
self.assertRequestBodyIs(json=req_body)
self.assertEqual(tenant.id, 4) self.assertEqual(tenant.id, 4)
self.assertEqual(tenant.name, "tenantX") self.assertEqual(tenant.name, "tenantX")
self.assertEqual(tenant.description, "") self.assertEqual(tenant.description, "")
self.assertFalse(tenant.enabled) self.assertFalse(tenant.enabled)
@httpretty.activate
def test_add_user(self): def test_add_user(self):
resp = utils.TestResponse({ self.stub_url(httpretty.PUT, ['tenants', '4', 'users', 'foo', 'roles',
"status_code": 204, 'OS-KSADM', 'barrr'], status=204)
"text": '',
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('PUT',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.tenants.add_user('4', 'foo', 'barrr') self.client.tenants.add_user('4', 'foo', 'barrr')
@httpretty.activate
def test_remove_user(self): def test_remove_user(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['tenants', '4', 'users', 'foo',
"status_code": 204, 'roles', 'OS-KSADM', 'barrr'],
"text": '', status=204)
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.tenants.remove_user('4', 'foo', 'barrr') self.client.tenants.remove_user('4', 'foo', 'barrr')
@httpretty.activate
def test_tenant_add_user(self): def test_tenant_add_user(self):
self.stub_url(httpretty.PUT, ['tenants', '4', 'users', 'foo', 'roles',
'OS-KSADM', 'barrr'],
status=204)
req_body = { req_body = {
"tenant": { "tenant": {
"id": 4, "id": 4,
@@ -377,26 +259,18 @@ class TenantTests(utils.TestCase):
"enabled": False, "enabled": False,
}, },
} }
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('PUT',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
# make tenant object with manager # make tenant object with manager
tenant = self.client.tenants.resource_class(self.client.tenants, tenant = self.client.tenants.resource_class(self.client.tenants,
req_body['tenant']) req_body['tenant'])
tenant.add_user('foo', 'barrr') tenant.add_user('foo', 'barrr')
self.assertTrue(isinstance(tenant, tenants.Tenant)) self.assertTrue(isinstance(tenant, tenants.Tenant))
@httpretty.activate
def test_tenant_remove_user(self): def test_tenant_remove_user(self):
self.stub_url(httpretty.DELETE, ['tenants', '4', 'users', 'foo',
'roles', 'OS-KSADM', 'barrr'],
status=204)
req_body = { req_body = {
"tenant": { "tenant": {
"id": 4, "id": 4,
@@ -405,18 +279,6 @@ class TenantTests(utils.TestCase):
"enabled": False, "enabled": False,
}, },
} }
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('DELETE',
urlparse.urljoin(self.TEST_URL,
'v2.0/tenants/4/users/foo/roles/OS-KSADM/barrr'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
# make tenant object with manager # make tenant object with manager
tenant = self.client.tenants.resource_class(self.client.tenants, tenant = self.client.tenants.resource_class(self.client.tenants,

View File

@@ -12,37 +12,13 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import urlparse
import requests from tests.v2_0 import utils
from tests import utils
class TokenTests(utils.TestCase): class TokenTests(utils.TestCase):
def setUp(self): @httpretty.activate
super(TokenTests, self).setUp()
self.TEST_REQUEST_HEADERS = {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient'}
self.TEST_POST_HEADERS = {
'Content-Type': 'application/json',
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient'}
def test_delete(self): def test_delete(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['tokens', '1'], status=204)
"status_code": 204,
"text": ""})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request(
'DELETE',
urlparse.urljoin(self.TEST_URL, 'v2.0/tokens/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.tokens.delete(1) self.client.tokens.delete(1)

View File

@@ -12,28 +12,15 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import urlparse
import requests
from keystoneclient.v2_0 import users from keystoneclient.v2_0 import users
from tests import utils from tests.v2_0 import utils
class UserTests(utils.TestCase): class UserTests(utils.TestCase):
def setUp(self): def setUp(self):
super(UserTests, self).setUp() super(UserTests, self).setUp()
self.TEST_REQUEST_HEADERS = {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_POST_HEADERS = {
'Content-Type': 'application/json',
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
self.TEST_USERS = { self.TEST_USERS = {
"users": { "users": {
"values": [ "values": [
@@ -53,6 +40,7 @@ class UserTests(utils.TestCase):
} }
} }
@httpretty.activate
def test_create(self): def test_create(self):
req_body = { req_body = {
"user": { "user": {
@@ -63,6 +51,7 @@ class UserTests(utils.TestCase):
"enabled": True, "enabled": True,
} }
} }
resp_body = { resp_body = {
"user": { "user": {
"name": "gabriel", "name": "gabriel",
@@ -73,19 +62,8 @@ class UserTests(utils.TestCase):
"email": "test@example.com", "email": "test@example.com",
} }
} }
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(resp_body),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_url(httpretty.POST, ['users'], json=resp_body)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request(
'POST',
urlparse.urljoin(self.TEST_URL, 'v2.0/users'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
user = self.client.users.create(req_body['user']['name'], user = self.client.users.create(req_body['user']['name'],
req_body['user']['password'], req_body['user']['password'],
@@ -96,112 +74,59 @@ class UserTests(utils.TestCase):
self.assertEqual(user.id, 3) self.assertEqual(user.id, 3)
self.assertEqual(user.name, "gabriel") self.assertEqual(user.name, "gabriel")
self.assertEqual(user.email, "test@example.com") self.assertEqual(user.email, "test@example.com")
self.assertRequestBodyIs(json=req_body)
@httpretty.activate
def test_delete(self): def test_delete(self):
resp = utils.TestResponse({ self.stub_url(httpretty.DELETE, ['users', '1'], status=204)
"status_code": 204,
"text": "",
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request(
'DELETE',
urlparse.urljoin(self.TEST_URL, 'v2.0/users/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.users.delete(1) self.client.users.delete(1)
@httpretty.activate
def test_get(self): def test_get(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['users', '1'],
"status_code": 200, json={'user': self.TEST_USERS['users']['values'][0]})
"text": json.dumps({
'user': self.TEST_USERS['users']['values'][0],
})
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request(
'GET',
urlparse.urljoin(self.TEST_URL, 'v2.0/users/1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
u = self.client.users.get(1) u = self.client.users.get(1)
self.assertTrue(isinstance(u, users.User)) self.assertTrue(isinstance(u, users.User))
self.assertEqual(u.id, 1) self.assertEqual(u.id, 1)
self.assertEqual(u.name, 'admin') self.assertEqual(u.name, 'admin')
@httpretty.activate
def test_list(self): def test_list(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['users'], json=self.TEST_USERS)
"status_code": 200,
"text": json.dumps(self.TEST_USERS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request(
'GET',
urlparse.urljoin(self.TEST_URL, 'v2.0/users'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
user_list = self.client.users.list() user_list = self.client.users.list()
[self.assertTrue(isinstance(u, users.User)) for u in user_list] [self.assertTrue(isinstance(u, users.User)) for u in user_list]
@httpretty.activate
def test_list_limit(self): def test_list_limit(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['users'], json=self.TEST_USERS)
"status_code": 200,
"text": json.dumps(self.TEST_USERS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request(
'GET',
urlparse.urljoin(self.TEST_URL, 'v2.0/users?limit=1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
user_list = self.client.users.list(limit=1) 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.assertTrue(isinstance(u, users.User)) for u in user_list]
@httpretty.activate
def test_list_marker(self): def test_list_marker(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['users'], json=self.TEST_USERS)
"status_code": 200,
"text": json.dumps(self.TEST_USERS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request(
'GET',
urlparse.urljoin(self.TEST_URL, 'v2.0/users?marker=foo'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
user_list = self.client.users.list(marker='foo') 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.assertTrue(isinstance(u, users.User)) for u in user_list]
@httpretty.activate
def test_list_limit_marker(self): def test_list_limit_marker(self):
resp = utils.TestResponse({ self.stub_url(httpretty.GET, ['users'], json=self.TEST_USERS)
"status_code": 200,
"text": json.dumps(self.TEST_USERS),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request(
'GET',
urlparse.urljoin(self.TEST_URL, 'v2.0/users?marker=foo&limit=1'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
user_list = self.client.users.list(limit=1, marker='foo') user_list = self.client.users.list(limit=1, marker='foo')
self.assertDictEqual(httpretty.last_request().querystring,
{'marker': ['foo'], 'limit': ['1']})
[self.assertTrue(isinstance(u, users.User)) for u in user_list] [self.assertTrue(isinstance(u, users.User)) for u in user_list]
@httpretty.activate
def test_update(self): def test_update(self):
req_1 = { req_1 = {
"user": { "user": {
@@ -229,61 +154,26 @@ class UserTests(utils.TestCase):
} }
} }
# Keystone basically echoes these back... including the password :-/ self.stub_url(httpretty.PUT, ['users', '2'], json=req_1)
resp_1 = utils.TestResponse({ self.stub_url(httpretty.PUT, ['users', '2', 'OS-KSADM', 'password'],
"status_code": 200, json=req_2)
"text": json.dumps(req_1) self.stub_url(httpretty.PUT, ['users', '2', 'OS-KSADM', 'tenant'],
}) json=req_3)
resp_2 = utils.TestResponse({ self.stub_url(httpretty.PUT, ['users', '2', 'OS-KSADM', 'enabled'],
"status_code": 200, json=req_4)
"text": json.dumps(req_2)
})
resp_3 = utils.TestResponse({
"status_code": 200,
"text": json.dumps(req_3)
})
resp_4 = utils.TestResponse({
"status_code": 200,
"text": json.dumps(req_4)
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_1)
requests.request(
'PUT',
urlparse.urljoin(self.TEST_URL, 'v2.0/users/2'),
**kwargs).AndReturn((resp_1))
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_2)
requests.request(
'PUT',
urlparse.urljoin(self.TEST_URL, 'v2.0/users/2/OS-KSADM/password'),
**kwargs).AndReturn((resp_2))
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_3)
requests.request(
'PUT',
urlparse.urljoin(self.TEST_URL, 'v2.0/users/2/OS-KSADM/tenant'),
**kwargs).AndReturn((resp_3))
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_4)
requests.request(
'PUT',
urlparse.urljoin(self.TEST_URL, 'v2.0/users/2/OS-KSADM/enabled'),
**kwargs).AndReturn((resp_4))
self.mox.ReplayAll()
self.client.users.update(2, self.client.users.update(2,
name='gabriel', name='gabriel',
email='gabriel@example.com') email='gabriel@example.com')
self.assertRequestBodyIs(json=req_1)
self.client.users.update_password(2, 'swordfish') self.client.users.update_password(2, 'swordfish')
self.assertRequestBodyIs(json=req_2)
self.client.users.update_tenant(2, 1) self.client.users.update_tenant(2, 1)
self.assertRequestBodyIs(json=req_3)
self.client.users.update_enabled(2, False) self.client.users.update_enabled(2, False)
self.assertRequestBodyIs(json=req_4)
@httpretty.activate
def test_update_own_password(self): def test_update_own_password(self):
req_body = { req_body = {
'user': { 'user': {
@@ -293,20 +183,9 @@ class UserTests(utils.TestCase):
resp_body = { resp_body = {
'access': {} 'access': {}
} }
resp = utils.TestResponse({ self.stub_url(httpretty.PATCH, ['OS-KSCRUD', 'users', '123'],
"status_code": 200, json=resp_body)
"text": json.dumps(resp_body)
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_POST_HEADERS
kwargs['data'] = json.dumps(req_body)
requests.request(
'PATCH',
urlparse.urljoin(self.TEST_URL, 'v2.0/OS-KSCRUD/users/123'),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.client.user_id = '123' self.client.user_id = '123'
self.client.users.update_own_password('DCBA', 'ABCD') self.client.users.update_own_password('DCBA', 'ABCD')
self.assertRequestBodyIs(json=req_body)

90
tests/v2_0/utils.py Normal file
View File

@@ -0,0 +1,90 @@
# 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
#
# 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.v2_0 import client
from tests import utils
TestResponse = utils.TestResponse
class UnauthenticatedTestCase(utils.TestCase):
"""Class used as base for unauthenticated calls."""
TEST_ROOT_URL = 'http://127.0.0.1:5000/'
TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v2.0')
TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/'
TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v2.0')
class TestCase(UnauthenticatedTestCase):
TEST_SERVICE_CATALOG = [{
"endpoints": [{
"adminURL": "http://cdn.admin-nets.local:8774/v1.0",
"region": "RegionOne",
"internalURL": "http://127.0.0.1:8774/v1.0",
"publicURL": "http://cdn.admin-nets.local:8774/v1.0/"
}],
"type": "nova_compat",
"name": "nova_compat"
}, {
"endpoints": [{
"adminURL": "http://nova/novapi/admin",
"region": "RegionOne",
"internalURL": "http://nova/novapi/internal",
"publicURL": "http://nova/novapi/public"
}],
"type": "compute",
"name": "nova"
}, {
"endpoints": [{
"adminURL": "http://glance/glanceapi/admin",
"region": "RegionOne",
"internalURL": "http://glance/glanceapi/internal",
"publicURL": "http://glance/glanceapi/public"
}],
"type": "image",
"name": "glance"
}, {
"endpoints": [{
"adminURL": "http://127.0.0.1:35357/v2.0",
"region": "RegionOne",
"internalURL": "http://127.0.0.1:5000/v2.0",
"publicURL": "http://127.0.0.1:5000/v2.0"
}],
"type": "identity",
"name": "keystone"
}, {
"endpoints": [{
"adminURL": "http://swift/swiftapi/admin",
"region": "RegionOne",
"internalURL": "http://swift/swiftapi/internal",
"publicURL": "http://swift/swiftapi/public"
}],
"type": "object-store",
"name": "swift"
}]
def setUp(self):
super(TestCase, self).setUp()
self.client = client.Client(username=self.TEST_USER,
token=self.TEST_TOKEN,
tenant_name=self.TEST_TENANT_NAME,
auth_url=self.TEST_URL,
endpoint=self.TEST_URL)
def stub_auth(self, **kwargs):
self.stub_url(httpretty.POST, ['tokens'], **kwargs)

View File

@@ -162,8 +162,10 @@ PROJECT_SCOPED_TOKEN = {
} }
} }
AUTH_SUBJECT_TOKEN = '3e2813b7ba0b4006840c3825860b86ed'
AUTH_RESPONSE_HEADERS = { AUTH_RESPONSE_HEADERS = {
'X-Subject-Token': '3e2813b7ba0b4006840c3825860b86ed' 'X-Subject-Token': AUTH_SUBJECT_TOKEN
} }
AUTH_RESPONSE_BODY = { AUTH_RESPONSE_BODY = {

View File

@@ -16,8 +16,8 @@ import datetime
from keystoneclient import access from keystoneclient import access
from keystoneclient.openstack.common import timeutils from keystoneclient.openstack.common import timeutils
from tests import utils
from tests.v3 import client_fixtures from tests.v3 import client_fixtures
from tests.v3 import utils
TOKEN_RESPONSE = utils.TestResponse({ TOKEN_RESPONSE = utils.TestResponse({
"headers": client_fixtures.AUTH_RESPONSE_HEADERS "headers": client_fixtures.AUTH_RESPONSE_HEADERS

View File

@@ -12,9 +12,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy import httpretty
import json
import requests
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.v3 import client from keystoneclient.v3 import client
@@ -82,53 +80,31 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
'X-Subject-Token': self.TEST_TOKEN 'X-Subject-Token': self.TEST_TOKEN
} }
@httpretty.activate
def test_authenticate_success(self): def test_authenticate_success(self):
TEST_TOKEN = "abcdef" TEST_TOKEN = "abcdef"
self.TEST_RESPONSE_HEADERS['X-Subject-Token'] = TEST_TOKEN
ident = self.TEST_REQUEST_BODY['auth']['identity'] ident = self.TEST_REQUEST_BODY['auth']['identity']
del ident['password']['user']['domain'] del ident['password']['user']['domain']
del ident['password']['user']['name'] del ident['password']['user']['name']
ident['password']['user']['id'] = self.TEST_USER ident['password']['user']['id'] = self.TEST_USER
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT, subject_token=TEST_TOKEN)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(user_id=self.TEST_USER, cs = client.Client(user_id=self.TEST_USER,
password=self.TEST_TOKEN, password=self.TEST_TOKEN,
project_id=self.TEST_TENANT_ID, project_id=self.TEST_TENANT_ID,
auth_url=self.TEST_URL) auth_url=self.TEST_URL)
self.assertEqual(cs.auth_token, TEST_TOKEN) self.assertEqual(cs.auth_token, TEST_TOKEN)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_failure(self): def test_authenticate_failure(self):
ident = self.TEST_REQUEST_BODY['auth']['identity'] ident = self.TEST_REQUEST_BODY['auth']['identity']
ident['password']['user']['password'] = 'bad_key' ident['password']['user']['password'] = 'bad_key'
resp = utils.TestResponse({ error = {"unauthorized": {"message": "Unauthorized",
"status_code": 401, "code": "401"}}
"text": json.dumps({
"unauthorized": {
"message": "Unauthorized",
"code": "401",
},
}),
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(status=401, json=error)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
# Workaround for issue with assertRaises on python2.6 # Workaround for issue with assertRaises on python2.6
# where with assertRaises(exceptions.Unauthorized): doesn't work # where with assertRaises(exceptions.Unauthorized): doesn't work
@@ -141,40 +117,15 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
auth_url=self.TEST_URL) auth_url=self.TEST_URL)
self.assertRaises(exceptions.Unauthorized, client_create_wrapper) self.assertRaises(exceptions.Unauthorized, client_create_wrapper)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_auth_redirect(self): def test_auth_redirect(self):
correct_response = json.dumps(self.TEST_RESPONSE_DICT, sort_keys=True) self.stub_auth(status=305, body='Use proxy',
dict_responses = [ location=self.TEST_ADMIN_URL + '/auth/tokens')
{
"headers": {
'location': self.TEST_ADMIN_URL + "/auth/tokens",
'X-Subject-Token': self.TEST_TOKEN,
},
"status_code": 305,
"text": "Use proxy",
},
{
"headers": {'X-Subject-Token': self.TEST_TOKEN},
"status_code": 200,
"text": correct_response,
},
]
responses = [(utils.TestResponse(resp))
for resp in dict_responses]
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT,
kwargs['headers'] = self.TEST_REQUEST_HEADERS base_url=self.TEST_ADMIN_URL)
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn(responses[0])
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_ADMIN_URL + "/auth/tokens",
**kwargs).AndReturn(responses[1])
self.mox.ReplayAll()
cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME, cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME,
username=self.TEST_USER, username=self.TEST_USER,
@@ -188,20 +139,9 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
@httpretty.activate
def test_authenticate_success_domain_username_password_scoped(self): def test_authenticate_success_domain_username_password_scoped(self):
resp = utils.TestResponse({ self.stub_auth(json=self.TEST_RESPONSE_DICT)
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME, cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME,
username=self.TEST_USER, username=self.TEST_USER,
@@ -214,6 +154,7 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
@httpretty.activate
def test_authenticate_success_userid_password_domain_scoped(self): def test_authenticate_success_userid_password_domain_scoped(self):
ident = self.TEST_REQUEST_BODY['auth']['identity'] ident = self.TEST_REQUEST_BODY['auth']['identity']
del ident['password']['user']['domain'] del ident['password']['user']['domain']
@@ -231,20 +172,7 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
token['domain']['id'] = self.TEST_DOMAIN_ID token['domain']['id'] = self.TEST_DOMAIN_ID
token['domain']['name'] = self.TEST_DOMAIN_NAME token['domain']['name'] = self.TEST_DOMAIN_NAME
resp = utils.TestResponse({ self.stub_auth(json=self.TEST_RESPONSE_DICT)
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(user_id=self.TEST_USER, cs = client.Client(user_id=self.TEST_USER,
password=self.TEST_TOKEN, password=self.TEST_TOKEN,
@@ -257,27 +185,16 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
['endpoints'][2]["url"]) ['endpoints'][2]["url"])
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_userid_password_project_scoped(self): def test_authenticate_success_userid_password_project_scoped(self):
ident = self.TEST_REQUEST_BODY['auth']['identity'] ident = self.TEST_REQUEST_BODY['auth']['identity']
del ident['password']['user']['domain'] del ident['password']['user']['domain']
del ident['password']['user']['name'] del ident['password']['user']['name']
ident['password']['user']['id'] = self.TEST_USER ident['password']['user']['id'] = self.TEST_USER
resp = utils.TestResponse({ self.stub_auth(json=self.TEST_RESPONSE_DICT)
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(user_id=self.TEST_USER, cs = client.Client(user_id=self.TEST_USER,
password=self.TEST_TOKEN, password=self.TEST_TOKEN,
@@ -290,23 +207,14 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
['endpoints'][2]["url"]) ['endpoints'][2]["url"])
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_password_unscoped(self): def test_authenticate_success_password_unscoped(self):
del self.TEST_RESPONSE_DICT['token']['catalog'] del self.TEST_RESPONSE_DICT['token']['catalog']
del self.TEST_REQUEST_BODY['auth']['scope'] del self.TEST_REQUEST_BODY['auth']['scope']
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME, cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME,
username=self.TEST_USER, username=self.TEST_USER,
@@ -315,7 +223,9 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
self.assertFalse('catalog' in cs.service_catalog.catalog) self.assertFalse('catalog' in cs.service_catalog.catalog)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_token_domain_scoped(self): def test_authenticate_success_token_domain_scoped(self):
ident = self.TEST_REQUEST_BODY['auth']['identity'] ident = self.TEST_REQUEST_BODY['auth']['identity']
del ident['password'] del ident['password']
@@ -335,19 +245,8 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
token['domain']['name'] = self.TEST_DOMAIN_NAME token['domain']['name'] = self.TEST_DOMAIN_NAME
self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(token=self.TEST_TOKEN, cs = client.Client(token=self.TEST_TOKEN,
domain_id=self.TEST_DOMAIN_ID, domain_id=self.TEST_DOMAIN_ID,
@@ -359,7 +258,9 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
['endpoints'][2]["url"]) ['endpoints'][2]["url"])
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_token_project_scoped(self): def test_authenticate_success_token_project_scoped(self):
ident = self.TEST_REQUEST_BODY['auth']['identity'] ident = self.TEST_REQUEST_BODY['auth']['identity']
del ident['password'] del ident['password']
@@ -367,19 +268,8 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
ident['token'] = {} ident['token'] = {}
ident['token']['id'] = self.TEST_TOKEN ident['token']['id'] = self.TEST_TOKEN
self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(token=self.TEST_TOKEN, cs = client.Client(token=self.TEST_TOKEN,
project_id=self.TEST_TENANT_ID, project_id=self.TEST_TENANT_ID,
@@ -391,7 +281,9 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
['endpoints'][2]["url"]) ['endpoints'][2]["url"])
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
@httpretty.activate
def test_authenticate_success_token_unscoped(self): def test_authenticate_success_token_unscoped(self):
ident = self.TEST_REQUEST_BODY['auth']['identity'] ident = self.TEST_REQUEST_BODY['auth']['identity']
del ident['password'] del ident['password']
@@ -401,22 +293,12 @@ class AuthenticateAgainstKeystoneTests(utils.TestCase):
del self.TEST_REQUEST_BODY['auth']['scope'] del self.TEST_REQUEST_BODY['auth']['scope']
del self.TEST_RESPONSE_DICT['token']['catalog'] del self.TEST_RESPONSE_DICT['token']['catalog']
self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN
resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(self.TEST_RESPONSE_DICT),
"headers": self.TEST_RESPONSE_HEADERS,
})
kwargs = copy.copy(self.TEST_REQUEST_BASE) self.stub_auth(json=self.TEST_RESPONSE_DICT)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY, sort_keys=True)
requests.request('POST',
self.TEST_URL + "/auth/tokens",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client(token=self.TEST_TOKEN, cs = client.Client(token=self.TEST_TOKEN,
auth_url=self.TEST_URL) auth_url=self.TEST_URL)
self.assertEqual(cs.auth_token, self.assertEqual(cs.auth_token,
self.TEST_RESPONSE_HEADERS["X-Subject-Token"]) self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
self.assertFalse('catalog' in cs.service_catalog.catalog) self.assertFalse('catalog' in cs.service_catalog.catalog)
self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

View File

@@ -13,148 +13,122 @@
# under the License. # under the License.
import json import json
import mock
import requests import httpretty
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.v3 import client from keystoneclient.v3 import client
from tests import utils
from tests.v3 import client_fixtures from tests.v3 import client_fixtures
from tests.v3 import utils
class KeystoneClientTest(utils.TestCase): class KeystoneClientTest(utils.TestCase):
def setUp(self):
super(KeystoneClientTest, self).setUp()
domain_scoped_fake_resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(client_fixtures.DOMAIN_SCOPED_TOKEN),
"headers": client_fixtures.AUTH_RESPONSE_HEADERS
})
self.domain_scoped_mock_req = mock.Mock(
return_value=domain_scoped_fake_resp)
project_scoped_fake_resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(client_fixtures.PROJECT_SCOPED_TOKEN),
"headers": client_fixtures.AUTH_RESPONSE_HEADERS
})
self.project_scoped_mock_req = mock.Mock(
return_value=project_scoped_fake_resp)
unscoped_fake_resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(client_fixtures.UNSCOPED_TOKEN),
"headers": client_fixtures.AUTH_RESPONSE_HEADERS
})
self.unscoped_mock_req = mock.Mock(return_value=unscoped_fake_resp)
trust_fake_resp = utils.TestResponse({
"status_code": 200,
"text": json.dumps(client_fixtures.TRUST_TOKEN),
"headers": client_fixtures.AUTH_RESPONSE_HEADERS
})
self.trust_mock_req = mock.Mock(return_value=trust_fake_resp)
@httpretty.activate
def test_unscoped_init(self): def test_unscoped_init(self):
with mock.patch.object(requests, "request", self.unscoped_mock_req): self.stub_auth(json=client_fixtures.UNSCOPED_TOKEN)
c = client.Client(user_domain_name='exampledomain',
username='exampleuser',
password='password',
auth_url='http://somewhere/')
self.assertIsNotNone(c.auth_ref)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertFalse(c.auth_ref.project_scoped)
self.assertEquals(c.auth_user_id,
'c4da488862bd435c9e6c0275a0d0e49a')
c = client.Client(user_domain_name='exampledomain',
username='exampleuser',
password='password',
auth_url=self.TEST_URL)
self.assertIsNotNone(c.auth_ref)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertFalse(c.auth_ref.project_scoped)
self.assertEquals(c.auth_user_id,
'c4da488862bd435c9e6c0275a0d0e49a')
@httpretty.activate
def test_domain_scoped_init(self): def test_domain_scoped_init(self):
with mock.patch.object(requests, self.stub_auth(json=client_fixtures.DOMAIN_SCOPED_TOKEN)
"request",
self.domain_scoped_mock_req):
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
domain_name='exampledomain',
auth_url='http://somewhere/')
self.assertIsNotNone(c.auth_ref)
self.assertTrue(c.auth_ref.domain_scoped)
self.assertFalse(c.auth_ref.project_scoped)
self.assertEquals(c.auth_user_id,
'c4da488862bd435c9e6c0275a0d0e49a')
self.assertEquals(c.auth_domain_id,
'8e9283b7ba0b1038840c3842058b86ab')
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
domain_name='exampledomain',
auth_url=self.TEST_URL)
self.assertIsNotNone(c.auth_ref)
self.assertTrue(c.auth_ref.domain_scoped)
self.assertFalse(c.auth_ref.project_scoped)
self.assertEquals(c.auth_user_id,
'c4da488862bd435c9e6c0275a0d0e49a')
self.assertEquals(c.auth_domain_id,
'8e9283b7ba0b1038840c3842058b86ab')
@httpretty.activate
def test_project_scoped_init(self): def test_project_scoped_init(self):
with mock.patch.object(requests, self.stub_auth(json=client_fixtures.PROJECT_SCOPED_TOKEN),
"request",
self.project_scoped_mock_req):
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
user_domain_name='exampledomain',
project_name='exampleproject',
auth_url='http://somewhere/')
self.assertIsNotNone(c.auth_ref)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertTrue(c.auth_ref.project_scoped)
self.assertEquals(c.auth_user_id,
'c4da488862bd435c9e6c0275a0d0e49a')
self.assertEquals(c.auth_tenant_id,
'225da22d3ce34b15877ea70b2a575f58')
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
user_domain_name='exampledomain',
project_name='exampleproject',
auth_url=self.TEST_URL)
self.assertIsNotNone(c.auth_ref)
self.assertFalse(c.auth_ref.domain_scoped)
self.assertTrue(c.auth_ref.project_scoped)
self.assertEquals(c.auth_user_id,
'c4da488862bd435c9e6c0275a0d0e49a')
self.assertEquals(c.auth_tenant_id,
'225da22d3ce34b15877ea70b2a575f58')
@httpretty.activate
def test_auth_ref_load(self): def test_auth_ref_load(self):
with mock.patch.object(requests, self.stub_auth(json=client_fixtures.PROJECT_SCOPED_TOKEN)
"request",
self.project_scoped_mock_req):
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
project_id='225da22d3ce34b15877ea70b2a575f58',
auth_url='http://somewhere/')
cache = json.dumps(c.auth_ref)
new_client = client.Client(auth_ref=json.loads(cache))
self.assertIsNotNone(new_client.auth_ref)
self.assertFalse(new_client.auth_ref.domain_scoped)
self.assertTrue(new_client.auth_ref.project_scoped)
self.assertEquals(new_client.username, 'exampleuser')
self.assertIsNone(new_client.password)
self.assertEqual(new_client.management_url,
'http://admin:35357/v3')
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
project_id='225da22d3ce34b15877ea70b2a575f58',
auth_url=self.TEST_URL)
cache = json.dumps(c.auth_ref)
new_client = client.Client(auth_ref=json.loads(cache))
self.assertIsNotNone(new_client.auth_ref)
self.assertFalse(new_client.auth_ref.domain_scoped)
self.assertTrue(new_client.auth_ref.project_scoped)
self.assertEquals(new_client.username, 'exampleuser')
self.assertIsNone(new_client.password)
self.assertEqual(new_client.management_url,
'http://admin:35357/v3')
@httpretty.activate
def test_auth_ref_load_with_overridden_arguments(self): def test_auth_ref_load_with_overridden_arguments(self):
with mock.patch.object(requests, new_auth_url = 'https://newkeystone.com/v3'
"request",
self.project_scoped_mock_req):
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
project_id='225da22d3ce34b15877ea70b2a575f58',
auth_url='http://somewhere/')
cache = json.dumps(c.auth_ref)
new_auth_url = "http://new-public:5000/v3"
new_client = client.Client(auth_ref=json.loads(cache),
auth_url=new_auth_url)
self.assertIsNotNone(new_client.auth_ref)
self.assertFalse(new_client.auth_ref.domain_scoped)
self.assertTrue(new_client.auth_ref.project_scoped)
self.assertEquals(new_client.auth_url, new_auth_url)
self.assertEquals(new_client.username, 'exampleuser')
self.assertIsNone(new_client.password)
self.assertEqual(new_client.management_url,
'http://admin:35357/v3')
self.stub_auth(json=client_fixtures.PROJECT_SCOPED_TOKEN)
self.stub_auth(json=client_fixtures.PROJECT_SCOPED_TOKEN,
base_url=new_auth_url)
c = client.Client(user_id='c4da488862bd435c9e6c0275a0d0e49a',
password='password',
project_id='225da22d3ce34b15877ea70b2a575f58',
auth_url=self.TEST_URL)
cache = json.dumps(c.auth_ref)
new_client = client.Client(auth_ref=json.loads(cache),
auth_url=new_auth_url)
self.assertIsNotNone(new_client.auth_ref)
self.assertFalse(new_client.auth_ref.domain_scoped)
self.assertTrue(new_client.auth_ref.project_scoped)
self.assertEquals(new_client.auth_url, new_auth_url)
self.assertEquals(new_client.username, 'exampleuser')
self.assertIsNone(new_client.password)
self.assertEqual(new_client.management_url,
'http://admin:35357/v3')
@httpretty.activate
def test_trust_init(self): def test_trust_init(self):
with mock.patch.object(requests, "request", self.trust_mock_req): self.stub_auth(json=client_fixtures.TRUST_TOKEN)
c = client.Client(user_domain_name='exampledomain',
username='exampleuser', c = client.Client(user_domain_name='exampledomain',
password='password', username='exampleuser',
auth_url='http://somewhere/', password='password',
trust_id='fe0aef') auth_url=self.TEST_URL,
self.assertIsNotNone(c.auth_ref) trust_id='fe0aef')
self.assertFalse(c.auth_ref.domain_scoped) self.assertIsNotNone(c.auth_ref)
self.assertFalse(c.auth_ref.project_scoped) self.assertFalse(c.auth_ref.domain_scoped)
self.assertEqual(c.auth_ref.trust_id, 'fe0aef') self.assertFalse(c.auth_ref.project_scoped)
self.assertTrue(c.auth_ref.trust_scoped) self.assertEqual(c.auth_ref.trust_id, 'fe0aef')
self.assertEquals(c.auth_user_id, '0ca8f6') self.assertTrue(c.auth_ref.trust_scoped)
self.assertEquals(c.auth_user_id, '0ca8f6')
def test_init_err_no_auth_url(self): def test_init_err_no_auth_url(self):
self.assertRaises(exceptions.AuthorizationFailure, self.assertRaises(exceptions.AuthorizationFailure,

View File

@@ -21,7 +21,6 @@ from tests.v3 import utils
class CredentialTests(utils.TestCase, utils.CrudTests): class CredentialTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(CredentialTests, self).setUp() super(CredentialTests, self).setUp()
self.additionalSetUp()
self.key = 'credential' self.key = 'credential'
self.collection_key = 'credentials' self.collection_key = 'credentials'
self.model = credentials.Credential self.model = credentials.Credential

View File

@@ -12,12 +12,12 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import json import json
import requests
import httpretty
from keystoneclient.generic import client from keystoneclient.generic import client
from tests import utils from tests.v3 import utils
class DiscoverKeystoneTests(utils.UnauthenticatedTestCase): class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
@@ -66,17 +66,11 @@ class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
'Accept': 'application/json', 'Accept': 'application/json',
} }
@httpretty.activate
def test_get_version_local(self): def test_get_version_local(self):
resp = utils.TestResponse({ httpretty.register_uri(httpretty.GET, "http://localhost:35357/",
"status_code": 300, status=300,
"text": json.dumps(self.TEST_RESPONSE_DICT), body=json.dumps(self.TEST_RESPONSE_DICT))
})
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.TEST_REQUEST_HEADERS
requests.request('GET',
"http://localhost:35357",
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
cs = client.Client() cs = client.Client()
versions = cs.discover() versions = cs.discover()

View File

@@ -21,7 +21,6 @@ from tests.v3 import utils
class DomainTests(utils.TestCase, utils.CrudTests): class DomainTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(DomainTests, self).setUp() super(DomainTests, self).setUp()
self.additionalSetUp()
self.key = 'domain' self.key = 'domain'
self.collection_key = 'domains' self.collection_key = 'domains'
self.model = domains.Domain self.model = domains.Domain

View File

@@ -21,7 +21,6 @@ from tests.v3 import utils
class EndpointTests(utils.TestCase, utils.CrudTests): class EndpointTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(EndpointTests, self).setUp() super(EndpointTests, self).setUp()
self.additionalSetUp()
self.key = 'endpoint' self.key = 'endpoint'
self.collection_key = 'endpoints' self.collection_key = 'endpoints'
self.model = endpoints.Endpoint self.model = endpoints.Endpoint

View File

@@ -14,11 +14,9 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import urlparse
import uuid import uuid
import requests import httpretty
from keystoneclient.v3 import groups from keystoneclient.v3 import groups
from tests.v3 import utils from tests.v3 import utils
@@ -27,7 +25,6 @@ from tests.v3 import utils
class GroupTests(utils.TestCase, utils.CrudTests): class GroupTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(GroupTests, self).setUp() super(GroupTests, self).setUp()
self.additionalSetUp()
self.key = 'group' self.key = 'group'
self.collection_key = 'groups' self.collection_key = 'groups'
self.model = groups.Group self.model = groups.Group
@@ -38,50 +35,31 @@ class GroupTests(utils.TestCase, utils.CrudTests):
kwargs.setdefault('name', uuid.uuid4().hex) kwargs.setdefault('name', uuid.uuid4().hex)
return kwargs return kwargs
@httpretty.activate
def test_list_groups_for_user(self): def test_list_groups_for_user(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['users', user_id, self.collection_key],
kwargs['headers'] = self.headers[method] status=200, entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/users/%s/%s' % (
user_id, self.collection_key)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned_list = self.manager.list(user=user_id) returned_list = self.manager.list(user=user_id)
self.assertTrue(len(returned_list)) self.assertTrue(len(returned_list))
[self.assertTrue(isinstance(r, self.model)) for r in returned_list] [self.assertTrue(isinstance(r, self.model)) for r in returned_list]
@httpretty.activate
def test_list_groups_for_domain(self): def test_list_groups_for_domain(self):
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) [self.collection_key],
kwargs['headers'] = self.headers[method] status=200, entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/%s?domain_id=%s' % (self.collection_key, domain_id)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned_list = self.manager.list(domain=domain_id) returned_list = self.manager.list(domain=domain_id)
self.assertTrue(len(returned_list)) self.assertTrue(len(returned_list))
[self.assertTrue(isinstance(r, self.model)) for r in returned_list] [self.assertTrue(isinstance(r, self.model)) for r in returned_list]
self.assertEqual(httpretty.last_request().querystring,
{'domain_id': [domain_id]})

View File

@@ -21,7 +21,6 @@ from tests.v3 import utils
class PolicyTests(utils.TestCase, utils.CrudTests): class PolicyTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(PolicyTests, self).setUp() super(PolicyTests, self).setUp()
self.additionalSetUp()
self.key = 'policy' self.key = 'policy'
self.collection_key = 'policies' self.collection_key = 'policies'
self.model = policies.Policy self.model = policies.Policy

View File

@@ -12,11 +12,9 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import urlparse
import uuid import uuid
import requests import httpretty
from keystoneclient.v3 import projects from keystoneclient.v3 import projects
from tests.v3 import utils from tests.v3 import utils
@@ -25,7 +23,6 @@ from tests.v3 import utils
class ProjectTests(utils.TestCase, utils.CrudTests): class ProjectTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(ProjectTests, self).setUp() super(ProjectTests, self).setUp()
self.additionalSetUp()
self.key = 'project' self.key = 'project'
self.collection_key = 'projects' self.collection_key = 'projects'
self.model = projects.Project self.model = projects.Project
@@ -38,50 +35,30 @@ class ProjectTests(utils.TestCase, utils.CrudTests):
kwargs.setdefault('name', uuid.uuid4().hex) kwargs.setdefault('name', uuid.uuid4().hex)
return kwargs return kwargs
@httpretty.activate
def test_list_projects_for_user(self): def test_list_projects_for_user(self):
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
resp = utils.TestResponse({
"status-code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['users', user_id, self.collection_key],
kwargs['headers'] = self.headers[method] entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/users/%s/%s' % (user_id, self.collection_key)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned_list = self.manager.list(user=user_id) returned_list = self.manager.list(user=user_id)
self.assertTrue(len(returned_list)) self.assertTrue(len(returned_list))
[self.assertTrue(isinstance(r, self.model)) for r in returned_list] [self.assertTrue(isinstance(r, self.model)) for r in returned_list]
@httpretty.activate
def test_list_projects_for_domain(self): def test_list_projects_for_domain(self):
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET, [self.collection_key],
kwargs = copy.copy(self.TEST_REQUEST_BASE) entity=ref_list)
kwargs['headers'] = self.headers[method]
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/%s?domain_id=%s' % (self.collection_key, domain_id)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned_list = self.manager.list(domain=domain_id) returned_list = self.manager.list(domain=domain_id)
self.assertTrue(len(returned_list)) self.assertTrue(len(returned_list))
[self.assertTrue(isinstance(r, self.model)) for r in returned_list] [self.assertTrue(isinstance(r, self.model)) for r in returned_list]
self.assertEqual(httpretty.last_request().querystring,
{'domain_id': [domain_id]})

View File

@@ -14,11 +14,9 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import urlparse
import uuid import uuid
import requests import httpretty
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.v3 import roles from keystoneclient.v3 import roles
@@ -28,7 +26,6 @@ from tests.v3 import utils
class RoleTests(utils.TestCase, utils.CrudTests): class RoleTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(RoleTests, self).setUp() super(RoleTests, self).setUp()
self.additionalSetUp()
self.key = 'role' self.key = 'role'
self.collection_key = 'roles' self.collection_key = 'roles'
self.model = roles.Role self.model = roles.Role
@@ -39,376 +36,213 @@ class RoleTests(utils.TestCase, utils.CrudTests):
kwargs.setdefault('name', uuid.uuid4().hex) kwargs.setdefault('name', uuid.uuid4().hex)
return kwargs return kwargs
@httpretty.activate
def test_domain_role_grant(self): def test_domain_role_grant(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 201,
"text": '',
})
method = 'PUT' self.stub_url(httpretty.PUT,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=201)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/users/%s/%s/%s' % (
domain_id, user_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.grant(role=ref['id'], domain=domain_id, user=user_id) self.manager.grant(role=ref['id'], domain=domain_id, user=user_id)
@httpretty.activate
def test_domain_group_role_grant(self): def test_domain_group_role_grant(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 201,
"text": '',
})
method = 'PUT' self.stub_url(httpretty.PUT,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=201)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/groups/%s/%s/%s' % (
domain_id, group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.grant(role=ref['id'], domain=domain_id, group=group_id) self.manager.grant(role=ref['id'], domain=domain_id, group=group_id)
@httpretty.activate
def test_domain_role_list(self): def test_domain_role_list(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key], entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/users/%s/%s' % (
domain_id, user_id, self.collection_key)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.list(domain=domain_id, user=user_id) self.manager.list(domain=domain_id, user=user_id)
@httpretty.activate
def test_domain_group_role_list(self): def test_domain_group_role_list(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key], entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/groups/%s/%s' % (
domain_id, group_id, self.collection_key)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.list(domain=domain_id, group=group_id) self.manager.list(domain=domain_id, group=group_id)
@httpretty.activate
def test_domain_role_check(self): def test_domain_role_check(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'HEAD' self.stub_url(httpretty.HEAD,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=204)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/users/%s/%s/%s' % (
domain_id, user_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.check(role=ref['id'], domain=domain_id, self.manager.check(role=ref['id'], domain=domain_id,
user=user_id) user=user_id)
@httpretty.activate
def test_domain_group_role_check(self): def test_domain_group_role_check(self):
return return
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'HEAD' self.stub_url(httpretty.HEAD,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=204)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/groups/%s/%s/%s' % (
domain_id, group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.check(role=ref['id'], domain=domain_id, group=group_id) self.manager.check(role=ref['id'], domain=domain_id, group=group_id)
@httpretty.activate
def test_domain_role_revoke(self): def test_domain_role_revoke(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'DELETE' self.stub_url(httpretty.DELETE,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=204)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/users/%s/%s/%s' % (
domain_id, user_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.revoke(role=ref['id'], domain=domain_id, user=user_id) self.manager.revoke(role=ref['id'], domain=domain_id, user=user_id)
@httpretty.activate
def test_domain_group_role_revoke(self): def test_domain_group_role_revoke(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
domain_id = uuid.uuid4().hex domain_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'DELETE' self.stub_url(httpretty.DELETE,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['domains', domain_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=204)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/domains/%s/groups/%s/%s/%s' % (
domain_id, group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.revoke(role=ref['id'], domain=domain_id, group=group_id) self.manager.revoke(role=ref['id'], domain=domain_id, group=group_id)
@httpretty.activate
def test_project_role_grant(self): def test_project_role_grant(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 201,
"text": '',
})
method = 'PUT' self.stub_url(httpretty.PUT,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=201)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/users/%s/%s/%s' % (
project_id, user_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.grant(role=ref['id'], project=project_id, user=user_id) self.manager.grant(role=ref['id'], project=project_id, user=user_id)
@httpretty.activate
def test_project_group_role_grant(self): def test_project_group_role_grant(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 201,
"text": '',
})
method = 'PUT' self.stub_url(httpretty.PUT,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=201)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/groups/%s/%s/%s' % (
project_id, group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.grant(role=ref['id'], project=project_id, group=group_id) self.manager.grant(role=ref['id'], project=project_id, group=group_id)
@httpretty.activate
def test_project_role_list(self): def test_project_role_list(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key], entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/users/%s/%s' % (
project_id, user_id, self.collection_key)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.list(project=project_id, user=user_id) self.manager.list(project=project_id, user=user_id)
@httpretty.activate
def test_project_group_role_list(self): def test_project_group_role_list(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key], entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/groups/%s/%s' % (
project_id, group_id, self.collection_key)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.list(project=project_id, group=group_id) self.manager.list(project=project_id, group=group_id)
@httpretty.activate
def test_project_role_check(self): def test_project_role_check(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 200,
"text": '',
})
method = 'HEAD' self.stub_url(httpretty.HEAD,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=200)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/users/%s/%s/%s' % (
project_id, user_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.check(role=ref['id'], project=project_id, user=user_id) self.manager.check(role=ref['id'], project=project_id, user=user_id)
@httpretty.activate
def test_project_group_role_check(self): def test_project_group_role_check(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 200,
"text": '',
})
method = 'HEAD' self.stub_url(httpretty.HEAD,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=200)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/groups/%s/%s/%s' % (
project_id, group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.check(role=ref['id'], project=project_id, group=group_id) self.manager.check(role=ref['id'], project=project_id, group=group_id)
@httpretty.activate
def test_project_role_revoke(self): def test_project_role_revoke(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'DELETE' self.stub_url(httpretty.DELETE,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'users', user_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=204)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/users/%s/%s/%s' % (
project_id, user_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.revoke(role=ref['id'], project=project_id, user=user_id) self.manager.revoke(role=ref['id'], project=project_id, user=user_id)
@httpretty.activate
def test_project_group_role_revoke(self): def test_project_group_role_revoke(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'DELETE' self.stub_url(httpretty.DELETE,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['projects', project_id, 'groups', group_id,
kwargs['headers'] = self.headers[method] self.collection_key, ref['id']],
requests.request( status=204)
method,
urlparse.urljoin(
self.TEST_URL,
'v3/projects/%s/groups/%s/%s/%s' % (
project_id, group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.revoke(role=ref['id'], project=project_id, group=group_id) self.manager.revoke(role=ref['id'], project=project_id, group=group_id)
@httpretty.activate
def test_domain_project_role_grant_fails(self): def test_domain_project_role_grant_fails(self):
user_id = uuid.uuid4().hex user_id = uuid.uuid4().hex
project_id = uuid.uuid4().hex project_id = uuid.uuid4().hex

View File

@@ -21,7 +21,6 @@ from tests.v3 import utils
class ServiceTests(utils.TestCase, utils.CrudTests): class ServiceTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(ServiceTests, self).setUp() super(ServiceTests, self).setUp()
self.additionalSetUp()
self.key = 'service' self.key = 'service'
self.collection_key = 'services' self.collection_key = 'services'
self.model = services.Service self.model = services.Service

View File

@@ -13,18 +13,17 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import uuid
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.openstack.common import timeutils from keystoneclient.openstack.common import timeutils
from keystoneclient.v3.contrib import trusts from keystoneclient.v3.contrib import trusts
from tests.v3 import utils from tests.v3 import utils
import uuid
class TrustTests(utils.TestCase, utils.CrudTests): class TrustTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(TrustTests, self).setUp() super(TrustTests, self).setUp()
self.additionalSetUp()
self.key = 'trust' self.key = 'trust'
self.collection_key = 'trusts' self.collection_key = 'trusts'
self.model = trusts.Trust self.model = trusts.Trust

View File

@@ -14,11 +14,9 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import urlparse
import uuid import uuid
import requests import httpretty
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.v3 import users from keystoneclient.v3 import users
@@ -28,7 +26,6 @@ from tests.v3 import utils
class UserTests(utils.TestCase, utils.CrudTests): class UserTests(utils.TestCase, utils.CrudTests):
def setUp(self): def setUp(self):
super(UserTests, self).setUp() super(UserTests, self).setUp()
self.additionalSetUp()
self.key = 'user' self.key = 'user'
self.collection_key = 'users' self.collection_key = 'users'
self.model = users.User self.model = users.User
@@ -43,25 +40,13 @@ class UserTests(utils.TestCase, utils.CrudTests):
kwargs.setdefault('default_project_id', uuid.uuid4().hex) kwargs.setdefault('default_project_id', uuid.uuid4().hex)
return kwargs return kwargs
@httpretty.activate
def test_add_user_to_group(self): def test_add_user_to_group(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({ self.stub_url(httpretty.PUT,
"status_code": 204, ['groups', group_id, self.collection_key, ref['id']],
"text": '', status=204)
})
method = 'PUT'
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/groups/%s/%s/%s' % (
group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.add_to_group(user=ref['id'], group=group_id) self.manager.add_to_group(user=ref['id'], group=group_id)
self.assertRaises(exceptions.ValidationError, self.assertRaises(exceptions.ValidationError,
@@ -69,49 +54,27 @@ class UserTests(utils.TestCase, utils.CrudTests):
user=ref['id'], user=ref['id'],
group=None) group=None)
@httpretty.activate
def test_list_users_in_group(self): def test_list_users_in_group(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
ref_list = [self.new_ref(), self.new_ref()] ref_list = [self.new_ref(), self.new_ref()]
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['groups', group_id, self.collection_key],
kwargs['headers'] = self.headers[method] entity=ref_list)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/groups/%s/%s' % (
group_id, self.collection_key)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned_list = self.manager.list(group=group_id) returned_list = self.manager.list(group=group_id)
self.assertTrue(len(returned_list)) self.assertTrue(len(returned_list))
[self.assertTrue(isinstance(r, self.model)) for r in returned_list] [self.assertTrue(isinstance(r, self.model)) for r in returned_list]
@httpretty.activate
def test_check_user_in_group(self): def test_check_user_in_group(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'HEAD' self.stub_url(httpretty.HEAD,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['groups', group_id, self.collection_key, ref['id']],
kwargs['headers'] = self.headers[method] status=204)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/groups/%s/%s/%s' % (
group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.check_in_group(user=ref['id'], group=group_id) self.manager.check_in_group(user=ref['id'], group=group_id)
@@ -120,25 +83,14 @@ class UserTests(utils.TestCase, utils.CrudTests):
user=ref['id'], user=ref['id'],
group=None) group=None)
@httpretty.activate
def test_remove_user_from_group(self): def test_remove_user_from_group(self):
group_id = uuid.uuid4().hex group_id = uuid.uuid4().hex
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 204,
"text": '',
})
method = 'DELETE' self.stub_url(httpretty.DELETE,
kwargs = copy.copy(self.TEST_REQUEST_BASE) ['groups', group_id, self.collection_key, ref['id']],
kwargs['headers'] = self.headers[method] status=204)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/groups/%s/%s/%s' % (
group_id, self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.manager.remove_from_group(user=ref['id'], group=group_id) self.manager.remove_from_group(user=ref['id'], group=group_id)
self.assertRaises(exceptions.ValidationError, self.assertRaises(exceptions.ValidationError,
@@ -146,29 +98,17 @@ class UserTests(utils.TestCase, utils.CrudTests):
user=ref['id'], user=ref['id'],
group=None) group=None)
@httpretty.activate
def test_create_with_project(self): def test_create_with_project(self):
# Can create a user with the deprecated project option rather than # Can create a user with the deprecated project option rather than
# default_project_id. # default_project_id.
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 201,
"text": self.serialize(ref),
})
method = 'POST' self.stub_entity(httpretty.POST, [self.collection_key],
status=201, entity=ref)
req_ref = ref.copy() req_ref = ref.copy()
req_ref.pop('id') req_ref.pop('id')
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
kwargs['data'] = self.serialize(req_ref)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/%s' % self.collection_key),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
param_ref = req_ref.copy() param_ref = req_ref.copy()
# Use deprecated project_id rather than new default_project_id. # Use deprecated project_id rather than new default_project_id.
param_ref['project_id'] = param_ref.pop('default_project_id') param_ref['project_id'] = param_ref.pop('default_project_id')
@@ -181,31 +121,22 @@ class UserTests(utils.TestCase, utils.CrudTests):
getattr(returned, attr), getattr(returned, attr),
ref[attr], ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
self.assertEntityRequestBodyIs(req_ref)
@httpretty.activate
def test_create_with_project_and_default_project(self): def test_create_with_project_and_default_project(self):
# Can create a user with the deprecated project and default_project_id. # Can create a user with the deprecated project and default_project_id.
# The backend call should only pass the default_project_id. # The backend call should only pass the default_project_id.
ref = self.new_ref() ref = self.new_ref()
resp = utils.TestResponse({
"status_code": 201,
"text": self.serialize(ref),
})
method = 'POST' self.stub_entity(httpretty.POST,
[self.collection_key],
status=201, entity=ref)
req_ref = ref.copy() req_ref = ref.copy()
req_ref.pop('id') req_ref.pop('id')
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
kwargs['data'] = self.serialize(req_ref)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/%s' % self.collection_key),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
param_ref = req_ref.copy() param_ref = req_ref.copy()
# Add the deprecated project_id in the call, the value will be ignored. # Add the deprecated project_id in the call, the value will be ignored.
param_ref['project_id'] = 'project' param_ref['project_id'] = 'project'
params = utils.parameterize(param_ref) params = utils.parameterize(param_ref)
@@ -217,31 +148,21 @@ class UserTests(utils.TestCase, utils.CrudTests):
getattr(returned, attr), getattr(returned, attr),
ref[attr], ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
self.assertEntityRequestBodyIs(req_ref)
@httpretty.activate
def test_update_with_project(self): def test_update_with_project(self):
# Can update a user with the deprecated project option rather than # Can update a user with the deprecated project option rather than
# default_project_id. # default_project_id.
ref = self.new_ref() ref = self.new_ref()
req_ref = ref.copy() req_ref = ref.copy()
del req_ref['id'] req_ref.pop('id')
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref),
})
method = 'PATCH'
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
kwargs['data'] = self.serialize(req_ref)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/%s/%s' % (self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
param_ref = req_ref.copy() param_ref = req_ref.copy()
self.stub_entity(httpretty.PATCH,
[self.collection_key, ref['id']],
status=200, entity=ref)
# Use deprecated project_id rather than new default_project_id. # Use deprecated project_id rather than new default_project_id.
param_ref['project_id'] = param_ref.pop('default_project_id') param_ref['project_id'] = param_ref.pop('default_project_id')
params = utils.parameterize(param_ref) params = utils.parameterize(param_ref)
@@ -253,29 +174,19 @@ class UserTests(utils.TestCase, utils.CrudTests):
getattr(returned, attr), getattr(returned, attr),
ref[attr], ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
self.assertEntityRequestBodyIs(req_ref)
@httpretty.activate
def test_update_with_project_and_default_project(self, ref=None): def test_update_with_project_and_default_project(self, ref=None):
ref = self.new_ref() ref = self.new_ref()
req_ref = ref.copy() req_ref = ref.copy()
del req_ref['id'] req_ref.pop('id')
resp = utils.TestResponse({
"status_code": 200,
"text": self.serialize(ref),
})
method = 'PATCH'
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
kwargs['data'] = self.serialize(req_ref)
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'v3/%s/%s' % (self.collection_key, ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
param_ref = req_ref.copy() param_ref = req_ref.copy()
self.stub_entity(httpretty.PATCH,
[self.collection_key, ref['id']],
status=200, entity=ref)
# Add the deprecated project_id in the call, the value will be ignored. # Add the deprecated project_id in the call, the value will be ignored.
param_ref['project_id'] = 'project' param_ref['project_id'] = 'project'
params = utils.parameterize(param_ref) params = utils.parameterize(param_ref)
@@ -287,3 +198,4 @@ class UserTests(utils.TestCase, utils.CrudTests):
getattr(returned, attr), getattr(returned, attr),
ref[attr], ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
self.assertEntityRequestBodyIs(req_ref)

View File

@@ -12,21 +12,16 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import copy
import json
import time
import urlparse import urlparse
import uuid import uuid
import mock import httpretty
from mox3 import mox
import requests
import testtools
from .. import utils
from keystoneclient.openstack.common import jsonutils
from keystoneclient.v3 import client from keystoneclient.v3 import client
from tests import utils
TestResponse = utils.TestResponse TestResponse = utils.TestResponse
@@ -44,26 +39,16 @@ def parameterize(ref):
return params return params
class TestClient(client.Client): class UnauthenticatedTestCase(utils.TestCase):
"""Class used as base for unauthenticated calls."""
def serialize(self, entity):
return json.dumps(entity, sort_keys=True)
class TestCase(testtools.TestCase):
TEST_DOMAIN_ID = '1'
TEST_DOMAIN_NAME = 'aDomain'
TEST_TENANT_ID = '1'
TEST_TENANT_NAME = 'aTenant'
TEST_TOKEN = 'aToken'
TEST_USER = 'test'
TEST_ROOT_URL = 'http://127.0.0.1:5000/' TEST_ROOT_URL = 'http://127.0.0.1:5000/'
TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v3') TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v3')
TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/' TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/'
TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v3') TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v3')
TEST_REQUEST_BASE = {
'verify': True,
} class TestCase(UnauthenticatedTestCase):
TEST_SERVICE_CATALOG = [{ TEST_SERVICE_CATALOG = [{
"endpoints": [{ "endpoints": [{
@@ -145,56 +130,21 @@ class TestCase(testtools.TestCase):
def setUp(self): def setUp(self):
super(TestCase, self).setUp() super(TestCase, self).setUp()
self.mox = mox.Mox() self.client = client.Client(username=self.TEST_USER,
self.request_patcher = mock.patch.object(requests, 'request', token=self.TEST_TOKEN,
self.mox.CreateMockAnything()) tenant_name=self.TEST_TENANT_NAME,
self.time_patcher = mock.patch.object(time, 'time', auth_url=self.TEST_URL,
lambda: 1234) endpoint=self.TEST_URL)
self.request_patcher.start()
self.time_patcher.start()
self.client = TestClient(username=self.TEST_USER,
token=self.TEST_TOKEN,
tenant_name=self.TEST_TENANT_NAME,
auth_url=self.TEST_URL,
endpoint=self.TEST_URL)
def tearDown(self): def stub_auth(self, subject_token=None, **kwargs):
self.request_patcher.stop() if not subject_token:
self.time_patcher.stop() subject_token = self.TEST_TOKEN
self.mox.UnsetStubs()
self.mox.VerifyAll() self.stub_url(httpretty.POST, ['auth', 'tokens'],
super(TestCase, self).tearDown() X_Subject_Token=subject_token, **kwargs)
class UnauthenticatedTestCase(testtools.TestCase): class CrudTests(object):
"""Class used as base for unauthenticated calls."""
TEST_ROOT_URL = 'http://127.0.0.1:5000/'
TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v3')
TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/'
TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v3')
TEST_REQUEST_BASE = {
'verify': True,
}
def setUp(self):
super(UnauthenticatedTestCase, self).setUp()
self.mox = mox.Mox()
self.request_patcher = mock.patch.object(requests, 'request',
self.mox.CreateMockAnything())
self.time_patcher = mock.patch.object(time, 'time',
lambda: 1234)
self.request_patcher.start()
def tearDown(self):
self.request_patcher.stop()
self.time_patcher.stop()
self.mox.UnsetStubs()
self.mox.VerifyAll()
super(UnauthenticatedTestCase, self).tearDown()
class CrudTests(testtools.TestCase):
key = None key = None
collection_key = None collection_key = None
model = None model = None
@@ -205,34 +155,36 @@ class CrudTests(testtools.TestCase):
kwargs.setdefault('id', uuid.uuid4().hex) kwargs.setdefault('id', uuid.uuid4().hex)
return kwargs return kwargs
def additionalSetUp(self): def encode(self, entity):
self.headers = {
'GET': {
'X-Auth-Token': 'aToken',
'User-Agent': 'python-keystoneclient',
}
}
self.headers['HEAD'] = self.headers['GET'].copy()
self.headers['DELETE'] = self.headers['GET'].copy()
self.headers['PUT'] = self.headers['GET'].copy()
self.headers['POST'] = self.headers['GET'].copy()
self.headers['POST']['Content-Type'] = 'application/json'
self.headers['PATCH'] = self.headers['POST'].copy()
def serialize(self, entity):
if isinstance(entity, dict): if isinstance(entity, dict):
return json.dumps({self.key: entity}, sort_keys=True) return {self.key: entity}
if isinstance(entity, list): if isinstance(entity, list):
return json.dumps({self.collection_key: entity}, sort_keys=True) return {self.collection_key: entity}
raise NotImplementedError('Are you sure you want to serialize that?') raise NotImplementedError('Are you sure you want to encode that?')
def _req_path(self): def stub_entity(self, method, parts=None, entity=None, id=None, **kwargs):
if self.path_prefix: if entity:
return 'v3/%s/%s' % (self.path_prefix, self.collection_key) entity = self.encode(entity)
else: kwargs['json'] = entity
return 'v3/%s' % self.collection_key
if not parts:
parts = [self.collection_key]
if self.path_prefix:
parts.insert(0, self.path_prefix)
if id:
if not parts:
parts = []
parts.append(id)
self.stub_url(method, parts=parts, **kwargs)
def assertEntityRequestBodyIs(self, entity):
self.assertRequestBodyIs(json=self.encode(entity))
@httpretty.activate
def test_create(self, ref=None, req_ref=None): def test_create(self, ref=None, req_ref=None):
ref = ref or self.new_ref() ref = ref or self.new_ref()
manager_ref = ref.copy() manager_ref = ref.copy()
@@ -244,24 +196,8 @@ class CrudTests(testtools.TestCase):
# from datetime object to timestamp string) # from datetime object to timestamp string)
req_ref = req_ref or ref.copy() req_ref = req_ref or ref.copy()
req_ref.pop('id') req_ref.pop('id')
data = self.serialize(req_ref)
resp = TestResponse({
"status_code": 201,
"text": data,
})
method = 'POST' self.stub_entity(httpretty.POST, entity=req_ref, status=201)
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
kwargs['data'] = data
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
self._req_path()),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned = self.manager.create(**parameterize(manager_ref)) returned = self.manager.create(**parameterize(manager_ref))
self.assertTrue(isinstance(returned, self.model)) self.assertTrue(isinstance(returned, self.model))
@@ -270,24 +206,13 @@ class CrudTests(testtools.TestCase):
getattr(returned, attr), getattr(returned, attr),
req_ref[attr], req_ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
self.assertEntityRequestBodyIs(req_ref)
@httpretty.activate
def test_get(self, ref=None): def test_get(self, ref=None):
ref = ref or self.new_ref() ref = ref or self.new_ref()
resp = TestResponse({
"status_code": 200,
"text": self.serialize(ref),
})
method = 'GET' self.stub_entity(httpretty.GET, id=ref['id'], entity=ref)
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'%s/%s' % (self._req_path(), ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned = self.manager.get(ref['id']) returned = self.manager.get(ref['id'])
self.assertTrue(isinstance(returned, self.model)) self.assertTrue(isinstance(returned, self.model))
@@ -297,47 +222,31 @@ class CrudTests(testtools.TestCase):
ref[attr], ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
@httpretty.activate
def test_list(self, ref_list=None, expected_path=None, **filter_kwargs): def test_list(self, ref_list=None, expected_path=None, **filter_kwargs):
ref_list = ref_list or [self.new_ref(), self.new_ref()] ref_list = ref_list or [self.new_ref(), self.new_ref()]
resp = TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' if not expected_path:
kwargs = copy.copy(self.TEST_REQUEST_BASE) if self.path_prefix:
kwargs['headers'] = self.headers[method] expected_path = 'v3/%s/%s' % (self.path_prefix,
requests.request( self.collection_key)
method, else:
urlparse.urljoin( expected_path = 'v3/%s' % self.collection_key
self.TEST_URL,
expected_path or self._req_path()), httpretty.register_uri(httpretty.GET,
**kwargs).AndReturn((resp)) urlparse.urljoin(self.TEST_URL, expected_path),
self.mox.ReplayAll() body=jsonutils.dumps(self.encode(ref_list)))
returned_list = self.manager.list(**filter_kwargs) returned_list = self.manager.list(**filter_kwargs)
self.assertTrue(len(returned_list)) self.assertTrue(len(returned_list))
[self.assertTrue(isinstance(r, self.model)) for r in returned_list] [self.assertTrue(isinstance(r, self.model)) for r in returned_list]
@httpretty.activate
def test_find(self, ref=None): def test_find(self, ref=None):
ref = ref or self.new_ref() ref = ref or self.new_ref()
ref_list = [ref] ref_list = [ref]
resp = TestResponse({
"status_code": 200,
"text": self.serialize(ref_list),
})
method = 'GET' self.stub_entity(httpretty.GET, entity=ref_list)
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
query = '?name=%s' % ref['name'] if hasattr(ref, 'name') else ''
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'%s%s' % (self._req_path(), query)),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned = self.manager.find(name=getattr(ref, 'name', None)) returned = self.manager.find(name=getattr(ref, 'name', None))
self.assertTrue(isinstance(returned, self.model)) self.assertTrue(isinstance(returned, self.model))
@@ -347,26 +256,19 @@ class CrudTests(testtools.TestCase):
ref[attr], ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
if hasattr(ref, 'name'):
self.assertQueryStringIs({'name': ref['name']})
else:
self.assertQueryStringIs({})
@httpretty.activate
def test_update(self, ref=None): def test_update(self, ref=None):
ref = ref or self.new_ref() ref = ref or self.new_ref()
req_ref = ref.copy()
del req_ref['id']
resp = TestResponse({
"status_code": 200,
"text": self.serialize(ref),
})
method = 'PATCH' self.stub_entity(httpretty.PATCH, id=ref['id'], entity=ref)
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method] req_ref = ref.copy()
kwargs['data'] = self.serialize(req_ref) req_ref.pop('id')
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'%s/%s' % (self._req_path(), ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
returned = self.manager.update(ref['id'], **parameterize(req_ref)) returned = self.manager.update(ref['id'], **parameterize(req_ref))
self.assertTrue(isinstance(returned, self.model)) self.assertTrue(isinstance(returned, self.model))
@@ -375,23 +277,11 @@ class CrudTests(testtools.TestCase):
getattr(returned, attr), getattr(returned, attr),
ref[attr], ref[attr],
'Expected different %s' % attr) 'Expected different %s' % attr)
self.assertEntityRequestBodyIs(req_ref)
@httpretty.activate
def test_delete(self, ref=None): def test_delete(self, ref=None):
ref = ref or self.new_ref() ref = ref or self.new_ref()
resp = TestResponse({
"status_code": 204,
"text": '',
})
method = 'DELETE'
kwargs = copy.copy(self.TEST_REQUEST_BASE)
kwargs['headers'] = self.headers[method]
requests.request(
method,
urlparse.urljoin(
self.TEST_URL,
'%s/%s' % (self._req_path(), ref['id'])),
**kwargs).AndReturn((resp))
self.mox.ReplayAll()
self.stub_entity(httpretty.DELETE, id=ref['id'], status=204)
self.manager.delete(ref['id']) self.manager.delete(ref['id'])