Merge "Change the name of flavor and disabled ssh-hostname verification."
[functest.git] / functest / api / common / api_utils.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 Utils for functest restapi
12
13 """
14
15 import collections
16 import logging
17 import os
18 import sys
19 from oslo_utils import importutils
20
21 from flask import jsonify
22 import six
23
24 import functest
25
26 LOGGER = logging.getLogger(__name__)
27
28
29 def change_to_str_in_dict(obj):
30     """
31     Return a dict with key and value both in string if they are in Unicode
32     """
33     if isinstance(obj, collections.Mapping):
34         return {str(k): change_to_str_in_dict(v) for k, v in obj.items()}
35     elif isinstance(obj, list):
36         return [change_to_str_in_dict(ele) for ele in obj]
37     elif isinstance(obj, six.text_type):
38         return str(obj)
39     return obj
40
41
42 def itersubclasses(cls, _seen=None):
43     """ Generator over all subclasses of a given class in depth first order """
44
45     if not isinstance(cls, type):
46         raise TypeError("itersubclasses must be called with "
47                         "new-style classes, not %.100r" % cls)
48     _seen = _seen or set()
49     try:
50         subs = cls.__subclasses__()
51     except TypeError:   # fails only when cls is type
52         subs = cls.__subclasses__(cls)
53     for sub in subs:
54         if sub not in _seen:
55             _seen.add(sub)
56             yield sub
57             for itersub in itersubclasses(sub, _seen):
58                 yield itersub
59
60
61 def import_modules_from_package(package):
62     """
63     Import modules from package and append into sys.modules
64     :param: package - Full package name. For example: functest.api.resources
65     """
66     path = [os.path.dirname(functest.__file__), ".."] + package.split(".")
67     path = os.path.join(*path)
68     for root, _, files in os.walk(path):
69         for filename in files:
70             if filename.startswith("__") or not filename.endswith(".py"):
71                 continue
72             new_package = ".".join(root.split(os.sep)).split("....")[1]
73             module_name = "%s.%s" % (new_package, filename[:-3])
74             try:
75                 try_append_module(module_name, sys.modules)
76             except ImportError:
77                 LOGGER.exception("unable to import %s", module_name)
78
79
80 def try_append_module(name, modules):
81     """ Append the module into specified module system """
82
83     if name not in modules:
84         modules[name] = importutils.import_module(name)
85
86
87 def change_obj_to_dict(obj):
88     """  Transfer the object into dict """
89     dic = {}
90     for key, value in vars(obj).items():
91         dic.update({key: value})
92     return dic
93
94
95 def result_handler(status, data):
96     """ Return the json format of result in dict """
97     result = {
98         'status': status,
99         'result': data
100     }
101     return jsonify(result)