Skip to content

Commit

Permalink
Add tests and fix loading settings from environment variables
Browse files Browse the repository at this point in the history
As with the CLI settings, parse the values as YAML to support non-string
settings.
  • Loading branch information
affenull2345 committed Jan 10, 2024
1 parent 7106d40 commit 9f63b42
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 13 deletions.
24 changes: 11 additions & 13 deletions src/cobbler_tftp/settings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,21 +220,19 @@ def load_env_variables(self) -> SettingsDict:
return self._settings_dict

for variable in cobbler_keys:
key_path = variable.split("__")
key_to_update = key_path[-1]

if len(key_path) == 2:
try:
self._settings_dict.update(
{key_to_update.lower(): str(os.environ[variable])}
)
except KeyError as exc:
print(exc)
key_path = variable.split("__")[1:]
key_path.reverse()
key_to_update = key_path[0]

if len(key_path) == 1:
self._settings_dict.update(
{key_to_update.lower(): yaml.safe_load(os.environ[variable])}
)
else:
setting_to_update = {key_to_update.lower(): str(os.environ[variable])}
setting_to_update = yaml.safe_load(os.environ[variable])

for pos in range(len(key_path) - 2, 1, -1):
setting_to_update = {key_path[pos]: setting_to_update}
for key in key_path:
setting_to_update = {key.lower(): setting_to_update}

self._settings_dict.update(setting_to_update) # type: ignore

Expand Down
18 changes: 18 additions & 0 deletions tests/unittests/application_settings/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
Tests for the application settings module.
"""

import os
from pathlib import Path
from unittest import mock

import pytest

Expand Down Expand Up @@ -136,3 +138,19 @@ def test_build_settings_with_integer_cli_args(settings_factory: SettingsFactory)

assert isinstance(settings, Settings)
assert settings.tftp_port == 1969


@mock.patch.dict(os.environ, {"COBBLER_TFTP__TFTP__ADDRESS": "1.2.3.4"})
def test_build_settings_with_env_vars(settings_factory: SettingsFactory):
settings = settings_factory.build_settings(None)

assert isinstance(settings, Settings)
assert settings.tftp_addr == "1.2.3.4"


@mock.patch.dict(os.environ, {"COBBLER_TFTP__TFTP__PORT": "1969"})
def test_build_settings_with_integer_env_vars(settings_factory: SettingsFactory):
settings = settings_factory.build_settings(None)

assert isinstance(settings, Settings)
assert settings.tftp_port == 1969

0 comments on commit 9f63b42

Please sign in to comment.