Merge "Create API to get test case result"
[yardstick.git] / api / utils / common.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
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 collections
10 import logging
11 import json
12
13 from api.utils.daemonthread import DaemonThread
14 from yardstick.cmd.cli import YardstickCLI
15
16 logger = logging.getLogger(__name__)
17
18
19 def translate_to_str(object):
20     if isinstance(object, collections.Mapping):
21         return {str(k): translate_to_str(v) for k, v in object.items()}
22     elif isinstance(object, list):
23         return [translate_to_str(ele) for ele in object]
24     elif isinstance(object, unicode):
25         return str(object)
26     return object
27
28
29 def get_command_list(command_list, opts, args):
30
31     command_list.append(args)
32
33     command_list.extend(('--{}'.format(k) for k in opts if 'task-args' != k))
34
35     task_args = opts.get('task-args', '')
36     if task_args:
37         command_list.extend(['--task-args', task_args])
38
39     return command_list
40
41
42 def exec_command_task(command_list, task_id):   # pragma: no cover
43     daemonthread = DaemonThread(YardstickCLI().api, (command_list, task_id))
44     daemonthread.start()
45
46
47 def error_handler(message):
48     logger.debug(message)
49     result = {
50         'status': 'error',
51         'message': message
52     }
53     return json.dumps(result)
54
55
56 def result_handler(status, data):
57     result = {
58         'status': status,
59         'result': data
60     }
61     return json.dumps(result)
62
63
64 class Url(object):
65
66     def __init__(self, url, resource, endpoint):
67         super(Url, self).__init__()
68         self.url = url
69         self.resource = resource
70         self.endpoint = endpoint