Skip to content

Commit

Permalink
Get config values from environment if not present in config file (#998)
Browse files Browse the repository at this point in the history
  • Loading branch information
Askaholic authored Jan 7, 2024
1 parent 00cf9ff commit 5d27a0a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
10 changes: 9 additions & 1 deletion server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,22 @@ def __init__(self):
self.QUEUE_POP_TIME_MOVING_AVG_SIZE = 5

self._defaults = {
key: value for key, value in vars(self).items() if key.isupper()
key: value
for key, value in vars(self).items()
if key.isupper()
}

self._callbacks: dict[str, Callable] = {}
self.refresh()

def refresh(self) -> None:
new_values = self._defaults.copy()
# Add fallback values from environment.
# NOTE: Only works for string values!
for key in new_values:
value = os.getenv(key)
if value is not None:
new_values[key] = value

config_file = os.getenv("CONFIGURATION_FILE")
if config_file is not None:
Expand Down
17 changes: 16 additions & 1 deletion tests/unit_tests/test_configuration_refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,27 @@ async def config_service(monkeypatch):
async def test_configuration_refresh(monkeypatch):
config.refresh()
assert config.DB_PASSWORD == "banana"
assert config.DB_LOGIN == "root"

monkeypatch.setenv("CONFIGURATION_FILE", "tests/data/refresh_conf.yaml")
assert config.DB_PASSWORD == "banana"

# Values in config file will override defaults
config.refresh()
assert config.DB_PASSWORD == "apple"
assert config.DB_LOGIN == "root"

# Values in config file will override environment
monkeypatch.setenv("DB_PASSWORD", "plantain")
config.refresh()
assert config.DB_PASSWORD == "apple"
assert config.DB_LOGIN == "root"

# Values in environment will override defaults
monkeypatch.setenv("DB_LOGIN", "beet")
config.refresh()
assert config.DB_PASSWORD == "apple"
assert config.DB_LOGIN == "beet"


async def test_config_refresh_file_not_found(monkeypatch):
Expand Down Expand Up @@ -80,7 +95,7 @@ async def test_config_callback_on_change(config_service, monkeypatch):


@fast_forward(20)
async def test_config_no_callback_without_change(config_service, monkeypatch):
async def test_config_no_callback_without_change(config_service):
callback = mock.Mock()
config.register_callback("DB_PASSWORD", callback)
assert config.DB_PASSWORD == "banana"
Expand Down

0 comments on commit 5d27a0a

Please sign in to comment.