Merge "bugfix: leverage data_files to stop hacking setup.py"
[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 = '/etc/opnfv_testapi/config.ini'
20         self._set_config_file()
21         self._parse()
22         self._parse_per_page()
23
24     def _parse(self):
25         if not os.path.exists(self.config_file):
26             raise Exception("%s not found" % self.config_file)
27
28         config = ConfigParser.RawConfigParser()
29         config.read(self.config_file)
30         self._parse_section(config)
31
32     def _parse_section(self, config):
33         [self._parse_item(config, section) for section in (config.sections())]
34
35     def _parse_item(self, config, section):
36         [setattr(self, '{}_{}'.format(section, k), self._parse_value(v))
37          for k, v in config.items(section)]
38
39     def _parse_per_page(self):
40         if not hasattr(self, 'api_results_per_page'):
41             self.api_results_per_page = 20
42
43     @staticmethod
44     def _parse_value(value):
45         try:
46             value = int(value)
47         except:
48             if str(value).lower() == 'true':
49                 value = True
50             elif str(value).lower() == 'false':
51                 value = False
52         return value
53
54     def _set_config_file(self):
55         parser = argparse.ArgumentParser()
56         parser.add_argument("-c", "--config-file", dest='config_file',
57                             help="Config file location", metavar="FILE")
58         args, _ = parser.parse_known_args(sys.argv)
59         if hasattr(args, 'config_file') and args.config_file:
60             self.config_file = args.config_file
61
62
63 CONF = Config()