Add swagger support for Rest API
[functest.git] / functest / api / resources / v1 / testcases.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
4 #
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
9
10 """
11 Resources to handle testcase related requests
12 """
13
14 import logging
15 import os
16 import pkg_resources
17 import socket
18 import uuid
19
20 import ConfigParser
21 from flask import jsonify
22 from flasgger.utils import swag_from
23
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
30
31 LOGGER = logging.getLogger(__name__)
32
33 ADDRESS = socket.gethostbyname(socket.gethostname())
34 ENDPOINT_TESTCASES = ('http://{}:5000/api/v1/functest/testcases'
35                       .format(ADDRESS))
36
37
38 class V1Testcases(ApiResource):
39     """ V1Testcases Resource class"""
40
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)
48
49
50 class V1Testcase(ApiResource):
51     """ V1Testcase Resource class"""
52
53     @swag_from(
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)
60         if not testcase:
61             return api_utils.result_handler(
62                 status=1,
63                 data="The test case '%s' does not exist or is not supported"
64                 % testcase_name)
65
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)
75
76     @swag_from(
77         pkg_resources.resource_filename('functest',
78                                         'api/swagger/testcase_run.yaml'),
79         endpoint='{0}/action'.format(ENDPOINT_TESTCASES))
80     def post(self):
81         """ Used to handle post request """
82         return self._dispatch_post()
83
84     def run_test_case(self, args):
85         """ Run a testcase """
86         try:
87             case_name = args['testcase']
88         except KeyError:
89             return api_utils.result_handler(
90                 status=1, data='testcase name must be provided')
91
92         testcase = Testcase().show(case_name)
93         if not testcase:
94             return api_utils.result_handler(
95                 status=1,
96                 data="The test case '%s' does not exist or is not supported"
97                 % case_name)
98
99         task_id = str(uuid.uuid4())
100
101         task_args = {'testcase': case_name, 'task_id': task_id}
102
103         task_args.update(args.get('opts', {}))
104
105         task_thread = thread.TaskThread(self._run, task_args, TasksHandler())
106         task_thread.start()
107
108         result = {'testcase': case_name, 'task_id': task_id}
109         return jsonify({'result': result})
110
111     def _run(self, args):  # pylint: disable=no-self-use
112         """ The built_in function to run a test case """
113
114         case_name = args.get('testcase')
115         self._update_logging_ini(args.get('task_id'))
116
117         if not os.path.isfile(CONST.__getattribute__('env_active')):
118             raise Exception("Functest environment is not ready.")
119         else:
120             try:
121                 cmd = "run_tests -t {}".format(case_name)
122                 runner = ft_utils.execute_command(cmd)
123             except Exception:  # pylint: disable=broad-except
124                 result = 'FAIL'
125                 LOGGER.exception("Running test case %s failed!", case_name)
126             if runner == os.EX_OK:
127                 result = 'PASS'
128             else:
129                 result = 'FAIL'
130
131             env_info = {
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')
136             }
137             result = {
138                 'task_id': args.get('task_id'),
139                 'testcase': case_name,
140                 'env_info': env_info,
141                 'result': result
142             }
143
144             return {'result': result}
145
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()
149         config.read(
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))
154
155         with open(
156             pkg_resources.resource_filename(
157                 'functest', 'ci/logging.ini'), 'wb') as configfile:
158             config.write(configfile)