Merge "Activate SFC testcases in CI (alpine)"
[functest-xtesting.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 abort, 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             abort(404, "The test case '%s' does not exist or is not supported"
50                   % testcase_name)
51         testcase_info = api_utils.change_obj_to_dict(testcase)
52         dependency_dict = api_utils.change_obj_to_dict(
53             testcase_info.get('dependency'))
54         testcase_info.pop('name')
55         testcase_info.pop('dependency')
56         result = {'testcase': testcase_name}
57         result.update(testcase_info)
58         result.update({'dependency': dependency_dict})
59         return jsonify(result)
60
61     def post(self):
62         """ Used to handle post request """
63         return self._dispatch_post()
64
65     def run_test_case(self, args):
66         """ Run a testcase """
67         try:
68             case_name = args['testcase']
69         except KeyError:
70             return api_utils.result_handler(
71                 status=1, data='testcase name must be provided')
72
73         task_id = str(uuid.uuid4())
74
75         task_args = {'testcase': case_name, 'task_id': task_id}
76
77         task_args.update(args.get('opts', {}))
78
79         task_thread = thread.TaskThread(self._run, task_args, TasksHandler())
80         task_thread.start()
81
82         results = {'testcase': case_name, 'task_id': task_id}
83         return jsonify(results)
84
85     def _run(self, args):  # pylint: disable=no-self-use
86         """ The built_in function to run a test case """
87
88         case_name = args.get('testcase')
89         self._update_logging_ini(args.get('task_id'))
90
91         if not os.path.isfile(CONST.__getattribute__('env_active')):
92             raise Exception("Functest environment is not ready.")
93         else:
94             try:
95                 cmd = "run_tests -t {}".format(case_name)
96                 runner = ft_utils.execute_command(cmd)
97             except Exception:  # pylint: disable=broad-except
98                 result = 'FAIL'
99                 LOGGER.exception("Running test case %s failed!", case_name)
100             if runner == os.EX_OK:
101                 result = 'PASS'
102             else:
103                 result = 'FAIL'
104
105             env_info = {
106                 'installer': CONST.__getattribute__('INSTALLER_TYPE'),
107                 'scenario': CONST.__getattribute__('DEPLOY_SCENARIO'),
108                 'build_tag': CONST.__getattribute__('BUILD_TAG'),
109                 'ci_loop': CONST.__getattribute__('CI_LOOP')
110             }
111             result = {
112                 'task_id': args.get('task_id'),
113                 'case_name': case_name,
114                 'env_info': env_info,
115                 'result': result
116             }
117
118             return {'result': result}
119
120     def _update_logging_ini(self, task_id):  # pylint: disable=no-self-use
121         """ Update the log file for each task"""
122         config = ConfigParser.RawConfigParser()
123         config.read(
124             pkg_resources.resource_filename('functest', 'ci/logging.ini'))
125         log_path = os.path.join(CONST.__getattribute__('dir_results'),
126                                 '{}.log'.format(task_id))
127         config.set('handler_file', 'args', '("{}",)'.format(log_path))
128
129         with open(
130             pkg_resources.resource_filename(
131                 'functest', 'ci/logging.ini'), 'wb') as configfile:
132             config.write(configfile)