Merge "Add task-args(from yaml file) candidates in /api/v2/yardstick/testcases API"
[yardstick.git] / api / resources / v2 / testcases.py
1 ##############################################################################
2 # Copyright (c) 2017 Huawei Technologies Co.,Ltd.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 import logging
10 import errno
11 import os
12
13 import jinja2schema
14
15 from api import ApiResource
16 from yardstick.common.utils import result_handler
17 from yardstick.common import constants as consts
18 from yardstick.benchmark.core import Param
19 from yardstick.benchmark.core.testcase import Testcase
20
21 LOG = logging.getLogger(__name__)
22 LOG.setLevel(logging.DEBUG)
23
24
25 class V2Testcases(ApiResource):
26
27     def get(self):
28         param = Param({})
29         testcase_list = Testcase().list_all(param)
30         return result_handler(consts.API_SUCCESS, {'testcases': testcase_list})
31
32     def post(self):
33         return self._dispatch_post()
34
35     def upload_case(self, args):
36         try:
37             upload_file = args['file']
38         except KeyError:
39             return result_handler(consts.API_ERROR, 'file must be provided')
40
41         case_name = os.path.join(consts.TESTCASE_DIR, upload_file.filename)
42
43         LOG.info('save case file')
44         upload_file.save(case_name)
45
46         return result_handler(consts.API_SUCCESS, {'testcase': upload_file.filename})
47
48
49 class V2Testcase(ApiResource):
50
51     def get(self, case_name):
52         case_path = os.path.join(consts.TESTCASE_DIR, '{}.yaml'.format(case_name))
53
54         try:
55             with open(case_path) as f:
56                 data = f.read()
57         except IOError as e:
58             if e.errno == errno.ENOENT:
59                 return result_handler(consts.API_ERROR, 'case does not exist')
60
61         options = {k: {'description': '', 'type': v.__class__.__name__}
62                    for k, v in jinja2schema.infer(data).items()}
63
64         return result_handler(consts.API_SUCCESS, {'testcase': data, 'args': options})
65
66     def delete(self, case_name):
67         case_path = os.path.join(consts.TESTCASE_DIR, '{}.yaml'.format(case_name))
68
69         try:
70             os.remove(case_path)
71         except IOError as e:
72             if e.errno == errno.ENOENT:
73                 return result_handler(consts.API_ERROR, 'case does not exist')
74
75         return result_handler(consts.API_SUCCESS, {'testcase': case_name})