Finished a better implementation of the config

This commit is contained in:
dandaedre 2022-02-20 19:14:34 +01:00
parent 4129507661
commit e0a5c88175
2 changed files with 82 additions and 20 deletions

View File

@ -1,33 +1,61 @@
# Interprets config files
import os
import yaml
class ConfigLoader:
"""
Reads config files
:param configfile: The file to read
Reads all config files in a folder
Behaves like a dictionary of all config files
return FileNotFound Error on Error
:param config_folder: The folder to read
"""
def __init__(self, configfile):
def __init__(self, config_folder, extensions="yaml"):
"""
Loads config file
:param configfile: path to config file
Defines the config folder and loads all configs
:param config_folder: path to config file
:param extensions: file extensions to load
:return: None
"""
with open(configfile, "r") as f:
self.loaded_conf = yaml.safe_load(f)
self.config_folder = config_folder
self.loaded_conf = {}
self.extensions = extensions
self.load_configs()
def load_from_file(self, filepath):
"""
Loads a config file
:param filepath: path to config file
:return: None
"""
basename = os.path.basename(filepath)
name, ext = os.path.splitext(basename)
with open(filepath, "r") as f:
self.loaded_conf[name] = yaml.safe_load(f)
def load_configs(self):
"""
Loads all configs in the config folder
:return: None
"""
for filename in os.listdir(self.config_folder):
file_ext = os.path.splitext(filename)[1][1:]
if file_ext in self.extensions:
self.load_from_file(os.path.join(self.config_folder, filename))
def __getitem__(self, item):
"""
Returns config value
Returns a yaml config object if in self.loaded_conf
:param item: config key
:return: config value
"""
try:
return self.loaded_conf[item]
except KeyError:
print("Argument", item, "not found.")
print(f"Error: {item} is not in {self.loaded_conf}")
raise FileNotFoundError
def __repr__(self):
"""
@ -40,21 +68,21 @@ class ConfigLoader:
class UserConfig(ConfigLoader):
"""
Reads user config file.
:param configfile: path to config file
:param config_folder: path to config file
:return: None
"""
def __init__(self, configfile):
super().__init__(configfile)
def __init__(self, config_folder):
super().__init__(config_folder)
class GlobalConfig(ConfigLoader):
"""
Reads global config file.
:param configfile: path to config file
:param config_folder: path to config file
:return: None
"""
def __init__(self, configfile):
super().__init__(configfile)
def __init__(self, config_folder):
super().__init__(config_folder)
# conf = ConfigLoader("./example_userfiles/config/aliases.yml")
# conf = ConfigLoader("./example_userfiles/config/aliases.yaml")

View File

@ -1,11 +1,45 @@
import os
import bootstraparse.modules.config as config
import pytest
import tempfile
"""
"""
temp_folder = tempfile.TemporaryDirectory()
configs = {
"app/configs/parser_config.yaml": '{"parser": {"name": "test_parser", "type": "test_parser"}}',
"user/config/aliases.yaml": '{"aliases": {"test_alias": "test_parser"}}',
"user/config/glossary.yaml": '{"glossary": {"test_glossary": "test_parser"}}',
"user/config/custom_template.yaml": '{"custom_template": {"test_template": "test_parser"}}',
}
user_conf = os.path.join(temp_folder.name, "user/config")
app_conf = os.path.join(temp_folder.name, "app/configs")
@pytest.fixture(autouse=True)
def make_false_configs():
for file_name, content in configs.items():
os.makedirs(os.path.dirname(os.path.join(temp_folder.name, file_name)), exist_ok=True)
with open(os.path.join(temp_folder.name, file_name), "w") as f:
f.write(content)
@pytest.mark.xfail(reason="Not implemented")
def test_config_load():
assert config.load() is not None
usr_c = config.ConfigLoader(user_conf)
assert usr_c["aliases"] == {"aliases": {"test_alias": "test_parser"}}
assert usr_c["glossary"] == {"glossary": {"test_glossary": "test_parser"}}
assert usr_c["aliases"]["aliases"] == {"test_alias": "test_parser"}
assert usr_c["aliases"]["aliases"]["test_alias"] == "test_parser"
with pytest.raises(KeyError):
assert usr_c["aliases"]["aliases"]["test_alias2"] is not None
with pytest.raises(FileNotFoundError):
assert usr_c["aliases2"] is not None
assert usr_c.__repr__()
def test_children():
usr_c = config.UserConfig(user_conf)
site_c = config.GlobalConfig(app_conf)
assert usr_c["glossary"] == {"glossary": {"test_glossary": "test_parser"}}
assert site_c["parser_config"] == {"parser": {"name": "test_parser", "type": "test_parser"}}