Remove white space when listing testcases
[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 re
17 import pkg_resources
18 import socket
19 import uuid
20
21 import ConfigParser
22 from flask import jsonify
23 from flasgger.utils import swag_from
24
25 from functest.api.base import ApiResource
26 from functest.api.common import api_utils, thread
27 from functest.cli.commands.cli_testcase import Testcase
28 from functest.api.database.v1.handlers import TasksHandler
29 from functest.utils.constants import CONST
30 import functest.utils.functest_utils as ft_utils
31
32 LOGGER = logging.getLogger(__name__)
33
34 ADDRESS = socket.gethostbyname(socket.gethostname())
35 ENDPOINT_TESTCASES = ('http://{}:5000/api/v1/functest/testcases'
36                       .format(ADDRESS))
37
38
39 class V1Testcases(ApiResource):
40     """ V1Testcases Resource class"""
41
42     @swag_from(pkg_resources.resource_filename(
43         'functest', 'api/swagger/testcases.yaml'))
44     def get(self):  # pylint: disable=no-self-use
45         """ GET all testcases """
46         testcases_list = Testcase().list()
47         result = {'testcases': re.split(' |\n ', testcases_list)[1:]}
48         return jsonify(result)
49
50
51 class V1Testcase(ApiResource):
52     """ V1Testcase Resource class"""
53
54     @swag_from(
55         pkg_resources.resource_filename('functest',
56                                         'api/swagger/testcase.yaml'),
57         endpoint='{0}/<testcase_name>'.format(ENDPOINT_TESTCASES))
58     def get(self, testcase_name):  # pylint: disable=no-self-use
59         """ GET the info of one testcase"""
60         testcase = Testcase().show(testcase_name)
61         if not testcase:
62             return api_utils.result_handler(
63                 status=1,
64                 data="The test case '%s' does not exist or is not supported"
65                 % testcase_name)
66
67         testcase_info = api_utils.change_obj_to_dict(testcase)
68         dependency_dict = api_utils.change_obj_to_dict(
69             testcase_info.get('dependency'))
70         testcase_info.pop('name')
71         testcase_info.pop('dependency')
72         result = {'testcase': testcase_name}
73         result.update(testcase_info)
74         result.update({'dependency': dependency_dict})
75         return jsonify(result)
76
77     @swag_from(
78         pkg_resources.resource_filename('functest',
79                                         'api/swagger/testcase_run.yaml'),
80         endpoint='{0}/action'.format(ENDPOINT_TESTCASES))
81     def post(self):
82         """ Used to handle post request """
83         return self._dispatch_post()
84
85     def run_test_case(self, args):
86         """ Run a testcase """
87         try:
88             case_name = args['testcase']
89         except KeyError:
90             return api_utils.result_handler(
91                 status=1, data='testcase name must be provided')
92
93         testcase = Testcase().show(case_name)
94         if not testcase:
95             return api_utils.result_handler(
96                 status=1,
97                 data="The test case '%s' does not exist or is not supported"
98                 % case_name)
99
100         task_id = str(uuid.uuid4())
101
102         task_args = {'testcase': case_name, 'task_id': task_id}
103
104         task_args.update(args.get('opts', {}))
105
106         task_thread = thread.TaskThread(self._run, task_args, TasksHandler())
107         task_thread.start()
108
109         result = {'testcase': case_name, 'task_id': task_id}
110         return jsonify({'result': result})
111
112     def _run(self, args):  # pylint: disable=no-self-use
113         """ The built_in function to run a test case """
114
115         case_name = args.get('testcase')
116         self._update_logging_ini(args.get('task_id'))
117
118         if not os.path.isfile(CONST.__getattribute__('env_active')):
119             raise Exception("Functest environment is not ready.")
120         else:
121             try:
122                 cmd = "run_tests -t {}".format(case_name)
123                 runner = ft_utils.execute_command(cmd)
124             except Exception:  # pylint: disable=broad-except
125                 result = 'FAIL'
126                 LOGGER.exception("Running test case %s failed!", case_name)
127             if runner == os.EX_OK:
128                 result = 'PASS'
129             else:
130                 result = 'FAIL'
131
132             env_info = {
133                 'installer': CONST.__getattribute__('INSTALLER_TYPE'),
134                 'scenario': CONST.__getattribute__('DEPLOY_SCENARIO'),
135                 'build_tag': CONST.__getattribute__('BUILD_TAG'),
136                 'ci_loop': CONST.__getattribute__('CI_LOOP')
137             }
138             result = {
139                 'task_id': args.get('task_id'),
140                 'testcase': case_name,
141                 'env_info': env_info,
142                 'result': result
143             }
144
145             return {'result': result}
146
147     def _update_logging_ini(self, task_id):  # pylint: disable=no-self-use
148         """ Update the log file for each task"""
149         config = ConfigParser.RawConfigParser()
150         config.read(
151             pkg_resources.resource_filename('functest', 'ci/logging.ini'))
152         log_path = os.path.join(CONST.__getattribute__('dir_results'),
153                                 '{}.log'.format(task_id))
154         config.set('handler_file', 'args', '("{}",)'.format(log_path))
155
156         with open(
157             pkg_resources.resource_filename(
158                 'functest', 'ci/logging.ini'), 'wb') as configfile:
159             config.write(configfile)