From b1ecf25d6f13e6c2549fbdddf3d72df3f6fb9617 Mon Sep 17 00:00:00 2001 From: jo Date: Tue, 18 Jan 2022 07:30:23 +0100 Subject: [PATCH] feat(shared): allow loading from ini config file --- shared/libretime_shared/config.py | 7 +++++++ shared/tests/config_test.py | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/shared/libretime_shared/config.py b/shared/libretime_shared/config.py index fe06758cb..b2b3eaaa7 100644 --- a/shared/libretime_shared/config.py +++ b/shared/libretime_shared/config.py @@ -1,4 +1,5 @@ import sys +from configparser import ConfigParser from os import environ from pathlib import Path from typing import Any, Dict, Optional @@ -84,6 +85,12 @@ class BaseConfig(BaseModel): if filepath is None: return {} + # TODO: Remove ability to load ini files once yaml if fully supported. + if filepath.suffix == ".conf": + config = ConfigParser() + config.read_string(filepath.read_text(encoding="utf-8")) + return {s: dict(config.items(s)) for s in config.sections()} + try: return safe_load(filepath.read_text(encoding="utf-8")) except YAMLError as error: diff --git a/shared/tests/config_test.py b/shared/tests/config_test.py index 0095da636..e3a4ef8e7 100644 --- a/shared/tests/config_test.py +++ b/shared/tests/config_test.py @@ -46,6 +46,28 @@ def test_base_config(tmp_path: Path): assert config.database.port == 8888 +FIXTURE_CONFIG_RAW_INI = """ +[database] +host = changed +port = 6666 +""" + + +def test_base_config_ini(tmp_path: Path): + config_filepath = tmp_path / "config.conf" + config_filepath.write_text(FIXTURE_CONFIG_RAW_INI) + + with mock.patch.dict( + environ, + dict(LIBRETIME_API_KEY="f3bf04fc"), + ): + config = FixtureConfig(filepath=config_filepath) + + assert config.api_key == "f3bf04fc" + assert config.database.host == "changed" + assert config.database.port == 6666 + + FIXTURE_CONFIG_RAW_MISSING = """ database: host: "localhost"