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