Merge changes from topic 'fuel-armband-deploy-sync'
[releng.git] / utils / test / testapi / opnfv_testapi / common / config.py
1 ##############################################################################
2 # Copyright (c) 2015 Orange
3 # guyrodrigue.koffi@orange.com / koffirodrigue@gmail.com
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 # feng.xiaowei@zte.com.cn remove prepare_put_request            5-30-2016
9 ##############################################################################
10 import ConfigParser
11 import argparse
12 import os
13 import sys
14
15
16 class Config(object):
17
18     def __init__(self):
19         self.config_file = None
20         self._set_config_file()
21         self._parse()
22         self._parse_per_page()
23         self.static_path = os.path.join(
24             os.path.dirname(os.path.normpath(__file__)),
25             os.pardir,
26             'static')
27
28     def _parse(self):
29         if not os.path.exists(self.config_file):
30             raise Exception("%s not found" % self.config_file)
31
32         config = ConfigParser.RawConfigParser()
33         config.read(self.config_file)
34         self._parse_section(config)
35
36     def _parse_section(self, config):
37         [self._parse_item(config, section) for section in (config.sections())]
38
39     def _parse_item(self, config, section):
40         [setattr(self, '{}_{}'.format(section, k), self._parse_value(v))
41          for k, v in config.items(section)]
42
43     def _parse_per_page(self):
44         if not hasattr(self, 'api_results_per_page'):
45             self.api_results_per_page = 20
46
47     @staticmethod
48     def _parse_value(value):
49         try:
50             value = int(value)
51         except:
52             if str(value).lower() == 'true':
53                 value = True
54             elif str(value).lower() == 'false':
55                 value = False
56         return value
57
58     def _set_config_file(self):
59         if not self._set_sys_config_file():
60             self._set_default_config_file()
61
62     def _set_sys_config_file(self):
63         parser = argparse.ArgumentParser()
64         parser.add_argument("-c", "--config-file", dest='config_file',
65                             help="Config file location", metavar="FILE")
66         args, _ = parser.parse_known_args(sys.argv)
67         try:
68             self.config_file = args.config_file
69         finally:
70             return self.config_file is not None
71
72     def _set_default_config_file(self):
73         is_venv = os.getenv('VIRTUAL_ENV')
74         self.config_file = os.path.join('/' if not is_venv else is_venv,
75                                         'etc/opnfv_testapi/config.ini')
76
77
78 CONF = Config()