Allow setting config options directly (#253)

This commit is contained in:
mlbonhomme 2024-10-24 18:20:58 +02:00 коммит произвёл GitHub
Родитель 8ffa5e4533
Коммит 6b475d297b
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
2 изменённых файлов: 53 добавлений и 4 удалений

Просмотреть файл

@ -11,12 +11,19 @@ except ImportError:
class Config(object):
def get(section, option, default=None):
raise NotImplementedError
def __init__(self):
self.local_config = {}
def set_default(self, section, option, value):
self.local_config[(section, option)] = value
def get(self, section, option, default=None):
return self.local_config.get((section, option), default)
class ConfigIni(Config):
def __init__(self, path=None):
super().__init__()
self.config = ConfigParser()
if path is not None:
self.config.read(path)
@ -32,7 +39,9 @@ class ConfigIni(Config):
def get(self, section, option, default=None, type=str):
if not self.config.has_option(section, option):
if default is not None:
return default
return super().get(section, option)
res = self.config.get(section, option)
if type == list or type == set:
@ -48,7 +57,9 @@ class ConfigEnv(Config):
def get(self, section, option, default=None, type=str):
env = os.environ.get("LIBMOZDATA_CFG_" + section.upper() + "_" + option.upper())
if not env:
if default is not None:
return default
return super().get(section, option)
if type == list or type == set:
return type([s.strip(" /t") for s in env.split(",")])
@ -72,3 +83,8 @@ def get(section, option, default=None, type=str, required=False):
if required:
assert value is not None, f"Option {option} in section {section} is not set"
return value
def set_default_value(section, option, value):
global __config
__config.set_default(section, option, value)

Просмотреть файл

@ -171,6 +171,39 @@ class ConfigTest(unittest.TestCase):
):
config.get("User-Agent", "name", required=True)
def test_set_default_value(self):
"""
The set_value function correctly sets a value in the configuration
"""
with open("config.ini", "w") as f:
custom_conf = ConfigParser()
custom_conf.add_section("Section 1")
custom_conf.set("Section 1", "something", "value")
custom_conf.write(f)
from libmozdata import config
config.set_config(config.ConfigIni("config.ini"))
config.set_default_value("User-Agent", "name", "something-0.1.1")
self.assertEqual(config.get("User-Agent", "name"), "something-0.1.1")
def test_local_config_fallback(self):
with open("config.ini", "w") as f:
custom_conf = ConfigParser()
custom_conf.add_section("Section 1")
custom_conf.set("Section 1", "something", "value")
custom_conf.write(f)
from libmozdata import config
config.set_config(config.ConfigIni("config.ini"))
config.set_default_value("User-Agent", "name", "something-0.1.1")
self.assertEqual(
config.get("User-Agent", "name", required=True), "something-0.1.1"
)
class ConfigEnvTest(unittest.TestCase):
def test_config_env(self):