class INIReader(object): """ConfigParser wrapper able to cast value when reading INI options.""" # Helper casters cast_boolean = casts.Boolean() cast_dict = casts.Dict() cast_list = casts.List() cast_logging_level = casts.LoggingLevel() cast_tuple = casts.Tuple() cast_webdriver_desired_capabilities = casts.WebdriverDesiredCapabilities() def __init__(self, path): self.config_parser = ConfigParser() with open(path) as handler: self.config_parser.readfp(handler) if sys.version_info[0] < 3: # ConfigParser.readfp is deprecated on Python3, read_file # replaces it self.config_parser.readfp(handler) else: self.config_parser.read_file(handler) def get(self, section, option, default=None, cast=None): """Read an option from a section of a INI file. The default value will return if the look up option is not available. The value will be cast using a callable if specified otherwise a string will be returned. :param section: Section to look for. :param option: Option to look for. :param default: The value that should be used if the option is not defined. :param cast: If provided the value will be cast using the cast provided. """ try: value = self.config_parser.get(section, option) if cast is not None: if cast is bool: value = self.cast_boolean(value) elif cast is dict: value = self.cast_dict(value) elif cast is list: value = self.cast_list(value) elif cast is tuple: value = self.cast_tuple(value) else: value = cast(value) except (NoSectionError, NoOptionError): value = default return value def has_section(self, section): """Check if section is available.""" return self.config_parser.has_section(section)
def setUp(self): self.cast_boolean = casts.Boolean()
def cast_boolean(self): """An instance of casts.Boolean""" return casts.Boolean()