diff --git a/pyttman/core/internals.py b/pyttman/core/internals.py index 9a4ac97..97b09ca 100644 --- a/pyttman/core/internals.py +++ b/pyttman/core/internals.py @@ -5,6 +5,9 @@ from dataclasses import dataclass, field from datetime import datetime from typing import Any +import json +from collections import UserDict + import pyttman from pyttman.core.containers import MessageMixin, Reply @@ -32,7 +35,6 @@ def depr_graceful(message: str, version: str): out = f"{message} - This was deprecated in version {version}." warnings.warn(out, DeprecationWarning) - class Settings: """ Dataclass holding settings configured in the settings.py @@ -48,7 +50,10 @@ class Settings: aren't valid settings. """ - def __init__(self, **kwargs): + def __init__(self, dictionary=None, **kwargs): + if dictionary is None: + dictionary = {} + self.__dict__.update(dictionary) self.APPEND_LOG_FILES: bool = True self.MIDDLEWARE: dict | None = None self.ABILITIES: list | None = None @@ -60,14 +65,27 @@ def __init__(self, **kwargs): self.LOG_FORMAT: str | None = None self.LOG_TO_STDOUT: bool = False - [setattr(self, k, v) for k, v in kwargs.items() + [self._set_attr(k, v) for k, v in kwargs.items() if not inspect.ismodule(v) and not inspect.isfunction(v)] + def __getitem__(self, item): + return self.__dict__[item] + + def _set_attr(self, k, v): + tmp = v + if isinstance(v, dict): + tmp = Settings._dict_to_object(v) + + setattr(self, k, tmp) + def __repr__(self): _attrs = {name: value for name, value in self.__dict__.items()} return f"Settings({_attrs})" + @staticmethod + def _dict_to_object(dictionary): + return json.loads(json.dumps(dictionary), object_hook=Settings) def _generate_name(name): """ diff --git a/tests/core/test_settings.py b/tests/core/test_settings.py new file mode 100644 index 0000000..a225584 --- /dev/null +++ b/tests/core/test_settings.py @@ -0,0 +1,32 @@ +from tests.module_helper import PyttmanInternalBaseTestCase +from pyttman.core.internals import Settings + +from importlib import import_module +import pytest + +@pytest.fixture +def mockSettings(): + + mock_settings = { + "d":{ + "k1":"v1", + "k2":{ + "a":"a", + "b":"b" + } + }, + "foo":"bar" + } + + return Settings(**mock_settings) + +def test_read_settings_with_dictionary(mockSettings): + assert mockSettings.d.k2.a == "a" + assert mockSettings.d["k2"].a == "a" + assert mockSettings.d["k2"]["a"] == "a" + + assert mockSettings.d.k1 == "v1" + assert mockSettings.d["k1"] == "v1" + + assert mockSettings.foo == "bar" +