pep8 1.1 changes and updates

Change-Id: I8bc3582bb3f35a3d841bb1e8c03b62ba61ff92d7
This commit is contained in:
Joe Heck
2012-06-01 18:07:26 -07:00
parent aa97614330
commit 52b392281e
22 changed files with 398 additions and 374 deletions

View File

@@ -101,8 +101,12 @@ class HTTPNotImplemented(ClientException):
# for c in ClientException.__subclasses__()) # for c in ClientException.__subclasses__())
# #
# Instead, we have to hardcode it: # Instead, we have to hardcode it:
_code_map = dict((c.http_status, c) for c in [BadRequest, Unauthorized, _code_map = dict((c.http_status, c) for c in [BadRequest,
Forbidden, NotFound, OverLimit, HTTPNotImplemented]) Unauthorized,
Forbidden,
NotFound,
OverLimit,
HTTPNotImplemented])
def from_response(response, body): def from_response(response, body):

View File

@@ -82,7 +82,8 @@ class Client(client.HTTPClient):
try: try:
httpclient = client.HTTPClient() httpclient = client.HTTPClient()
resp, body = httpclient.request(url, "GET", resp, body = httpclient.request(url, "GET",
headers={'Accept': 'application/json'}) headers={'Accept':
'application/json'})
if resp.status in (200, 204): # in some cases we get No Content if resp.status in (200, 204): # in some cases we get No Content
try: try:
results = {} results = {}
@@ -90,8 +91,8 @@ class Client(client.HTTPClient):
results['message'] = "Keystone found at %s" % url results['message'] = "Keystone found at %s" % url
version = body['version'] version = body['version']
# Stable/diablo incorrect format # Stable/diablo incorrect format
id, status, version_url = self._get_version_info( id, status, version_url = \
version, url) self._get_version_info(version, url)
results[str(id)] = {"id": id, results[str(id)] = {"id": id,
"status": status, "status": status,
"url": version_url} "url": version_url}
@@ -100,8 +101,8 @@ class Client(client.HTTPClient):
# Correct format # Correct format
results['message'] = "Keystone found at %s" % url results['message'] = "Keystone found at %s" % url
for version in body['versions']['values']: for version in body['versions']['values']:
id, status, version_url = self._get_version_info( id, status, version_url = \
version, url) self._get_version_info(version, url)
results[str(id)] = {"id": id, results[str(id)] = {"id": id,
"status": status, "status": status,
"url": version_url} "url": version_url}
@@ -142,7 +143,8 @@ class Client(client.HTTPClient):
if not url.endswith("/"): if not url.endswith("/"):
url += '/' url += '/'
resp, body = httpclient.request("%sextensions" % url, "GET", resp, body = httpclient.request("%sextensions" % url, "GET",
headers={'Accept': 'application/json'}) headers={'Accept':
'application/json'})
if resp.status in (200, 204): # in some cases we get No Content if resp.status in (200, 204): # in some cases we get No Content
try: try:
results = {} results = {}
@@ -150,15 +152,17 @@ class Client(client.HTTPClient):
if 'values' in body['extensions']: if 'values' in body['extensions']:
# Parse correct format (per contract) # Parse correct format (per contract)
for extension in body['extensions']['values']: for extension in body['extensions']['values']:
alias, name = self._get_extension_info( alias, name = \
extension['extension']) self._get_extension_info(
extension['extension']
)
results[alias] = name results[alias] = name
return results return results
else: else:
# Support incorrect, but prevalent format # Support incorrect, but prevalent format
for extension in body['extensions']: for extension in body['extensions']:
alias, name = self._get_extension_info( alias, name = \
extension) self._get_extension_info(extension)
results[alias] = name results[alias] = name
return results return results
else: else:

View File

@@ -56,69 +56,84 @@ class OpenStackIdentityShell(object):
) )
# Global arguments # Global arguments
parser.add_argument('-h', '--help', parser.add_argument('-h',
'--help',
action='store_true', action='store_true',
help=argparse.SUPPRESS, help=argparse.SUPPRESS)
)
parser.add_argument('--debug', parser.add_argument('--debug',
default=False, default=False,
action='store_true', action='store_true',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
parser.add_argument('--os_username', metavar='<auth-user-name>', parser.add_argument('--os_username',
metavar='<auth-user-name>',
default=env('OS_USERNAME'), default=env('OS_USERNAME'),
help='Defaults to env[OS_USERNAME]') help='Defaults to env[OS_USERNAME]')
parser.add_argument('--os_password', metavar='<auth-password>', parser.add_argument('--os_password',
metavar='<auth-password>',
default=env('OS_PASSWORD'), default=env('OS_PASSWORD'),
help='Defaults to env[OS_PASSWORD]') help='Defaults to env[OS_PASSWORD]')
parser.add_argument('--os_tenant_name', metavar='<auth-tenant-name>', parser.add_argument('--os_tenant_name',
metavar='<auth-tenant-name>',
default=env('OS_TENANT_NAME'), default=env('OS_TENANT_NAME'),
help='Defaults to env[OS_TENANT_NAME]') help='Defaults to env[OS_TENANT_NAME]')
parser.add_argument('--os_tenant_id', metavar='<tenant-id>', parser.add_argument('--os_tenant_id',
metavar='<tenant-id>',
default=env('OS_TENANT_ID'), default=env('OS_TENANT_ID'),
help='Defaults to env[OS_TENANT_ID]') help='Defaults to env[OS_TENANT_ID]')
parser.add_argument('--os_auth_url', metavar='<auth-url>', parser.add_argument('--os_auth_url',
metavar='<auth-url>',
default=env('OS_AUTH_URL'), default=env('OS_AUTH_URL'),
help='Defaults to env[OS_AUTH_URL]') help='Defaults to env[OS_AUTH_URL]')
parser.add_argument('--os_region_name', metavar='<region-name>', parser.add_argument('--os_region_name',
metavar='<region-name>',
default=env('OS_REGION_NAME'), default=env('OS_REGION_NAME'),
help='Defaults to env[OS_REGION_NAME]') help='Defaults to env[OS_REGION_NAME]')
parser.add_argument('--os_identity_api_version', parser.add_argument('--os_identity_api_version',
metavar='<identity-api-version>', metavar='<identity-api-version>',
default=env('OS_IDENTITY_API_VERSION', 'KEYSTONE_VERSION'), default=env('OS_IDENTITY_API_VERSION',
help='Defaults to env[OS_IDENTITY_API_VERSION] or 2.0') 'KEYSTONE_VERSION'),
help='Defaults to env[OS_IDENTITY_API_VERSION]'
' or 2.0')
parser.add_argument('--token', metavar='<service-token>', parser.add_argument('--token',
metavar='<service-token>',
default=env('SERVICE_TOKEN'), default=env('SERVICE_TOKEN'),
help='Defaults to env[SERVICE_TOKEN]') help='Defaults to env[SERVICE_TOKEN]')
parser.add_argument('--endpoint', metavar='<service-endpoint>', parser.add_argument('--endpoint',
metavar='<service-endpoint>',
default=env('SERVICE_ENDPOINT'), default=env('SERVICE_ENDPOINT'),
help='Defaults to env[SERVICE_ENDPOINT]') help='Defaults to env[SERVICE_ENDPOINT]')
# FIXME(dtroyer): The args below are here for diablo compatibility, # FIXME(dtroyer): The args below are here for diablo compatibility,
# remove them in folsum cycle # remove them in folsum cycle
parser.add_argument('--username', metavar='<auth-user-name>', parser.add_argument('--username',
metavar='<auth-user-name>',
help='Deprecated') help='Deprecated')
parser.add_argument('--password', metavar='<auth-password>', parser.add_argument('--password',
metavar='<auth-password>',
help='Deprecated') help='Deprecated')
parser.add_argument('--tenant_name', metavar='<tenant-name>', parser.add_argument('--tenant_name',
metavar='<tenant-name>',
help='Deprecated') help='Deprecated')
parser.add_argument('--auth_url', metavar='<auth-url>', parser.add_argument('--auth_url',
metavar='<auth-url>',
help='Deprecated') help='Deprecated')
parser.add_argument('--region_name', metavar='<region-name>', parser.add_argument('--region_name',
metavar='<region-name>',
help='Deprecated') help='Deprecated')
return parser return parser
@@ -151,16 +166,14 @@ class OpenStackIdentityShell(object):
help = desc.strip().split('\n')[0] help = desc.strip().split('\n')[0]
arguments = getattr(callback, 'arguments', []) arguments = getattr(callback, 'arguments', [])
subparser = subparsers.add_parser(command, subparser = subparsers.add_parser(
command,
help=help, help=help,
description=desc, description=desc,
add_help=False, add_help=False,
formatter_class=OpenStackHelpFormatter formatter_class=OpenStackHelpFormatter)
) subparser.add_argument('-h', '--help', action='help',
subparser.add_argument('-h', '--help', help=argparse.SUPPRESS)
action='help',
help=argparse.SUPPRESS,
)
self.subcommands[command] = subparser self.subcommands[command] = subparser
for (args, kwargs) in arguments: for (args, kwargs) in arguments:
subparser.add_argument(*args, **kwargs) subparser.add_argument(*args, **kwargs)
@@ -219,12 +232,14 @@ class OpenStackIdentityShell(object):
if args.token or args.endpoint and not ( if args.token or args.endpoint and not (
args.token and args.endpoint): args.token and args.endpoint):
if not args.token: if not args.token:
raise exc.CommandError('Expecting a token provided ' raise exc.CommandError(
'via either --token or env[SERVICE_TOKEN]') 'Expecting a token provided via either --token or '
'env[SERVICE_TOKEN]')
if not args.endpoint: if not args.endpoint:
raise exc.CommandError('Expecting an endpoint provided ' raise exc.CommandError(
'via either --endpoint or env[SERVICE_ENDPOINT]') 'Expecting an endpoint provided via either --endpoint '
'or env[SERVICE_ENDPOINT]')
# if it looks like the user wants to provide a credentials # if it looks like the user wants to provide a credentials
# but is missing something # but is missing something
@@ -232,16 +247,19 @@ class OpenStackIdentityShell(object):
and not (args.os_username and args.os_password and and not (args.os_username and args.os_password and
args.os_auth_url)): args.os_auth_url)):
if not args.os_username: if not args.os_username:
raise exc.CommandError('Expecting a username provided ' raise exc.CommandError(
'via either --os_username or env[OS_USERNAME]') 'Expecting a username provided via either '
'--os_username or env[OS_USERNAME]')
if not args.os_password: if not args.os_password:
raise exc.CommandError('Expecting a password provided ' raise exc.CommandError(
'via either --os_password or env[OS_PASSWORD]') 'Expecting a password provided via either '
'--os_password or env[OS_PASSWORD]')
if not args.os_auth_url: if not args.os_auth_url:
raise exc.CommandError('Expecting an auth URL ' raise exc.CommandError(
'via either --os_auth_url or env[OS_AUTH_URL]') 'Expecting an auth URL via either --os_auth_url or '
'env[OS_AUTH_URL]')
if utils.isunauthenticated(args.func): if utils.isunauthenticated(args.func):
self.cs = shell_generic.CLIENT_CLASS(endpoint=args.os_auth_url) self.cs = shell_generic.CLIENT_CLASS(endpoint=args.os_auth_url)

View File

@@ -127,8 +127,9 @@ class Client(client.HTTPClient):
# in fact we should rewrite the client to support the service # in fact we should rewrite the client to support the service
# catalog (api calls should be directable to any endpoints) # catalog (api calls should be directable to any endpoints)
try: try:
self.management_url = self.service_catalog.url_for(attr='region', self.management_url = self.service_catalog.url_for(
filter_value=self.region_name, endpoint_type='adminURL') attr='region', filter_value=self.region_name,
endpoint_type='adminURL')
except: except:
# Unscoped tokens don't return a service catalog # Unscoped tokens don't return a service catalog
_logger.exception("unable to retrieve service catalog with token") _logger.exception("unable to retrieve service catalog with token")

View File

@@ -369,9 +369,11 @@ def do_endpoint_list(kc, args):
help='Internal URL endpoint') help='Internal URL endpoint')
def do_endpoint_create(kc, args): def do_endpoint_create(kc, args):
"""Create a new endpoint associated with a service""" """Create a new endpoint associated with a service"""
endpoint = kc.endpoints.create( endpoint = kc.endpoints.create(args.region,
args.region, args.service_id, args.publicurl, args.service_id,
args.adminurl, args.internalurl) args.publicurl,
args.adminurl,
args.internalurl)
utils.print_dict(endpoint._info) utils.print_dict(endpoint._info)

View File

@@ -33,8 +33,7 @@ class ClientTest(utils.TestCase):
def test_get_call(): def test_get_call():
resp, body = cl.get("/hi") resp, body = cl.get("/hi")
headers = {"X-Auth-Token": "token", headers = {"X-Auth-Token": "token",
"User-Agent": cl.USER_AGENT, "User-Agent": cl.USER_AGENT}
}
mock_request.assert_called_with("http://127.0.0.1:5000/hi", mock_request.assert_called_with("http://127.0.0.1:5000/hi",
"GET", headers=headers) "GET", headers=headers)
# Automatic JSON parsing # Automatic JSON parsing

View File

@@ -27,8 +27,7 @@ SERVICE_CATALOG = {
"id": "235", "id": "235",
"name": "object-store:admin", "name": "object-store:admin",
"tenantId": "1" "tenantId": "1"
} }],
],
"roles_links": [] "roles_links": []
}, },
"serviceCatalog": [{ "serviceCatalog": [{
@@ -51,8 +50,7 @@ SERVICE_CATALOG = {
"versionId": "1.1", "versionId": "1.1",
"versionInfo": "https://compute.north.host/v1.1/", "versionInfo": "https://compute.north.host/v1.1/",
"versionList": "https://compute.north.host/" "versionList": "https://compute.north.host/"
} }],
],
"endpoints_links": [] "endpoints_links": []
}, },
{ {
@@ -75,21 +73,19 @@ SERVICE_CATALOG = {
"versionId": "1.1", "versionId": "1.1",
"versionInfo": "https://compute.north.host/v1.1/", "versionInfo": "https://compute.north.host/v1.1/",
"versionList": "https://compute.north.host/" "versionList": "https://compute.north.host/"
} }],
],
"endpoints_links":[{ "endpoints_links":[{
"rel":"next", "rel":"next",
"href":"https://identity.north.host/v2.0/endpoints?marker=2" "href":"https://identity.north.host/v2.0/"
} "endpoints?marker=2"
] }]
} }
], ],
"serviceCatalog_links": [{ "serviceCatalog_links": [{
"rel": "next", "rel": "next",
"href": ("https://identity.host/v2.0/endpoints?" "href": ("https://identity.host/v2.0/endpoints?"
"session=2hfh8Ar&marker=2") "session=2hfh8Ar&marker=2")
} }]
]
} }
} }
@@ -105,8 +101,8 @@ class ServiceCatalogTest(utils.TestCase):
self.assertEquals(sc.url_for('tenantId', '2', service_type='compute'), self.assertEquals(sc.url_for('tenantId', '2', service_type='compute'),
"https://compute.north.host/v1.1/3456") "https://compute.north.host/v1.1/3456")
self.assertRaises(exceptions.EndpointNotFound, self.assertRaises(exceptions.EndpointNotFound, sc.url_for, "region",
sc.url_for, "region", "South", service_type='compute') "South", service_type='compute')
def test_service_catalog_endpoints(self): def test_service_catalog_endpoints(self):
sc = service_catalog.ServiceCatalog(SERVICE_CATALOG['access']) sc = service_catalog.ServiceCatalog(SERVICE_CATALOG['access'])
@@ -120,12 +116,11 @@ class ServiceCatalogTest(utils.TestCase):
def test_token(self): def test_token(self):
sc = service_catalog.ServiceCatalog(SERVICE_CATALOG['access']) sc = service_catalog.ServiceCatalog(SERVICE_CATALOG['access'])
self.assertEquals(sc.get_token(), self.assertEquals(sc.get_token(), {
{'id': 'ab48a9efdfedb23ty3494', 'id': 'ab48a9efdfedb23ty3494',
'tenant_id': '345', 'tenant_id': '345',
'user_id': '123', 'user_id': '123',
'expires': '2010-11-01T03:32:15-05:00'}) 'expires': '2010-11-01T03:32:15-05:00'})
self.assertEquals(sc.catalog['token']['expires'], self.assertEquals(sc.catalog['token']['expires'],
"2010-11-01T03:32:15-05:00") "2010-11-01T03:32:15-05:00")
self.assertEquals(sc.catalog['token']['tenant']['id'], self.assertEquals(sc.catalog['token']['tenant']['id'], '345')
'345')

View File

@@ -26,11 +26,11 @@ class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
"id": "v2.0", "id": "v2.0",
"status": "beta", "status": "beta",
"updated": "2011-11-19T00:00:00Z", "updated": "2011-11-19T00:00:00Z",
"links": [{ "links": [
"rel": "self", {"rel": "self",
"href": "http://127.0.0.1:5000/v2.0/", "href": "http://127.0.0.1:5000/v2.0/",
}, { },
"rel": "describedby", {"rel": "describedby",
"type": "text/html", "type": "text/html",
"href": "http://docs.openstack.org/api/" "href": "http://docs.openstack.org/api/"
"openstack-identity-service/2.0/content/", "openstack-identity-service/2.0/content/",
@@ -47,12 +47,11 @@ class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
}], }],
"media-types": [{ "media-types": [{
"base": "application/xml", "base": "application/xml",
"type": "application/" "type": "application/vnd.openstack.identity-v2.0+xml",
"vnd.openstack.identity-v2.0+xml", },
}, { {
"base": "application/json", "base": "application/json",
"type": "application/" "type": "application/vnd.openstack.identity-v2.0+json",
"vnd.openstack.identity-v2.0+json",
}], }],
}], }],
}, },
@@ -79,7 +78,8 @@ class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
self.assertIsInstance(versions, dict) self.assertIsInstance(versions, dict)
self.assertIn('message', versions) self.assertIn('message', versions)
self.assertIn('v2.0', versions) self.assertIn('v2.0', versions)
self.assertEquals(versions['v2.0']['url'], self.assertEquals(
versions['v2.0']['url'],
self.TEST_RESPONSE_DICT['versions']['values'][0]['links'][0] self.TEST_RESPONSE_DICT['versions']['values'][0]['links'][0]
['href']) ['href'])
@@ -100,6 +100,7 @@ class DiscoverKeystoneTests(utils.UnauthenticatedTestCase):
self.assertIsInstance(versions, dict) self.assertIsInstance(versions, dict)
self.assertIn('message', versions) self.assertIn('message', versions)
self.assertIn('v2.0', versions) self.assertIn('v2.0', versions)
self.assertEquals(versions['v2.0']['url'], self.assertEquals(
versions['v2.0']['url'],
self.TEST_RESPONSE_DICT['versions']['values'][0]['links'][0] self.TEST_RESPONSE_DICT['versions']['values'][0]['links'][0]
['href']) ['href'])