3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
11 Resources to handle testcase related requests
21 from flask import jsonify
22 from flasgger.utils import swag_from
24 from functest.api.base import ApiResource
25 from functest.api.common import api_utils, thread
26 from functest.cli.commands.cli_testcase import Testcase
27 from functest.api.database.v1.handlers import TasksHandler
28 from functest.utils.constants import CONST
29 import functest.utils.functest_utils as ft_utils
31 LOGGER = logging.getLogger(__name__)
33 ADDRESS = socket.gethostbyname(socket.gethostname())
34 ENDPOINT_TESTCASES = ('http://{}:5000/api/v1/functest/testcases'
38 class V1Testcases(ApiResource):
39 """ V1Testcases Resource class"""
41 @swag_from(pkg_resources.resource_filename(
42 'functest', 'api/swagger/testcases.yaml'))
43 def get(self): # pylint: disable=no-self-use
44 """ GET all testcases """
45 testcases_list = Testcase().list()
46 result = {'testcases': testcases_list.split('\n')[:-1]}
47 return jsonify(result)
50 class V1Testcase(ApiResource):
51 """ V1Testcase Resource class"""
54 pkg_resources.resource_filename('functest',
55 'api/swagger/testcase.yaml'),
56 endpoint='{0}/<testcase_name>'.format(ENDPOINT_TESTCASES))
57 def get(self, testcase_name): # pylint: disable=no-self-use
58 """ GET the info of one testcase"""
59 testcase = Testcase().show(testcase_name)
61 return api_utils.result_handler(
63 data="The test case '%s' does not exist or is not supported"
66 testcase_info = api_utils.change_obj_to_dict(testcase)
67 dependency_dict = api_utils.change_obj_to_dict(
68 testcase_info.get('dependency'))
69 testcase_info.pop('name')
70 testcase_info.pop('dependency')
71 result = {'testcase': testcase_name}
72 result.update(testcase_info)
73 result.update({'dependency': dependency_dict})
74 return jsonify(result)
77 pkg_resources.resource_filename('functest',
78 'api/swagger/testcase_run.yaml'),
79 endpoint='{0}/action'.format(ENDPOINT_TESTCASES))
81 """ Used to handle post request """
82 return self._dispatch_post()
84 def run_test_case(self, args):
85 """ Run a testcase """
87 case_name = args['testcase']
89 return api_utils.result_handler(
90 status=1, data='testcase name must be provided')
92 testcase = Testcase().show(case_name)
94 return api_utils.result_handler(
96 data="The test case '%s' does not exist or is not supported"
99 task_id = str(uuid.uuid4())
101 task_args = {'testcase': case_name, 'task_id': task_id}
103 task_args.update(args.get('opts', {}))
105 task_thread = thread.TaskThread(self._run, task_args, TasksHandler())
108 result = {'testcase': case_name, 'task_id': task_id}
109 return jsonify({'result': result})
111 def _run(self, args): # pylint: disable=no-self-use
112 """ The built_in function to run a test case """
114 case_name = args.get('testcase')
115 self._update_logging_ini(args.get('task_id'))
117 if not os.path.isfile(CONST.__getattribute__('env_active')):
118 raise Exception("Functest environment is not ready.")
121 cmd = "run_tests -t {}".format(case_name)
122 runner = ft_utils.execute_command(cmd)
123 except Exception: # pylint: disable=broad-except
125 LOGGER.exception("Running test case %s failed!", case_name)
126 if runner == os.EX_OK:
132 'installer': CONST.__getattribute__('INSTALLER_TYPE'),
133 'scenario': CONST.__getattribute__('DEPLOY_SCENARIO'),
134 'build_tag': CONST.__getattribute__('BUILD_TAG'),
135 'ci_loop': CONST.__getattribute__('CI_LOOP')
138 'task_id': args.get('task_id'),
139 'testcase': case_name,
140 'env_info': env_info,
144 return {'result': result}
146 def _update_logging_ini(self, task_id): # pylint: disable=no-self-use
147 """ Update the log file for each task"""
148 config = ConfigParser.RawConfigParser()
150 pkg_resources.resource_filename('functest', 'ci/logging.ini'))
151 log_path = os.path.join(CONST.__getattribute__('dir_results'),
152 '{}.log'.format(task_id))
153 config.set('handler_file', 'args', '("{}",)'.format(log_path))
156 pkg_resources.resource_filename(
157 'functest', 'ci/logging.ini'), 'wb') as configfile:
158 config.write(configfile)