# Path: wtframework/wtf/config.py
# class ConfigReader:
# 
#     '''
#     Config Reader provides a way of reading configuration settings. 
#     '''
# 
#     ENV_PREFIX = "WTF_"
#     # NOTE: these vars are defined on __init__.py to avoid loading ConfigReader
#     # when runtests.py is running.
#     CONFIG_LOCATION = constants.WTF_CONFIG_LOCATION
#     DEFAULT_CONFIG_FILE = constants.WTF_DEFAULT_CONFIG_FILE
#     CONFIG_EXT = constants.WTF_CONFIG_EXT
#     ENV_VARS = constants.WTF_ENV_VARS
# 
#     _dataMaps = None  # instance variable to store config data loaded.
#     _singleton_instance = None  # class variable to track singleton.
# 
#     def __init__(self, _env_var_=None):
#         """
#         constructor
#         """
#         self._dataMaps = []
# 
#         # load default yaml file if this is not a unit test.
#         try:
#             if _env_var_ is not None:
#                 # We pass in a custom env var for unit testing.
#                 configs = re.split(",|;", _env_var_)
#                 for config in reversed(configs):
#                     self.__load_config_file(config)
#             elif not ConfigReader.ENV_VARS in os.environ:
#                 _wtflog.warning(u("Config file not specified. Using:{0}")\
#                                 .format(os.path.join(ConfigReader.CONFIG_LOCATION,
#                                                      ConfigReader.DEFAULT_CONFIG_FILE + ConfigReader.CONFIG_EXT)))
#                 self.__load_config_file(ConfigReader.DEFAULT_CONFIG_FILE)
#             else:
#                 # Read and load in all configs specified in reverse order
#                 configs = re.split(
#                     ",|;", str(os.environ[ConfigReader.ENV_VARS]))
#                 for config in reversed(configs):
#                     self.__load_config_file(config)
# 
#         except Exception as e:
#             # Error loading config file.
#             _wtflog.error(
#                 u("An error occurred while loading config file: %s"), e)
#             raise e
# 
#     class __NoDefaultSpecified__(object):
# 
#         "No default specified to config reader."
#         pass
# 
#     def get(self, key, default_value=__NoDefaultSpecified__):
#         '''
#         Gets the value from the yaml config based on the key.
# 
#         No type casting is performed, any type casting should be 
#         performed by the caller.
# 
#         Args:
#             key (str) - Config setting key.
# 
#         Kwargs:
#             default_value - Default value to return if config is not specified.
# 
#         Returns:
#             Returns value stored in config file.
# 
#         '''
#         # First attempt to get the var from OS enviornment.
#         os_env_string = ConfigReader.ENV_PREFIX + key
#         os_env_string = os_env_string.replace(".", "_")
#         if type(os.getenv(os_env_string)) != NoneType:
#             return os.getenv(os_env_string)
# 
#         # Otherwise search through config files.
#         for data_map in self._dataMaps:
#             try:
#                 if "." in key:
#                     # this is a multi levl string
#                     namespaces = key.split(".")
#                     temp_var = data_map
#                     for name in namespaces:
#                         temp_var = temp_var[name]
#                     return temp_var
#                 else:
#                     value = data_map[key]
#                     return value
#             except (AttributeError, TypeError, KeyError):
#                 pass
# 
#         if default_value == self.__NoDefaultSpecified__:
#             raise KeyError(u("Key '{0}' does not exist").format(key))
#         else:
#             return default_value
# 
#     def __load_config_file(self, file_name):
#         try:
#             config_file_location = os.path.join(ProjectUtils.get_project_root(),
#                                                 ConfigReader.CONFIG_LOCATION,
#                                                 file_name + ConfigReader.CONFIG_EXT)
#             _wtflog.debug(u("locating config file: %s"), config_file_location)
#             config_yaml = open(config_file_location, 'r')
#             dataMap = yaml.load(config_yaml)
#             self._dataMaps.insert(0, dataMap)
#             config_yaml.close()
#         except Exception as e:
#             _wtflog.error(u("Error loading config file: %s"), file_name)
#             raise ConfigFileReadError(u("Error reading config file {0}").format(file_name), e)
# 
# class ConfigFileReadError(RuntimeError):
# 
#     """
#     Raised when a config file is not found.
#     """
#     pass


from wtframework.wtf.config import ConfigReader, ConfigFileReadError
import unittest2
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with WTFramework.  If not, see <http://www.gnu.org/licenses/>.
##########################################################################


class TestConfigReader(unittest2.TestCase):

    def test_get_returns_string_config_value(self):
        '''
        Test config value returned is expected value
        '''
        config = ConfigReader("tests/TestConfigReaderData")
        value = config.get("string_test")
        self.assertEqual(value, "some value", "Value did not match expected.")

    def test_get_with_default_value(self):
        "Test the get method returns value if available or the the default."
        config = ConfigReader("tests/TestConfigReaderData")
        self.assertEqual(
            "some value", config.get("string_test", "default value"))
        self.assertEqual(
            "default value", config.get("i_dont_exist", "default value"))

    def test_get_handles_namespaced_keys(self):
        '''
        Test ConfigReader works with namespaced keys like, path.to.element
        '''

# Path: wtframework/wtf/config.py
# class ConfigReader:
# 
#     '''
#     Config Reader provides a way of reading configuration settings. 
#     '''
# 
#     ENV_PREFIX = "WTF_"
#     # NOTE: these vars are defined on __init__.py to avoid loading ConfigReader
#     # when runtests.py is running.
#     CONFIG_LOCATION = constants.WTF_CONFIG_LOCATION
#     DEFAULT_CONFIG_FILE = constants.WTF_DEFAULT_CONFIG_FILE
#     CONFIG_EXT = constants.WTF_CONFIG_EXT
#     ENV_VARS = constants.WTF_ENV_VARS
# 
#     _dataMaps = None  # instance variable to store config data loaded.
#     _singleton_instance = None  # class variable to track singleton.
# 
#     def __init__(self, _env_var_=None):
#         """
#         constructor
#         """
#         self._dataMaps = []
# 
#         # load default yaml file if this is not a unit test.
#         try:
#             if _env_var_ is not None:
#                 # We pass in a custom env var for unit testing.
#                 configs = re.split(",|;", _env_var_)
#                 for config in reversed(configs):
#                     self.__load_config_file(config)
#             elif not ConfigReader.ENV_VARS in os.environ:
#                 _wtflog.warning(u("Config file not specified. Using:{0}")\
#                                 .format(os.path.join(ConfigReader.CONFIG_LOCATION,
#                                                      ConfigReader.DEFAULT_CONFIG_FILE + ConfigReader.CONFIG_EXT)))
#                 self.__load_config_file(ConfigReader.DEFAULT_CONFIG_FILE)
#             else:
#                 # Read and load in all configs specified in reverse order
#                 configs = re.split(
#                     ",|;", str(os.environ[ConfigReader.ENV_VARS]))
#                 for config in reversed(configs):
#                     self.__load_config_file(config)
# 
#         except Exception as e:
#             # Error loading config file.
#             _wtflog.error(
#                 u("An error occurred while loading config file: %s"), e)
#             raise e
# 
#     class __NoDefaultSpecified__(object):
# 
#         "No default specified to config reader."
#         pass
# 
#     def get(self, key, default_value=__NoDefaultSpecified__):
#         '''
#         Gets the value from the yaml config based on the key.
# 
#         No type casting is performed, any type casting should be 
#         performed by the caller.
# 
#         Args:
#             key (str) - Config setting key.
# 
#         Kwargs:
#             default_value - Default value to return if config is not specified.
# 
#         Returns:
#             Returns value stored in config file.
# 
#         '''
#         # First attempt to get the var from OS enviornment.
#         os_env_string = ConfigReader.ENV_PREFIX + key
#         os_env_string = os_env_string.replace(".", "_")
#         if type(os.getenv(os_env_string)) != NoneType:
#             return os.getenv(os_env_string)
# 
#         # Otherwise search through config files.
#         for data_map in self._dataMaps:
#             try:
#                 if "." in key:
#                     # this is a multi levl string
#                     namespaces = key.split(".")
#                     temp_var = data_map
#                     for name in namespaces:
#                         temp_var = temp_var[name]
#                     return temp_var
#                 else:
#                     value = data_map[key]
#                     return value
#             except (AttributeError, TypeError, KeyError):
#                 pass
# 
#         if default_value == self.__NoDefaultSpecified__:
#             raise KeyError(u("Key '{0}' does not exist").format(key))
#         else:
#             return default_value
# 
#     def __load_config_file(self, file_name):
#         try:
#             config_file_location = os.path.join(ProjectUtils.get_project_root(),
#                                                 ConfigReader.CONFIG_LOCATION,
#                                                 file_name + ConfigReader.CONFIG_EXT)
#             _wtflog.debug(u("locating config file: %s"), config_file_location)
#             config_yaml = open(config_file_location, 'r')
#             dataMap = yaml.load(config_yaml)
#             self._dataMaps.insert(0, dataMap)
#             config_yaml.close()
#         except Exception as e:
#             _wtflog.error(u("Error loading config file: %s"), file_name)
#             raise ConfigFileReadError(u("Error reading config file {0}").format(file_name), e)
# 
# class ConfigFileReadError(RuntimeError):
# 
#     """
#     Raised when a config file is not found.
#     """
#     pass


# Path: wtframework/wtf/tests/test_config_reader.py
from wtframework.wtf.config import ConfigReader, ConfigFileReadError
import unittest2

#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with WTFramework.  If not, see <http://www.gnu.org/licenses/>.
##########################################################################


class TestConfigReader(unittest2.TestCase):

    def test_get_returns_string_config_value(self):
        '''
        Test config value returned is expected value
        '''
        config = ConfigReader("tests/TestConfigReaderData")
        value = config.get("string_test")
        self.assertEqual(value, "some value", "Value did not match expected.")

    def test_get_with_default_value(self):
        "Test the get method returns value if available or the the default."
        config = ConfigReader("tests/TestConfigReaderData")
        self.assertEqual(
            "some value", config.get("string_test", "default value"))
        self.assertEqual(
            "default value", config.get("i_dont_exist", "default value"))

    def test_get_handles_namespaced_keys(self):
        '''
        Test ConfigReader works with namespaced keys like, path.to.element
        '''

        config = ConfigReader("tests/TestConfigReaderData")