diff options
Diffstat (limited to 'utils/test')
20 files changed, 472 insertions, 300 deletions
diff --git a/utils/test/reporting/img/danube.jpg b/utils/test/reporting/img/danube.jpg Binary files differindex a5778356f..2d8e27b60 100644 --- a/utils/test/reporting/img/danube.jpg +++ b/utils/test/reporting/img/danube.jpg diff --git a/utils/test/testapi/opnfv_testapi/common/check.py b/utils/test/testapi/opnfv_testapi/common/check.py new file mode 100644 index 000000000..be4b1df12 --- /dev/null +++ b/utils/test/testapi/opnfv_testapi/common/check.py @@ -0,0 +1,111 @@ +############################################################################## +# Copyright (c) 2017 ZTE Corp +# feng.xiaowei@zte.com.cn +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 +############################################################################## +import functools + +from tornado import web, gen + +from opnfv_testapi.common import raises, message + + +def authenticate(method): + @web.asynchronous + @gen.coroutine + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + if self.auth: + try: + token = self.request.headers['X-Auth-Token'] + except KeyError: + raises.Unauthorized(message.unauthorized()) + query = {'access_token': token} + check = yield self._eval_db_find_one(query, 'tokens') + if not check: + raises.Forbidden(message.invalid_token()) + ret = yield gen.coroutine(method)(self, *args, **kwargs) + raise gen.Return(ret) + return wrapper + + +def not_exist(xstep): + @functools.wraps(xstep) + def wrap(self, *args, **kwargs): + query = kwargs.get('query') + data = yield self._eval_db_find_one(query) + if not data: + raises.NotFound(message.not_found(self.table, query)) + ret = yield gen.coroutine(xstep)(self, data, *args, **kwargs) + raise gen.Return(ret) + + return wrap + + +def no_body(xstep): + @functools.wraps(xstep) + def wrap(self, *args, **kwargs): + if self.json_args is None: + raises.BadRequest(message.no_body()) + ret = yield gen.coroutine(xstep)(self, *args, **kwargs) + raise gen.Return(ret) + + return wrap + + +def miss_fields(xstep): + @functools.wraps(xstep) + def wrap(self, *args, **kwargs): + fields = kwargs.get('miss_fields') + if fields: + for miss in fields: + miss_data = self.json_args.get(miss) + if miss_data is None or miss_data == '': + raises.BadRequest(message.missing(miss)) + ret = yield gen.coroutine(xstep)(self, *args, **kwargs) + raise gen.Return(ret) + return wrap + + +def carriers_exist(xstep): + @functools.wraps(xstep) + def wrap(self, *args, **kwargs): + carriers = kwargs.get('carriers') + if carriers: + for table, query in carriers: + exist = yield self._eval_db_find_one(query(), table) + if not exist: + raises.Forbidden(message.not_found(table, query())) + ret = yield gen.coroutine(xstep)(self, *args, **kwargs) + raise gen.Return(ret) + return wrap + + +def new_not_exists(xstep): + @functools.wraps(xstep) + def wrap(self, *args, **kwargs): + query = kwargs.get('query') + if query: + to_data = yield self._eval_db_find_one(query()) + if to_data: + raises.Forbidden(message.exist(self.table, query())) + ret = yield gen.coroutine(xstep)(self, *args, **kwargs) + raise gen.Return(ret) + return wrap + + +def updated_one_not_exist(xstep): + @functools.wraps(xstep) + def wrap(self, data, *args, **kwargs): + db_keys = kwargs.get('db_keys') + query = self._update_query(db_keys, data) + if query: + to_data = yield self._eval_db_find_one(query) + if to_data: + raises.Forbidden(message.exist(self.table, query)) + ret = yield gen.coroutine(xstep)(self, data, *args, **kwargs) + raise gen.Return(ret) + return wrap diff --git a/utils/test/testapi/opnfv_testapi/common/message.py b/utils/test/testapi/opnfv_testapi/common/message.py new file mode 100644 index 000000000..98536ff4b --- /dev/null +++ b/utils/test/testapi/opnfv_testapi/common/message.py @@ -0,0 +1,46 @@ +############################################################################## +# Copyright (c) 2017 ZTE Corp +# feng.xiaowei@zte.com.cn +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 +############################################################################## +not_found_base = 'Could Not Found' +exist_base = 'Already Exists' + + +def no_body(): + return 'No Body' + + +def not_found(key, value): + return '{} {} [{}]'.format(not_found_base, key, value) + + +def missing(name): + return '{} Missing'.format(name) + + +def exist(key, value): + return '{} [{}] {}'.format(key, value, exist_base) + + +def bad_format(error): + return 'Bad Format [{}]'.format(error) + + +def unauthorized(): + return 'No Authentication Header' + + +def invalid_token(): + return 'Invalid Token' + + +def no_update(): + return 'Nothing to update' + + +def must_int(name): + return '{} must be int'.format(name) diff --git a/utils/test/testapi/opnfv_testapi/common/raises.py b/utils/test/testapi/opnfv_testapi/common/raises.py new file mode 100644 index 000000000..ec6b8a564 --- /dev/null +++ b/utils/test/testapi/opnfv_testapi/common/raises.py @@ -0,0 +1,39 @@ +############################################################################## +# Copyright (c) 2017 ZTE Corp +# feng.xiaowei@zte.com.cn +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 +############################################################################## +import httplib + +from tornado import web + + +class Raiser(object): + code = httplib.OK + + def __init__(self, reason): + raise web.HTTPError(self.code, reason) + + +class BadRequest(Raiser): + code = httplib.BAD_REQUEST + + +class Forbidden(Raiser): + code = httplib.FORBIDDEN + + +class NotFound(Raiser): + code = httplib.NOT_FOUND + + +class Unauthorized(Raiser): + code = httplib.UNAUTHORIZED + + +class CodeTBD(object): + def __init__(self, code, reason): + raise web.HTTPError(code, reason) diff --git a/utils/test/testapi/opnfv_testapi/resources/handlers.py b/utils/test/testapi/opnfv_testapi/resources/handlers.py index bf8a92b54..955fbbef7 100644 --- a/utils/test/testapi/opnfv_testapi/resources/handlers.py +++ b/utils/test/testapi/opnfv_testapi/resources/handlers.py @@ -21,14 +21,15 @@ ############################################################################## from datetime import datetime -import functools -import httplib import json from tornado import gen from tornado import web import models +from opnfv_testapi.common import check +from opnfv_testapi.common import message +from opnfv_testapi.common import raises from opnfv_testapi.tornado_swagger import swagger DEFAULT_REPRESENTATION = "application/json" @@ -56,9 +57,7 @@ class GenericApiHandler(web.RequestHandler): try: self.json_args = json.loads(self.request.body) except (ValueError, KeyError, TypeError) as error: - raise web.HTTPError(httplib.BAD_REQUEST, - "Bad Json format [{}]". - format(error)) + raises.BadRequest(message.bad_format(str(error))) def finish_request(self, json_object=None): if json_object: @@ -74,51 +73,20 @@ class GenericApiHandler(web.RequestHandler): cls_data = self.table_cls.from_dict(data) return cls_data.format_http() - def authenticate(method): - @web.asynchronous - @gen.coroutine - @functools.wraps(method) - def wrapper(self, *args, **kwargs): - if self.auth: - try: - token = self.request.headers['X-Auth-Token'] - except KeyError: - raise web.HTTPError(httplib.UNAUTHORIZED, - "No Authentication Header.") - query = {'access_token': token} - check = yield self._eval_db_find_one(query, 'tokens') - if not check: - raise web.HTTPError(httplib.FORBIDDEN, - "Invalid Token.") - ret = yield gen.coroutine(method)(self, *args, **kwargs) - raise gen.Return(ret) - return wrapper - - @authenticate - def _create(self, miss_checks, db_checks, **kwargs): + @check.authenticate + @check.no_body + @check.miss_fields + @check.carriers_exist + @check.new_not_exists + def _create(self, **kwargs): """ :param miss_checks: [miss1, miss2] :param db_checks: [(table, exist, query, error)] """ - if self.json_args is None: - raise web.HTTPError(httplib.BAD_REQUEST, "no body") - data = self.table_cls.from_dict(self.json_args) - for miss in miss_checks: - miss_data = data.__getattribute__(miss) - if miss_data is None or miss_data == '': - raise web.HTTPError(httplib.BAD_REQUEST, - '{} missing'.format(miss)) - for k, v in kwargs.iteritems(): data.__setattr__(k, v) - for table, exist, query, error in db_checks: - check = yield self._eval_db_find_one(query(data), table) - if (exist and not check) or (not exist and check): - code, message = error(data) - raise web.HTTPError(code, message) - if self.table != 'results': data.creation_date = datetime.now() _id = yield self._eval_db(self.table, 'insert', data.format(), @@ -150,55 +118,27 @@ class GenericApiHandler(web.RequestHandler): @web.asynchronous @gen.coroutine - def _get_one(self, query): - data = yield self._eval_db_find_one(query) - if data is None: - raise web.HTTPError(httplib.NOT_FOUND, - "[{}] not exist in table [{}]" - .format(query, self.table)) + @check.not_exist + def _get_one(self, data, query=None): self.finish_request(self.format_data(data)) - @authenticate - def _delete(self, query): - data = yield self._eval_db_find_one(query) - if data is None: - raise web.HTTPError(httplib.NOT_FOUND, - "[{}] not exit in table [{}]" - .format(query, self.table)) - + @check.authenticate + @check.not_exist + def _delete(self, data, query=None): yield self._eval_db(self.table, 'remove', query) self.finish_request() - @authenticate - def _update(self, query, db_keys): - if self.json_args is None: - raise web.HTTPError(httplib.BAD_REQUEST, "No payload") - - # check old data exist - from_data = yield self._eval_db_find_one(query) - if from_data is None: - raise web.HTTPError(httplib.NOT_FOUND, - "{} could not be found in table [{}]" - .format(query, self.table)) - - data = self.table_cls.from_dict(from_data) - # check new data exist - equal, new_query = self._update_query(db_keys, data) - if not equal: - to_data = yield self._eval_db_find_one(new_query) - if to_data is not None: - raise web.HTTPError(httplib.FORBIDDEN, - "{} already exists in table [{}]" - .format(new_query, self.table)) - - # we merge the whole document """ - edit_request = self._update_requests(data) - - """ Updating the DB """ - yield self._eval_db(self.table, 'update', query, edit_request, + @check.authenticate + @check.no_body + @check.not_exist + @check.updated_one_not_exist + def _update(self, data, query=None, **kwargs): + data = self.table_cls.from_dict(data) + update_req = self._update_requests(data) + yield self._eval_db(self.table, 'update', query, update_req, check_keys=False) - edit_request['_id'] = str(data._id) - self.finish_request(edit_request) + update_req['_id'] = str(data._id) + self.finish_request(update_req) def _update_requests(self, data): request = dict() @@ -206,7 +146,7 @@ class GenericApiHandler(web.RequestHandler): request = self._update_request(request, k, v, data.__getattribute__(k)) if not request: - raise web.HTTPError(httplib.FORBIDDEN, "Nothing to update") + raises.Forbidden(message.no_update()) edit_request = data.format() edit_request.update(request) @@ -231,13 +171,13 @@ class GenericApiHandler(web.RequestHandler): equal = True for key in keys: new = self.json_args.get(key) - old = data.__getattribute__(key) + old = data.get(key) if new is None: new = old elif new != old: equal = False query[key] = new - return equal, query + return query if not equal else dict() def _eval_db(self, table, method, *args, **kwargs): exec_collection = self.db.__getattr__(table) diff --git a/utils/test/testapi/opnfv_testapi/resources/pod_handlers.py b/utils/test/testapi/opnfv_testapi/resources/pod_handlers.py index fd9ce3eb5..e21841d33 100644 --- a/utils/test/testapi/opnfv_testapi/resources/pod_handlers.py +++ b/utils/test/testapi/opnfv_testapi/resources/pod_handlers.py @@ -6,8 +6,6 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -import httplib - import handlers from opnfv_testapi.tornado_swagger import swagger import pod_models @@ -42,16 +40,10 @@ class PodCLHandler(GenericPodHandler): @raise 403: pod already exists @raise 400: body or name not provided """ - def query(data): - return {'name': data.name} - - def error(data): - message = '{} already exists as a pod'.format(data.name) - return httplib.FORBIDDEN, message - - miss_checks = ['name'] - db_checks = [(self.table, False, query, error)] - self._create(miss_checks, db_checks) + def query(): + return {'name': self.json_args.get('name')} + miss_fields = ['name'] + self._create(miss_fields=miss_fields, query=query) class PodGURHandler(GenericPodHandler): @@ -63,9 +55,7 @@ class PodGURHandler(GenericPodHandler): @return 200: pod exist @raise 404: pod not exist """ - query = dict() - query['name'] = pod_name - self._get_one(query) + self._get_one(query={'name': pod_name}) def delete(self, pod_name): """ Remove a POD diff --git a/utils/test/testapi/opnfv_testapi/resources/project_handlers.py b/utils/test/testapi/opnfv_testapi/resources/project_handlers.py index 087bb8af2..d79cd3b61 100644 --- a/utils/test/testapi/opnfv_testapi/resources/project_handlers.py +++ b/utils/test/testapi/opnfv_testapi/resources/project_handlers.py @@ -6,7 +6,6 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -import httplib import handlers from opnfv_testapi.tornado_swagger import swagger @@ -44,16 +43,10 @@ class ProjectCLHandler(GenericProjectHandler): @raise 403: project already exists @raise 400: body or name not provided """ - def query(data): - return {'name': data.name} - - def error(data): - message = '{} already exists as a project'.format(data.name) - return httplib.FORBIDDEN, message - - miss_checks = ['name'] - db_checks = [(self.table, False, query, error)] - self._create(miss_checks, db_checks) + def query(): + return {'name': self.json_args.get('name')} + miss_fields = ['name'] + self._create(miss_fields=miss_fields, query=query) class ProjectGURHandler(GenericProjectHandler): @@ -65,7 +58,7 @@ class ProjectGURHandler(GenericProjectHandler): @return 200: project exist @raise 404: project not exist """ - self._get_one({'name': project_name}) + self._get_one(query={'name': project_name}) @swagger.operation(nickname="updateProjectByName") def put(self, project_name): @@ -81,7 +74,7 @@ class ProjectGURHandler(GenericProjectHandler): """ query = {'name': project_name} db_keys = ['name'] - self._update(query, db_keys) + self._update(query=query, db_keys=db_keys) @swagger.operation(nickname='deleteProjectByName') def delete(self, project_name): @@ -90,4 +83,4 @@ class ProjectGURHandler(GenericProjectHandler): @return 200: delete success @raise 404: project not exist """ - self._delete({'name': project_name}) + self._delete(query={'name': project_name}) diff --git a/utils/test/testapi/opnfv_testapi/resources/result_handlers.py b/utils/test/testapi/opnfv_testapi/resources/result_handlers.py index 44b9f8c07..214706f5f 100644 --- a/utils/test/testapi/opnfv_testapi/resources/result_handlers.py +++ b/utils/test/testapi/opnfv_testapi/resources/result_handlers.py @@ -8,11 +8,11 @@ ############################################################################## from datetime import datetime from datetime import timedelta -import httplib from bson import objectid -from tornado import web +from opnfv_testapi.common import message +from opnfv_testapi.common import raises from opnfv_testapi.resources import handlers from opnfv_testapi.resources import result_models from opnfv_testapi.tornado_swagger import swagger @@ -30,8 +30,7 @@ class GenericResultHandler(handlers.GenericApiHandler): try: value = int(value) except: - raise web.HTTPError(httplib.BAD_REQUEST, - '{} must be int'.format(key)) + raises.BadRequest(message.must_int(key)) return value def set_query(self): @@ -127,7 +126,9 @@ class ResultsCLHandler(GenericResultHandler): if last is not None: last = self.get_int('last', last) - self._list(self.set_query(), sort=[('start_date', -1)], last=last) + self._list(query=self.set_query(), + sort=[('start_date', -1)], + last=last) @swagger.operation(nickname="createTestResult") def post(self): @@ -141,33 +142,21 @@ class ResultsCLHandler(GenericResultHandler): @raise 404: pod/project/testcase not exist @raise 400: body/pod_name/project_name/case_name not provided """ - def pod_query(data): - return {'name': data.pod_name} + def pod_query(): + return {'name': self.json_args.get('pod_name')} - def pod_error(data): - message = 'Could not find pod [{}]'.format(data.pod_name) - return httplib.NOT_FOUND, message + def project_query(): + return {'name': self.json_args.get('project_name')} - def project_query(data): - return {'name': data.project_name} + def testcase_query(): + return {'project_name': self.json_args.get('project_name'), + 'name': self.json_args.get('case_name')} - def project_error(data): - message = 'Could not find project [{}]'.format(data.project_name) - return httplib.NOT_FOUND, message - - def testcase_query(data): - return {'project_name': data.project_name, 'name': data.case_name} - - def testcase_error(data): - message = 'Could not find testcase [{}] in project [{}]'\ - .format(data.case_name, data.project_name) - return httplib.NOT_FOUND, message - - miss_checks = ['pod_name', 'project_name', 'case_name'] - db_checks = [('pods', True, pod_query, pod_error), - ('projects', True, project_query, project_error), - ('testcases', True, testcase_query, testcase_error)] - self._create(miss_checks, db_checks) + miss_fields = ['pod_name', 'project_name', 'case_name'] + carriers = [('pods', pod_query), + ('projects', project_query), + ('testcases', testcase_query)] + self._create(miss_fields=miss_fields, carriers=carriers) class ResultsGURHandler(GenericResultHandler): @@ -181,7 +170,7 @@ class ResultsGURHandler(GenericResultHandler): """ query = dict() query["_id"] = objectid.ObjectId(result_id) - self._get_one(query) + self._get_one(query=query) @swagger.operation(nickname="updateTestResultById") def put(self, result_id): @@ -197,4 +186,4 @@ class ResultsGURHandler(GenericResultHandler): """ query = {'_id': objectid.ObjectId(result_id)} db_keys = [] - self._update(query, db_keys) + self._update(query=query, db_keys=db_keys) diff --git a/utils/test/testapi/opnfv_testapi/resources/scenario_handlers.py b/utils/test/testapi/opnfv_testapi/resources/scenario_handlers.py index a2856dbd7..5d420a56e 100644 --- a/utils/test/testapi/opnfv_testapi/resources/scenario_handlers.py +++ b/utils/test/testapi/opnfv_testapi/resources/scenario_handlers.py @@ -1,8 +1,7 @@ import functools -import httplib - -from tornado import web +from opnfv_testapi.common import message +from opnfv_testapi.common import raises from opnfv_testapi.resources import handlers import opnfv_testapi.resources.scenario_models as models from opnfv_testapi.tornado_swagger import swagger @@ -65,7 +64,7 @@ class ScenariosCLHandler(GenericScenarioHandler): query['installers'] = {'$elemMatch': elem_query} return query - self._list(_set_query()) + self._list(query=_set_query()) @swagger.operation(nickname="createScenario") def post(self): @@ -79,16 +78,10 @@ class ScenariosCLHandler(GenericScenarioHandler): @raise 403: scenario already exists @raise 400: body or name not provided """ - def query(data): - return {'name': data.name} - - def error(data): - message = '{} already exists as a scenario'.format(data.name) - return httplib.FORBIDDEN, message - - miss_checks = ['name'] - db_checks = [(self.table, False, query, error)] - self._create(miss_checks=miss_checks, db_checks=db_checks) + def query(): + return {'name': self.json_args.get('name')} + miss_fields = ['name'] + self._create(miss_fields=miss_fields, query=query) class ScenarioGURHandler(GenericScenarioHandler): @@ -100,7 +93,7 @@ class ScenarioGURHandler(GenericScenarioHandler): @return 200: scenario exist @raise 404: scenario not exist """ - self._get_one({'name': name}) + self._get_one(query={'name': name}) pass @swagger.operation(nickname="updateScenarioByName") @@ -117,7 +110,7 @@ class ScenarioGURHandler(GenericScenarioHandler): """ query = {'name': name} db_keys = ['name'] - self._update(query, db_keys) + self._update(query=query, db_keys=db_keys) @swagger.operation(nickname="deleteScenarioByName") def delete(self, name): @@ -127,19 +120,16 @@ class ScenarioGURHandler(GenericScenarioHandler): @raise 404: scenario not exist: """ - query = {'name': name} - self._delete(query) + self._delete(query={'name': name}) def _update_query(self, keys, data): query = dict() - equal = True if self._is_rename(): new = self._term.get('name') - if data.name != new: - equal = False + if data.get('name') != new: query['name'] = new - return equal, query + return query def _update_requests(self, data): updates = { @@ -185,8 +175,7 @@ class ScenarioGURHandler(GenericScenarioHandler): def _update_requests_rename(self, data): data.name = self._term.get('name') if not data.name: - raise web.HTTPError(httplib.BAD_REQUEST, - "new scenario name is not provided") + raises.BadRequest(message.missing('name')) def _update_requests_add_installer(self, data): data.installers.append(models.ScenarioInstaller.from_dict(self._term)) diff --git a/utils/test/testapi/opnfv_testapi/resources/testcase_handlers.py b/utils/test/testapi/opnfv_testapi/resources/testcase_handlers.py index 1211a0573..9399326f0 100644 --- a/utils/test/testapi/opnfv_testapi/resources/testcase_handlers.py +++ b/utils/test/testapi/opnfv_testapi/resources/testcase_handlers.py @@ -6,7 +6,6 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -import httplib from opnfv_testapi.resources import handlers from opnfv_testapi.resources import testcase_models @@ -31,9 +30,7 @@ class TestcaseCLHandler(GenericTestcaseHandler): empty list is no testcase exist in this project @rtype: L{TestCases} """ - query = dict() - query['project_name'] = project_name - self._list(query) + self._list(query={'project_name': project_name}) @swagger.operation(nickname="createTestCase") def post(self, project_name): @@ -48,28 +45,18 @@ class TestcaseCLHandler(GenericTestcaseHandler): or testcase already exists in this project @raise 400: body or name not provided """ - def p_query(data): - return {'name': data.project_name} - - def tc_query(data): - return { - 'project_name': data.project_name, - 'name': data.name - } - - def p_error(data): - message = 'Could not find project [{}]'.format(data.project_name) - return httplib.FORBIDDEN, message - - def tc_error(data): - message = '{} already exists as a testcase in project {}'\ - .format(data.name, data.project_name) - return httplib.FORBIDDEN, message + def project_query(): + return {'name': project_name} - miss_checks = ['name'] - db_checks = [(self.db_projects, True, p_query, p_error), - (self.db_testcases, False, tc_query, tc_error)] - self._create(miss_checks, db_checks, project_name=project_name) + def testcase_query(): + return {'project_name': project_name, + 'name': self.json_args.get('name')} + miss_fields = ['name'] + carriers = [(self.db_projects, project_query)] + self._create(miss_fields=miss_fields, + carriers=carriers, + query=testcase_query, + project_name=project_name) class TestcaseGURHandler(GenericTestcaseHandler): @@ -85,7 +72,7 @@ class TestcaseGURHandler(GenericTestcaseHandler): query = dict() query['project_name'] = project_name query["name"] = case_name - self._get_one(query) + self._get_one(query=query) @swagger.operation(nickname="updateTestCaseByName") def put(self, project_name, case_name): @@ -103,7 +90,7 @@ class TestcaseGURHandler(GenericTestcaseHandler): """ query = {'project_name': project_name, 'name': case_name} db_keys = ['name', 'project_name'] - self._update(query, db_keys) + self._update(query=query, db_keys=db_keys) @swagger.operation(nickname='deleteTestCaseByName') def delete(self, project_name, case_name): @@ -113,4 +100,4 @@ class TestcaseGURHandler(GenericTestcaseHandler): @raise 404: testcase not exist """ query = {'project_name': project_name, 'name': case_name} - self._delete(query) + self._delete(query=query) diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/executor.py b/utils/test/testapi/opnfv_testapi/tests/unit/executor.py new file mode 100644 index 000000000..b30c3258b --- /dev/null +++ b/utils/test/testapi/opnfv_testapi/tests/unit/executor.py @@ -0,0 +1,83 @@ +############################################################################## +# Copyright (c) 2017 ZTE Corp +# feng.xiaowei@zte.com.cn +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 +############################################################################## +import functools +import httplib + + +def create(excepted_status, excepted_response): + def _create(create_request): + @functools.wraps(create_request) + def wrap(self): + request = create_request(self) + status, body = self.create(request) + if excepted_status == httplib.OK: + getattr(self, excepted_response)(body) + else: + self.assertIn(excepted_response, body) + return wrap + return _create + + +def get(excepted_status, excepted_response): + def _get(get_request): + @functools.wraps(get_request) + def wrap(self): + request = get_request(self) + status, body = self.get(request) + if excepted_status == httplib.OK: + getattr(self, excepted_response)(body) + else: + self.assertIn(excepted_response, body) + return wrap + return _get + + +def update(excepted_status, excepted_response): + def _update(update_request): + @functools.wraps(update_request) + def wrap(self): + request, resource = update_request(self) + status, body = self.update(request, resource) + if excepted_status == httplib.OK: + getattr(self, excepted_response)(request, body) + else: + self.assertIn(excepted_response, body) + return wrap + return _update + + +def delete(excepted_status, excepted_response): + def _delete(delete_request): + @functools.wraps(delete_request) + def wrap(self): + request = delete_request(self) + if isinstance(request, tuple): + status, body = self.delete(request[0], *(request[1])) + else: + status, body = self.delete(request) + if excepted_status == httplib.OK: + getattr(self, excepted_response)(body) + else: + self.assertIn(excepted_response, body) + return wrap + return _delete + + +def query(excepted_status, excepted_response, number=0): + def _query(get_request): + @functools.wraps(get_request) + def wrap(self): + request = get_request(self) + status, body = self.query(request) + if excepted_status == httplib.OK: + getattr(self, excepted_response)(body, number) + else: + self.assertIn(excepted_response, body) + return wrap + return _query diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_base.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_base.py index b955f4a5a..a6e733914 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_base.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_base.py @@ -12,9 +12,9 @@ from os import path import mock from tornado import testing -import fake_pymongo from opnfv_testapi.cmd import server from opnfv_testapi.resources import models +from opnfv_testapi.tests.unit import fake_pymongo class TestBase(testing.AsyncHTTPTestCase): diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_fake_pymongo.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_fake_pymongo.py index 7c43fca62..1ebc96f3b 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_fake_pymongo.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_fake_pymongo.py @@ -12,7 +12,7 @@ from tornado import gen from tornado import testing from tornado import web -import fake_pymongo +from opnfv_testapi.tests.unit import fake_pymongo class MyTest(testing.AsyncHTTPTestCase): diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_pod.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_pod.py index cec90d8a5..0ed348df9 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_pod.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_pod.py @@ -9,8 +9,10 @@ import httplib import unittest +from opnfv_testapi.common import message from opnfv_testapi.resources import pod_models -import test_base as base +from opnfv_testapi.tests.unit import executor +from opnfv_testapi.tests.unit import test_base as base class TestPodBase(base.TestBase): @@ -35,48 +37,47 @@ class TestPodBase(base.TestBase): class TestPodCreate(TestPodBase): + @executor.create(httplib.BAD_REQUEST, message.no_body()) def test_withoutBody(self): - (code, body) = self.create() - self.assertEqual(code, httplib.BAD_REQUEST) + return None + @executor.create(httplib.BAD_REQUEST, message.missing('name')) def test_emptyName(self): - req_empty = pod_models.PodCreateRequest('') - (code, body) = self.create(req_empty) - self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + return pod_models.PodCreateRequest('') + @executor.create(httplib.BAD_REQUEST, message.missing('name')) def test_noneName(self): - req_none = pod_models.PodCreateRequest(None) - (code, body) = self.create(req_none) - self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + return pod_models.PodCreateRequest(None) + @executor.create(httplib.OK, 'assert_create_body') def test_success(self): - code, body = self.create_d() - self.assertEqual(code, httplib.OK) - self.assert_create_body(body) + return self.req_d + @executor.create(httplib.FORBIDDEN, message.exist_base) def test_alreadyExist(self): self.create_d() - code, body = self.create_d() - self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('already exists', body) + return self.req_d class TestPodGet(TestPodBase): + def setUp(self): + super(TestPodGet, self).setUp() + self.create_d() + self.create_e() + + @executor.get(httplib.NOT_FOUND, message.not_found_base) def test_notExist(self): - code, body = self.get('notExist') - self.assertEqual(code, httplib.NOT_FOUND) + return 'notExist' + @executor.get(httplib.OK, 'assert_get_body') def test_getOne(self): - self.create_d() - code, body = self.get(self.req_d.name) - self.assert_get_body(body) + return self.req_d.name + @executor.get(httplib.OK, '_assert_list') def test_list(self): - self.create_d() - self.create_e() - code, body = self.get() + return None + + def _assert_list(self, body): self.assertEqual(len(body.pods), 2) for pod in body.pods: if self.req_d.name == pod.name: diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_project.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_project.py index 75b2d5260..9143f8a8a 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_project.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_project.py @@ -9,8 +9,9 @@ import httplib import unittest +from opnfv_testapi.common import message from opnfv_testapi.resources import project_models -import test_base as base +from opnfv_testapi.tests.unit import test_base as base class TestProjectBase(base.TestBase): @@ -43,13 +44,13 @@ class TestProjectCreate(TestProjectBase): req_empty = project_models.ProjectCreateRequest('') (code, body) = self.create(req_empty) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + self.assertIn(message.missing('name'), body) def test_noneName(self): req_none = project_models.ProjectCreateRequest(None) (code, body) = self.create(req_none) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + self.assertIn(message.missing('name'), body) def test_success(self): (code, body) = self.create_d() @@ -60,7 +61,7 @@ class TestProjectCreate(TestProjectBase): self.create_d() (code, body) = self.create_d() self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('already exists', body) + self.assertIn(message.exist_base, body) class TestProjectGet(TestProjectBase): @@ -99,13 +100,13 @@ class TestProjectUpdate(TestProjectBase): self.create_e() code, body = self.update(self.req_e, self.req_d.name) self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn("already exists", body) + self.assertIn(message.exist_base, body) def test_noUpdate(self): self.create_d() code, body = self.update(self.req_d, self.req_d.name) self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn("Nothing to update", body) + self.assertIn(message.no_update(), body) def test_success(self): self.create_d() diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_result.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_result.py index 05220f1d2..940279cd4 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_result.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_result.py @@ -11,11 +11,12 @@ from datetime import datetime, timedelta import httplib import unittest +from opnfv_testapi.common import message from opnfv_testapi.resources import pod_models from opnfv_testapi.resources import project_models from opnfv_testapi.resources import result_models from opnfv_testapi.resources import testcase_models -import test_base as base +from opnfv_testapi.tests.unit import test_base as base class Details(object): @@ -135,49 +136,49 @@ class TestResultCreate(TestResultBase): def test_nobody(self): (code, body) = self.create(None) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('no body', body) + self.assertIn(message.no_body(), body) def test_podNotProvided(self): req = self.req_d req.pod_name = None (code, body) = self.create(req) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('pod_name missing', body) + self.assertIn(message.missing('pod_name'), body) def test_projectNotProvided(self): req = self.req_d req.project_name = None (code, body) = self.create(req) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('project_name missing', body) + self.assertIn(message.missing('project_name'), body) def test_testcaseNotProvided(self): req = self.req_d req.case_name = None (code, body) = self.create(req) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('case_name missing', body) + self.assertIn(message.missing('case_name'), body) def test_noPod(self): req = self.req_d req.pod_name = 'notExistPod' (code, body) = self.create(req) - self.assertEqual(code, httplib.NOT_FOUND) - self.assertIn('Could not find pod', body) + self.assertEqual(code, httplib.FORBIDDEN) + self.assertIn(message.not_found_base, body) def test_noProject(self): req = self.req_d req.project_name = 'notExistProject' (code, body) = self.create(req) - self.assertEqual(code, httplib.NOT_FOUND) - self.assertIn('Could not find project', body) + self.assertEqual(code, httplib.FORBIDDEN) + self.assertIn(message.not_found_base, body) def test_noTestcase(self): req = self.req_d req.case_name = 'notExistTestcase' (code, body) = self.create(req) - self.assertEqual(code, httplib.NOT_FOUND) - self.assertIn('Could not find testcase', body) + self.assertEqual(code, httplib.FORBIDDEN) + self.assertIn(message.not_found_base, body) def test_success(self): (code, body) = self.create_d() diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_scenario.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_scenario.py index ab2c34b31..b232bc168 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_scenario.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_scenario.py @@ -5,8 +5,9 @@ import httplib import json import os +from opnfv_testapi.common import message import opnfv_testapi.resources.scenario_models as models -import test_base as base +from opnfv_testapi.tests.unit import test_base as base class TestScenarioBase(base.TestBase): @@ -66,13 +67,13 @@ class TestScenarioCreate(TestScenarioBase): req_empty = models.ScenarioCreateRequest('') (code, body) = self.create(req_empty) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + self.assertIn(message.missing('name'), body) def test_noneName(self): req_none = models.ScenarioCreateRequest(None) (code, body) = self.create(req_none) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + self.assertIn(message.missing('name'), body) def test_success(self): (code, body) = self.create_d() @@ -83,7 +84,7 @@ class TestScenarioCreate(TestScenarioBase): self.create_d() (code, body) = self.create_d() self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('already exists', body) + self.assertIn(message.exist_base, body) class TestScenarioGet(TestScenarioBase): diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_testcase.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_testcase.py index ec44fcae5..73c481986 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_testcase.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_testcase.py @@ -10,9 +10,10 @@ import copy import httplib import unittest +from opnfv_testapi.common import message from opnfv_testapi.resources import project_models from opnfv_testapi.resources import testcase_models -import test_base as base +from opnfv_testapi.tests.unit import test_base as base class TestCaseBase(base.TestBase): @@ -84,19 +85,19 @@ class TestCaseCreate(TestCaseBase): def test_noProject(self): code, body = self.create(self.req_d, 'noProject') self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('Could not find project', body) + self.assertIn(message.not_found_base, body) def test_emptyName(self): req_empty = testcase_models.TestcaseCreateRequest('') (code, body) = self.create(req_empty, self.project) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + self.assertIn(message.missing('name'), body) def test_noneName(self): req_none = testcase_models.TestcaseCreateRequest(None) (code, body) = self.create(req_none, self.project) self.assertEqual(code, httplib.BAD_REQUEST) - self.assertIn('name missing', body) + self.assertIn(message.missing('name'), body) def test_success(self): code, body = self.create_d() @@ -107,7 +108,7 @@ class TestCaseCreate(TestCaseBase): self.create_d() code, body = self.create_d() self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('already exists', body) + self.assertIn(message.exist_base, body) class TestCaseGet(TestCaseBase): @@ -146,13 +147,13 @@ class TestCaseUpdate(TestCaseBase): self.create_e() code, body = self.update(self.update_e, self.req_d.name) self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn("already exists", body) + self.assertIn(message.exist_base, body) def test_noUpdate(self): self.create_d() code, body = self.update(self.update_d, self.req_d.name) self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn("Nothing to update", body) + self.assertIn(message.no_update(), body) def test_success(self): self.create_d() diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_token.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_token.py index 9cc52a2f0..ca247a3b7 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_token.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_token.py @@ -8,10 +8,12 @@ import unittest from tornado import web -import fake_pymongo +from opnfv_testapi.common import message from opnfv_testapi.resources import project_models from opnfv_testapi.router import url_mappings -import test_base as base +from opnfv_testapi.tests.unit import executor +from opnfv_testapi.tests.unit import fake_pymongo +from opnfv_testapi.tests.unit import test_base as base class TestToken(base.TestBase): @@ -31,22 +33,24 @@ class TestTokenCreateProject(TestToken): fake_pymongo.tokens.insert({"access_token": "12345"}) self.basePath = '/api/v1/projects' + @executor.create(httplib.FORBIDDEN, message.invalid_token()) def test_projectCreateTokenInvalid(self): self.headers['X-Auth-Token'] = '1234' - code, body = self.create_d() - self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('Invalid Token.', body) + return self.req_d + @executor.create(httplib.UNAUTHORIZED, message.unauthorized()) def test_projectCreateTokenUnauthorized(self): - self.headers.pop('X-Auth-Token') - code, body = self.create_d() - self.assertEqual(code, httplib.UNAUTHORIZED) - self.assertIn('No Authentication Header.', body) + if 'X-Auth-Token' in self.headers: + self.headers.pop('X-Auth-Token') + return self.req_d + @executor.create(httplib.OK, '_create_success') def test_projectCreateTokenSuccess(self): self.headers['X-Auth-Token'] = '12345' - code, body = self.create_d() - self.assertEqual(code, httplib.OK) + return self.req_d + + def _create_success(self, body): + self.assertIn('CreateResponse', str(type(body))) class TestTokenDeleteProject(TestToken): @@ -55,28 +59,25 @@ class TestTokenDeleteProject(TestToken): self.req_d = project_models.ProjectCreateRequest('vping') fake_pymongo.tokens.insert({"access_token": "12345"}) self.basePath = '/api/v1/projects' - - def test_projectDeleteTokenIvalid(self): self.headers['X-Auth-Token'] = '12345' self.create_d() + + @executor.delete(httplib.FORBIDDEN, message.invalid_token()) + def test_projectDeleteTokenIvalid(self): self.headers['X-Auth-Token'] = '1234' - code, body = self.delete(self.req_d.name) - self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('Invalid Token.', body) + return self.req_d.name + @executor.delete(httplib.UNAUTHORIZED, message.unauthorized()) def test_projectDeleteTokenUnauthorized(self): - self.headers['X-Auth-Token'] = '12345' - self.create_d() self.headers.pop('X-Auth-Token') - code, body = self.delete(self.req_d.name) - self.assertEqual(code, httplib.UNAUTHORIZED) - self.assertIn('No Authentication Header.', body) + return self.req_d.name + @executor.delete(httplib.OK, '_delete_success') def test_projectDeleteTokenSuccess(self): - self.headers['X-Auth-Token'] = '12345' - self.create_d() - code, body = self.delete(self.req_d.name) - self.assertEqual(code, httplib.OK) + return self.req_d.name + + def _delete_success(self, body): + self.assertEqual('', body) class TestTokenUpdateProject(TestToken): @@ -85,34 +86,28 @@ class TestTokenUpdateProject(TestToken): self.req_d = project_models.ProjectCreateRequest('vping') fake_pymongo.tokens.insert({"access_token": "12345"}) self.basePath = '/api/v1/projects' - - def test_projectUpdateTokenIvalid(self): self.headers['X-Auth-Token'] = '12345' self.create_d() - code, body = self.get(self.req_d.name) + + @executor.update(httplib.FORBIDDEN, message.invalid_token()) + def test_projectUpdateTokenIvalid(self): self.headers['X-Auth-Token'] = '1234' req = project_models.ProjectUpdateRequest('newName', 'new description') - code, body = self.update(req, self.req_d.name) - self.assertEqual(code, httplib.FORBIDDEN) - self.assertIn('Invalid Token.', body) + return req, self.req_d.name + @executor.update(httplib.UNAUTHORIZED, message.unauthorized()) def test_projectUpdateTokenUnauthorized(self): - self.headers['X-Auth-Token'] = '12345' - self.create_d() - code, body = self.get(self.req_d.name) self.headers.pop('X-Auth-Token') req = project_models.ProjectUpdateRequest('newName', 'new description') - code, body = self.update(req, self.req_d.name) - self.assertEqual(code, httplib.UNAUTHORIZED) - self.assertIn('No Authentication Header.', body) + return req, self.req_d.name + @executor.update(httplib.OK, '_update_success') def test_projectUpdateTokenSuccess(self): - self.headers['X-Auth-Token'] = '12345' - self.create_d() - code, body = self.get(self.req_d.name) req = project_models.ProjectUpdateRequest('newName', 'new description') - code, body = self.update(req, self.req_d.name) - self.assertEqual(code, httplib.OK) + return req, self.req_d.name + + def _update_success(self, request, body): + self.assertIn(request.name, body) if __name__ == '__main__': unittest.main() diff --git a/utils/test/testapi/opnfv_testapi/tests/unit/test_version.py b/utils/test/testapi/opnfv_testapi/tests/unit/test_version.py index c8f3f5062..fff802ac8 100644 --- a/utils/test/testapi/opnfv_testapi/tests/unit/test_version.py +++ b/utils/test/testapi/opnfv_testapi/tests/unit/test_version.py @@ -6,10 +6,12 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +import httplib import unittest from opnfv_testapi.resources import models -import test_base as base +from opnfv_testapi.tests.unit import executor +from opnfv_testapi.tests.unit import test_base as base class TestVersionBase(base.TestBase): @@ -20,12 +22,15 @@ class TestVersionBase(base.TestBase): class TestVersion(TestVersionBase): + @executor.get(httplib.OK, '_get_success') def test_success(self): - code, body = self.get() - self.assertEqual(200, code) + return None + + def _get_success(self, body): self.assertEqual(len(body.versions), 1) self.assertEqual(body.versions[0].version, 'v1.0') self.assertEqual(body.versions[0].description, 'basics') + if __name__ == '__main__': unittest.main() |