Merge "Read env vars instead of using CONST in 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 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         try:
119             cmd = "run_tests -t {}".format(case_name)
120             runner = ft_utils.execute_command(cmd)
121         except Exception:  # pylint: disable=broad-except
122             result = 'FAIL'
123             LOGGER.exception("Running test case %s failed!", case_name)
124         if runner == os.EX_OK:
125             result = 'PASS'
126         else:
127             result = 'FAIL'
128
129         env_info = {
130             'installer': os.environ.get('INSTALLER_TYPE', None),
131             'scenario': os.environ.get('DEPLOY_SCENARIO', None),
132             'build_tag': os.environ.get('BUILD_TAG', None),
133             'ci_loop': os.environ.get('CI_LOOP', 'daily')
134         }
135         result = {
136             'task_id': args.get('task_id'),
137             'testcase': case_name,
138             'env_info': env_info,
139             'result': result
140         }
141
142         return {'result': result}
143
144     def _update_logging_ini(self, task_id):  # pylint: disable=no-self-use
145         """ Update the log file for each task"""
146         config = ConfigParser.RawConfigParser()
147         config.read(
148             pkg_resources.resource_filename('functest', 'ci/logging.ini'))
149         log_path = os.path.join(getattr(CONST, 'dir_results'),
150                                 '{}.log'.format(task_id))
151         config.set('handler_file', 'args', '("{}",)'.format(log_path))
152
153         with open(
154             pkg_resources.resource_filename(
155                 'functest', 'ci/logging.ini'), 'wb') as configfile:
156             config.write(configfile)