From 6fe763ebbe5916cdc0d6355ca8150f85f978480b Mon Sep 17 00:00:00 2001 From: BenjamenMeyer Date: Mon, 2 Feb 2015 20:19:16 +0000 Subject: [PATCH] PEP8 compliance --- stackinabox/httpretty.py | 1 + stackinabox/responses.py | 3 +- stackinabox/services/keystone/backend.py | 132 ++++++++++--------- stackinabox/services/keystone/v2/__init__.py | 32 +++-- stackinabox/services/service.py | 32 +++-- stackinabox/stack.py | 7 +- stackinabox/test/test_keystone.py | 18 ++- 7 files changed, 135 insertions(+), 90 deletions(-) diff --git a/stackinabox/httpretty.py b/stackinabox/httpretty.py index 4f997a6..097cc00 100644 --- a/stackinabox/httpretty.py +++ b/stackinabox/httpretty.py @@ -20,6 +20,7 @@ def httpretty_callback(request, uri, headers): uri, headers) + def httpretty_registration(uri): logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty' .format(uri)) diff --git a/stackinabox/responses.py b/stackinabox/responses.py index 3facfe7..8c3a365 100644 --- a/stackinabox/responses.py +++ b/stackinabox/responses.py @@ -16,7 +16,8 @@ def responses_callback(request): method = request.method headers = request.headers uri = request.url - return (200, headers, 'Hello') + return (200, headers, 'Hello') + def responses_registration(uri): logger.debug('Registering Stack-In-A-Box at {0} under Python Responses' diff --git a/stackinabox/services/keystone/backend.py b/stackinabox/services/keystone/backend.py index 456ea93..16cd304 100644 --- a/stackinabox/services/keystone/backend.py +++ b/stackinabox/services/keystone/backend.py @@ -28,52 +28,52 @@ """ schema = [ -''' - CREATE TABLE keystone_tenants - ( - tenantid INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - description TEXT, - enabled INTEGER DEFAULT 1 - ) -''', -''' - CREATE TABLE keystone_users - ( - tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid), - userid INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT NOT NULL, - email TEXT NOT NULL, - password TEXT NOT NULL, - apikey TEXT NOT NULL, - enabled INTEGER DEFAULT 1 - ) -''', -''' - CREATE TABLE keystone_tokens - ( - tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid), - userid INTEGER NOT NULL REFERENCES keystone_users(userid), - token TEXT NOT NULL UNIQUE, - ttl DATETIME NOT NULL, - revoked INTEGER DEFAULT 0 - ) -''', -''' - CREATE TABLE keystone_roles - ( - roleid INTEGER PRIMARY KEY AUTOINCREMENT, - rolename TEXT NOT NULL UNIQUE - ) -''', -''' - CREATE TABLE keystone_user_roles - ( - tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid), - userid INTEGER NOT NULL REFERENCES keystone_users(userid), - roleid INTEGER NOT NULL REFERENCES keystone_roles(roleid) - ) -''' + ''' + CREATE TABLE keystone_tenants + ( + tenantid INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + description TEXT, + enabled INTEGER DEFAULT 1 + ) + ''', + ''' + CREATE TABLE keystone_users + ( + tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid), + userid INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL, + email TEXT NOT NULL, + password TEXT NOT NULL, + apikey TEXT NOT NULL, + enabled INTEGER DEFAULT 1 + ) + ''', + ''' + CREATE TABLE keystone_tokens + ( + tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid), + userid INTEGER NOT NULL REFERENCES keystone_users(userid), + token TEXT NOT NULL UNIQUE, + ttl DATETIME NOT NULL, + revoked INTEGER DEFAULT 0 + ) + ''', + ''' + CREATE TABLE keystone_roles + ( + roleid INTEGER PRIMARY KEY AUTOINCREMENT, + rolename TEXT NOT NULL UNIQUE + ) + ''', + ''' + CREATE TABLE keystone_user_roles + ( + tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid), + userid INTEGER NOT NULL REFERENCES keystone_users(userid), + roleid INTEGER NOT NULL REFERENCES keystone_roles(roleid) + ) + ''' ] SQL_ADD_TENANT = ''' @@ -131,7 +131,7 @@ SELECT tenantid, userid, username, email, password, apikey, enabled FROM keystone_users WHERE tenantid = :tenantid AND - username = :username + username = :username ''' SQL_GET_USER_BY_USERID = ''' @@ -172,7 +172,8 @@ ''' SQL_GET_TOKEN_BY_USER_NAME = ''' - SELECT keystone_tokens.tenantid, keystone_tokens.userid, keystone_tokens.token, keystone_tokens.ttl, keystone_tokens.revoked + SELECT keystone_tokens.tenantid, keystone_tokens.userid, + keystone_tokens.token, keystone_tokens.ttl, keystone_tokens.revoked FROM keystone_tokens, keystone_users WHERE keystone_tokens.tenantid = keystone_users.tenantid AND keystone_tokens.userid = keystone_users.userid @@ -225,6 +226,7 @@ AND keystone_user_roles.userid = :userid ''' + class KeystoneError(Exception): pass @@ -266,7 +268,7 @@ class KeystoneBackend(object): IDENTITY_ADMIN_ROLE = 'identity:user-admin' def __init__(self): - self.__admin_token = 'adminstrate_with_this_{0}'.format(uuid.uuid4()) + self.__admin_token = 'adminstrate_with_this_{0}'.format(uuid.uuid4()) self.database = sqlite3.connect(':memory:') self.init_database() @@ -292,8 +294,13 @@ def init_database(self): dbcursor.execute(table_sql) # Create an admin user and add the admin token to that user - self.__admin_tenant_id = self.add_tenant('system', 'system administrator') - self.__admin_user_id = self.add_user(self.__admin_tenant_id, 'system', 'system@stackinabox', 'stackinabox','537461636b496e41426f78') + self.__admin_tenant_id = self.add_tenant('system', + 'system administrator') + self.__admin_user_id = self.add_user(self.__admin_tenant_id, + 'system', + 'system@stackinabox', + 'stackinabox', + '537461636b496e41426f78') role_data = self.add_role(KeystoneBackend.IDENTITY_ADMIN_ROLE) self.__admin_role_id = role_data['roleid'] self.add_user_role_by_roleid(self.__admin_tenant_id, @@ -307,7 +314,7 @@ def init_database(self): self.database.commit() def get_admin_token(self): - return self.__admin_token + return self.__admin_token def add_tenant(self, tenantname=None, description=None, enabled=True): args = { @@ -325,7 +332,8 @@ def add_tenant(self, tenantname=None, description=None, enabled=True): dbcursor.execute(SQL_GET_MAX_TENANT_ID) tenant_data = dbcursor.fetchone() if tenant_data is None: - raise KeystoneTenantError('Unable to retrieve tenantid for newly created tenant') + raise KeystoneTenantError( + 'Unable to retrieve tenantid for newly created tenant') tenantid = tenant_data[0] return tenantid @@ -400,7 +408,8 @@ def update_tenant_status(self, tenantid=None, enabled=None): self.database.commit() - def add_user(self, tenantid=None, username=None, email=None, password=None, apikey=None, enabled=True): + def add_user(self, tenantid=None, username=None, email=None, + password=None, apikey=None, enabled=True): args = { 'tenantid': tenantid, 'username': username, @@ -481,7 +490,8 @@ def get_users_for_tenant_id(self, tenantid=None): }) return results - def add_token(self, tenantid=None, userid=None, expire_time=None, token=None): + def add_token(self, tenantid=None, userid=None, + expire_time=None, token=None): if token is None: token = uuid.uuid4() @@ -493,7 +503,8 @@ def add_token(self, tenantid=None, userid=None, expire_time=None, token=None): } if expire_time is not None: if not isinstance(expire_time, datetime.datetime): - raise TypeError('expire_time must be a datetime.datetime object') + raise TypeError( + 'expire_time must be a datetime.datetime object') '''2015-02-03 02:31:17''' utc_expire_time = expire_time.utctimetuple() @@ -503,8 +514,7 @@ def add_token(self, tenantid=None, userid=None, expire_time=None, token=None): utc_expire_time[2], utc_expire_time[3], utc_expire_time[4], - utc_expire_time[5] - ) + utc_expire_time[5]) dbcursor.execute(SQL_INSERT_TOKEN_AND_EXPIRATION, args) else: dbcursor.execute(SQL_INSERT_TOKEN, args) @@ -527,7 +537,8 @@ def revoke_token(self, tenantid=None, userid=None, reset=False): dbcursor.execute(SQL_REVOKE_TOKEN, args) if not dbcursor.rowcount: - raise KeystoneTokenError('Unknown tenantid or userid; or no associated token') + raise KeystoneTokenError( + 'Unknown tenantid or userid; or no associated token') self.database.commit() @@ -622,7 +633,8 @@ def add_user_role_by_roleid(self, tenantid=None, userid=None, roleid=None): if not dbcursor.rowcount: raise KeystoneRoleError('Unable to assign role to tenantid/userid') - def add_user_role_by_rolename(self, tenantid=None, userid=None, rolename=None): + def add_user_role_by_rolename(self, tenantid=None, userid=None, + rolename=None): role_data = self.get_role_id(rolename) self.add_user_role_by_roleid(tenantid, userid, role_data['roleid']) diff --git a/stackinabox/services/keystone/v2/__init__.py b/stackinabox/services/keystone/v2/__init__.py index 734dfe4..662c20f 100644 --- a/stackinabox/services/keystone/v2/__init__.py +++ b/stackinabox/services/keystone/v2/__init__.py @@ -19,8 +19,12 @@ def __init__(self): self.__id = uuid.uuid4() self.__backend = KeystoneBackend() - self.register(StackInABoxService.GET, '/tenants', KeystoneV2Service.handle_list_tenants) - self.register(StackInABoxService.GET, '/users', KeystoneV2Service.handle_list_users) + self.register(StackInABoxService.GET, + '/tenants', + KeystoneV2Service.handle_list_tenants) + self.register(StackInABoxService.GET, + '/users', + KeystoneV2Service.handle_list_users) @property def backend(self): @@ -38,7 +42,8 @@ def handle_list_tenants(self, request, uri, headers): ''' 200, 203 -> OK - 400 -> Bad Request: one or more required parameters is missing or invalid + 400 -> Bad Request: one or more required parameters + are missing or invalid 401 -> not authorized 403 -> forbidden (no permission) 404 -> Not found @@ -56,12 +61,17 @@ def handle_list_tenants(self, request, uri, headers): """ Body on success: body = { - 'tenants' : [ {'id': 01234, 'name': 'bob', 'description': 'joe bob', 'enabled': True }] + 'tenants' : [ {'id': 01234, + 'name': 'bob', + 'description': 'joe bob', + 'enabled': True }] 'tenants_links': [] } """ response_body = { - 'tenants' : [tenant_info for tenant_info in self.backend.get_tenants()], + 'tenants': [tenant_info + for tenant_info in + self.backend.get_tenants()], 'tenants_links': [] } return (200, headers, json.dumps(response_body)) @@ -92,14 +102,18 @@ def user_data_filter(user): if 'x-auth-token' in req_headers: try: - user_data = self.backend.validate_token_admin(req_headers['x-auth-token']) + user_data = self.backend.validate_token_admin( + req_headers['x-auth-token']) + if user_data: - logger.debug('KeystoneV2Service({0}): Token Valid for tenantid {1}' + logger.debug('KeystoneV2Service({0}): Token Valid for ' + 'tenantid {1}' .format(self.__id, user_data['tenantid'])) response_body = { 'users': [user_data_filter(user_info) for user_info in - self.backend.get_users_for_tenant_id(user_data['tenantid'])] + self.backend.get_users_for_tenant_id( + user_data['tenantid'])] } return (200, headers, json.dumps(response_body)) @@ -107,6 +121,6 @@ def user_data_filter(user): return (200, headers, json.dumps({'users': []})) except Exception as ex: - return (401, headers, 'Not Authorized - {0} {1}'.format(ex, type(ex))) + return (401, headers, 'Not Authorized') else: return (403, headers, 'Forbidden') diff --git a/stackinabox/services/service.py b/stackinabox/services/service.py index c0723a7..c943e67 100644 --- a/stackinabox/services/service.py +++ b/stackinabox/services/service.py @@ -57,8 +57,12 @@ def base_url(self): @base_url.setter def base_url(self, value): - logger.debug('StackInABoxService ({0}:{1}) Updating Base URL from {2} to {3}' - .format(self.__id, self.name, self.__base_url, value)) + logger.debug('StackInABoxService ({0}:{1}) Updating Base URL ' + 'from {2} to {3}' + .format(self.__id, + self.name, + self.__base_url, + value)) self.__base_url = value for k, v in self.routes.items(): v['regex'] = StackInABoxService.__get_service_regex(value, @@ -70,21 +74,27 @@ def reset(self): self.base_url = '/{0}'.format(self.name) logger.debug('StackInABoxService ({0}): Hosting Service {1}' .format(self.__id, self.name)) - - + def request(self, method, request, uri, headers): logger.debug('StackInABoxService ({0}:{1}): Received {2} - {3}' .format(self.__id, self.name, method, uri)) for k, v in self.routes.items(): - logger.debug('StackInABoxService ({0}:{1}): Checking if route {1} handles...' + logger.debug('StackInABoxService ({0}:{1}): Checking if ' + 'route {1} handles...' .format(self.__id, self.name, v['uri'])) - logger.debug('StackInABoxService ({0}:{1}): ...using regex pattern {1} against {2}' - .format(self.__id, self.name, v['regex'].pattern, uri)) + logger.debug('StackInABoxService ({0}:{1}): ...using regex ' + 'pattern {1} against {2}' + .format(self.__id, + self.name, + v['regex'].pattern, + uri)) if v['regex'].match(uri): - logger.debug('StackInABoxService ({0}:{1}): Checking if method {2} is handled...' + logger.debug('StackInABoxService ({0}:{1}): Checking if ' + 'method {2} is handled...' .format(self.__id, self.name, method)) if method in v['handlers']: - logger.debug('StackInABoxService ({0}:{1}): Calling handler for method {2}...' + logger.debug('StackInABoxService ({0}:{1}): Calling ' + 'handler for method {2}...' .format(self.__id, self.name, method)) return v['handlers'][method](self, request, @@ -95,7 +105,7 @@ def request(self, method, request, uri, headers): def register(self, method, uri, call_back): found = False - if not uri in self.routes.keys(): + if uri not in self.routes.keys(): logger.debug('Service ({0}): Creating routes' .format(self.name)) self.routes[uri] = { @@ -106,7 +116,7 @@ def register(self, method, uri, call_back): } } - if not method in self.routes[uri]['handlers'].keys(): + if method not in self.routes[uri]['handlers'].keys(): logger.debug('Service ({0}): Adding route for {1}' .format(self.name, method)) self.routes[uri]['handlers'][method] = call_back diff --git a/stackinabox/stack.py b/stackinabox/stack.py index 7a7fb13..48db906 100644 --- a/stackinabox/stack.py +++ b/stackinabox/stack.py @@ -95,7 +95,7 @@ def reset(self): .format(self.__id)) def register(self, service): - if not service.name in self.services.keys(): + if service.name not in self.services.keys(): logger.debug('StackInABox({0}): Registering Service {1}' .format(self.__id, service.name)) regex = '^/{0}'.format(service.name) @@ -119,14 +119,15 @@ def call(self, method, request, uri, headers): matcher, service = v logger.debug('StackInABox({0}): Checking if Service {1} handles...' .format(self.__id, service.name)) - logger.debug('StackInABox({0}): ...using regex pattern {1} against {2}' + logger.debug('StackInABox({0}): ...using regex pattern {1} ' + 'against {2}' .format(self.__id, matcher.pattern, service_uri)) if matcher.match(service_uri): logger.debug('StackInABox({0}): Trying Service {1} handler...' .format(self.__id, service.name)) try: - service_caller_uri = service_uri[len(service.name)+1:] + service_caller_uri = service_uri[(len(service.name) + 1):] return service.request(method, request, service_caller_uri, diff --git a/stackinabox/test/test_keystone.py b/stackinabox/test/test_keystone.py index 669fe15..4e09e47 100644 --- a/stackinabox/test/test_keystone.py +++ b/stackinabox/test/test_keystone.py @@ -10,6 +10,7 @@ from stackinabox.stack import StackInABox from stackinabox.services.keystone.v2 import KeystoneV2Service + @httpretty.activate class TestHttpretty(unittest.TestCase): @@ -36,7 +37,8 @@ def test_tenant_listing(self): # There is always 1 tenant - the system self.assertEqual(len(tenant_data['tenants']), 1) - self.keystone.backend.add_tenant(tenantname='neo', description='The One') + self.keystone.backend.add_tenant(tenantname='neo', + description='The One') res = requests.get('http://localhost/keystone/v2.0/tenants', headers=self.headers) @@ -51,19 +53,23 @@ def test_tenant_listing(self): def test_user_listing(self): stackinabox.httpretty.httpretty_registration('localhost') - neo_tenant_id = self.keystone.backend.add_tenant(tenantname='neo', description='The One') + neo_tenant_id = self.keystone.backend.add_tenant(tenantname='neo', + description='The One') tom = self.keystone.backend.add_user(neo_tenant_id, 'tom', 'tom@theone.matrix', 'bluepill', 'iamnottheone', enabled=True) - self.keystone.backend.add_user_role_by_rolename(neo_tenant_id, tom, 'identity:user-admin') + self.keystone.backend.add_user_role_by_rolename(neo_tenant_id, + tom, + 'identity:user-admin') self.keystone.backend.add_token(neo_tenant_id, tom) - self.headers['x-auth-token'] = self.keystone.backend.get_token_by_userid(tom)['token'] + user_data = self.keystone.backend.get_token_by_userid(tom) + self.headers['x-auth-token'] = user_data['token'] res = requests.get('http://localhost/keystone/v2.0/users', - headers = self.headers) + headers=self.headers) print(res.text) self.assertEqual(res.status_code, 200) user_data = res.json() @@ -78,7 +84,7 @@ def test_user_listing(self): enabled=True) res = requests.get('http://localhost/keystone/v2.0/users', - headers = self.headers) + headers=self.headers) self.assertEqual(res.status_code, 200) user_data = res.json()