bugfix: E722 do not use bare except
[releng.git] / utils / test / testapi / opnfv_testapi / common / config.py
index 84a1273..f888b07 100644 (file)
@@ -8,91 +8,56 @@
 # feng.xiaowei@zte.com.cn remove prepare_put_request            5-30-2016
 ##############################################################################
 import ConfigParser
+import argparse
+import os
+import sys
 
 
-class ParseError(Exception):
-    """
-    Custom exception class for config file
-    """
-
-    def __init__(self, message):
-        self.msg = message
-
-    def __str__(self):
-        return 'error parsing config file : %s' % self.msg
-
-
-class APIConfig:
-    """
-    The purpose of this class is to load values correctly from the config file.
-    Each key is declared as an attribute in __init__() and linked in parse()
-    """
+class Config(object):
 
     def __init__(self):
-        self._default_config_location = "/etc/opnfv_testapi/config.ini"
-        self.mongo_url = None
-        self.mongo_dbname = None
-        self.api_port = None
-        self.api_debug_on = None
-        self.api_authenticate_on = None
-        self._parser = None
-        self.swagger_base_url = None
+        self.config_file = '/etc/opnfv_testapi/config.ini'
+        self._set_config_file()
+        self._parse()
+        self._parse_per_page()
 
-    def _get_parameter(self, section, param):
-        try:
-            return self._parser.get(section, param)
-        except ConfigParser.NoOptionError:
-            raise ParseError("[%s.%s] parameter not found" % (section, param))
-
-    def _get_int_parameter(self, section, param):
-        try:
-            return int(self._get_parameter(section, param))
-        except ValueError:
-            raise ParseError("[%s.%s] not an int" % (section, param))
+    def _parse(self):
+        if not os.path.exists(self.config_file):
+            raise Exception("%s not found" % self.config_file)
 
-    def _get_bool_parameter(self, section, param):
-        result = self._get_parameter(section, param)
-        if str(result).lower() == 'true':
-            return True
-        if str(result).lower() == 'false':
-            return False
+        config = ConfigParser.RawConfigParser()
+        config.read(self.config_file)
+        self._parse_section(config)
 
-        raise ParseError(
-            "[%s.%s : %s] not a boolean" % (section, param, result))
+    def _parse_section(self, config):
+        [self._parse_item(config, section) for section in (config.sections())]
 
-    @staticmethod
-    def parse(config_location=None):
-        obj = APIConfig()
+    def _parse_item(self, config, section):
+        [setattr(self, '{}_{}'.format(section, k), self._parse_value(v))
+         for k, v in config.items(section)]
 
-        if config_location is None:
-            config_location = obj._default_config_location
+    def _parse_per_page(self):
+        if not hasattr(self, 'api_results_per_page'):
+            self.api_results_per_page = 20
 
-        obj._parser = ConfigParser.SafeConfigParser()
-        obj._parser.read(config_location)
-        if not obj._parser:
-            raise ParseError("%s not found" % config_location)
-
-        # Linking attributes to keys from file with their sections
-        obj.mongo_url = obj._get_parameter("mongo", "url")
-        obj.mongo_dbname = obj._get_parameter("mongo", "dbname")
-
-        obj.api_port = obj._get_int_parameter("api", "port")
-        obj.api_debug_on = obj._get_bool_parameter("api", "debug")
-        obj.api_authenticate_on = obj._get_bool_parameter("api",
-                                                          "authenticate")
-
-        obj.swagger_base_url = obj._get_parameter("swagger", "base_url")
-
-        return obj
-
-    def __str__(self):
-        return "mongo_url = %s \n" \
-               "mongo_dbname = %s \n" \
-               "api_port = %s \n" \
-               "api_debug_on = %s \n" \
-               "swagger_base_url = %s \n" % (self.mongo_url,
-                                             self.mongo_dbname,
-                                             self.api_port,
-                                             self.api_debug_on,
-                                             self.api_authenticate_on,
-                                             self.swagger_base_url)
+    @staticmethod
+    def _parse_value(value):
+        try:
+            value = int(value)
+        except Exception:
+            if str(value).lower() == 'true':
+                value = True
+            elif str(value).lower() == 'false':
+                value = False
+        return value
+
+    def _set_config_file(self):
+        parser = argparse.ArgumentParser()
+        parser.add_argument("-c", "--config-file", dest='config_file',
+                            help="Config file location", metavar="FILE")
+        args, _ = parser.parse_known_args(sys.argv)
+        if hasattr(args, 'config_file') and args.config_file:
+            self.config_file = args.config_file
+
+
+CONF = Config()