pyinfra/tests/unit_test/config_test.py
Julius Unverfehrt fff5be2e50 feat(settings): improve config loading logic
Load settings from .toml files, .env and environment variables. Also ensures a ROOT_PATH environment variable is
set. If ROOT_PATH is not set and no root_path argument is passed, the current working directory is used as root.
Settings paths can be a single .toml file, a folder containing .toml files or a list of .toml files and folders.
If a folder is passed, all .toml files in the folder are loaded. If settings path is None, only .env and
environment variables are loaded. If settings_path are relative paths, they are joined with the root_path argument.
2024-01-30 12:56:58 +01:00

56 lines
1.9 KiB
Python

import os
from pathlib import Path
import pytest
from dynaconf import Validator
from pyinfra.config.loader import load_settings, local_pyinfra_root_path, normalize_to_settings_files
from pyinfra.config.validators import webserver_validators
@pytest.fixture
def test_validators():
return [
Validator("test.value.int", must_exist=True, is_type_of=int),
Validator("test.value.str", must_exist=True, is_type_of=str),
]
class TestConfig:
def test_config_validation(self):
os.environ["WEBSERVER__HOST"] = "localhost"
os.environ["WEBSERVER__PORT"] = "8080"
validators = webserver_validators
test_settings = load_settings(root_path=local_pyinfra_root_path, validators=validators)
assert test_settings.webserver.host == "localhost"
def test_env_into_correct_type_conversion(self, test_validators):
os.environ["TEST__VALUE__INT"] = "1"
os.environ["TEST__VALUE__STR"] = "test"
test_settings = load_settings(root_path=local_pyinfra_root_path, validators=test_validators)
assert test_settings.test.value.int == 1
assert test_settings.test.value.str == "test"
@pytest.mark.parametrize(
"settings_path,expected_file_paths",
[
(None, []),
("config", [f"{local_pyinfra_root_path}/config/settings.toml"]),
("config/settings.toml", [f"{local_pyinfra_root_path}/config/settings.toml"]),
(f"{local_pyinfra_root_path}/config", [f"{local_pyinfra_root_path}/config/settings.toml"]),
],
)
def test_normalize_settings_files(self, settings_path, expected_file_paths):
files = normalize_to_settings_files(settings_path, local_pyinfra_root_path)
print(files)
assert len(files) == len(expected_file_paths)
for path, expected in zip(files, expected_file_paths):
assert path == Path(expected).absolute()