Merge "Move source_credentials() into run_tests.py"
[functest.git] / functest / utils / config.py
1 #!/usr/bin/env python
2
3 # pylint: disable=missing-docstring
4
5 import os
6 import pkg_resources
7 import yaml
8
9 import six
10
11
12 class Config(object):
13     def __init__(self):
14         try:
15             # pylint: disable=bad-continuation
16             with open(pkg_resources.resource_filename(
17                     'functest', 'ci/config_functest.yaml')) as yfile:
18                 self.functest_yaml = yaml.safe_load(yfile)
19         except Exception as error:
20             raise Exception('Parse config failed: {}'.format(str(error)))
21
22     @staticmethod
23     def _merge_dicts(dict1, dict2):
24         for k in set(dict1.keys()).union(dict2.keys()):
25             if k in dict1 and k in dict2:
26                 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
27                     yield (k, dict(Config._merge_dicts(dict1[k], dict2[k])))
28                 else:
29                     yield (k, dict2[k])
30             elif k in dict1:
31                 yield (k, dict1[k])
32             else:
33                 yield (k, dict2[k])
34
35     def patch_file(self, patch_file_path):
36         with open(patch_file_path) as yfile:
37             patch_file = yaml.safe_load(yfile)
38
39         for key in patch_file:
40             if key in os.environ.get('DEPLOY_SCENARIO', ""):
41                 self.functest_yaml = dict(Config._merge_dicts(
42                     self.functest_yaml, patch_file[key]))
43
44     def _parse(self, attr_now, left_parametes):
45         for param_n, param_v in six.iteritems(left_parametes):
46             attr_further = self._get_attr_further(attr_now, param_n)
47             if attr_further:
48                 self.__setattr__(attr_further, param_v)
49             if isinstance(param_v, dict):
50                 self._parse(attr_further, param_v)
51
52     @staticmethod
53     def _get_attr_further(attr_now, next):  # pylint: disable=redefined-builtin
54         return attr_now if next == 'general' else (
55             '{}_{}'.format(attr_now, next) if attr_now else next)
56
57     def fill(self):
58         try:
59             self._parse(None, self.functest_yaml)
60         except Exception as error:
61             raise Exception('Parse config failed: {}'.format(str(error)))
62
63
64 CONF = Config()
65 CONF.patch_file(pkg_resources.resource_filename(
66     'functest', 'ci/config_patch.yaml'))
67 if os.getenv("POD_ARCH", None) and os.getenv("POD_ARCH", None) in ['aarch64']:
68     CONF.patch_file(pkg_resources.resource_filename(
69         'functest', 'ci/config_aarch64_patch.yaml'))
70 CONF.fill()