3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
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
11 Utils for functest restapi
19 from oslo_utils import importutils
21 from flask import jsonify
26 LOGGER = logging.getLogger(__name__)
29 def change_to_str_in_dict(obj):
31 Return a dict with key and value both in string if they are in Unicode
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):
42 def itersubclasses(cls, _seen=None):
43 """ Generator over all subclasses of a given class in depth first order """
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()
50 subs = cls.__subclasses__()
51 except TypeError: # fails only when cls is type
52 subs = cls.__subclasses__(cls)
57 for itersub in itersubclasses(sub, _seen):
61 def import_modules_from_package(package):
63 Import modules from package and append into sys.modules
64 :param: package - Full package name. For example: functest.api.resources
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"):
72 new_package = ".".join(root.split(os.sep)).split("....")[1]
73 module_name = "%s.%s" % (new_package, filename[:-3])
75 try_append_module(module_name, sys.modules)
77 LOGGER.exception("unable to import %s", module_name)
80 def try_append_module(name, modules):
81 """ Append the module into specified module system """
83 if name not in modules:
84 modules[name] = importutils.import_module(name)
87 def change_obj_to_dict(obj):
88 """ Transfer the object into dict """
90 for key, value in vars(obj).items():
91 dic.update({key: value})
95 def result_handler(status, data):
96 """ Return the json format of result in dict """
101 return jsonify(result)