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