S allius/issue217 (#229)

* move config.py into a sub directory cnf

* adapt unit test

* split config class

- use depency injection to get config

* increase test coverage
This commit is contained in:
Stefan Allius
2024-12-03 22:02:23 +01:00
committed by GitHub
parent 668c631018
commit a5b2b4b7c2
19 changed files with 145 additions and 85 deletions

View File

@@ -1,19 +1,23 @@
'''Config module handles the proxy configuration in the config.toml file'''
import shutil
import tomllib
import logging
from abc import ABC, abstractmethod
from schema import Schema, And, Or, Use, Optional
class ConfigIfc(ABC):
@abstractmethod
def get_config(cls) -> dict: # pragma: no cover
pass
class Config():
'''Static class Config is reads and sanitize the config.
Read config.toml file and sanitize it with read().
Get named parts of the config with get()'''
act_config = {}
def_config = {}
conf_schema = Schema({
'tsun': {
'enabled': Use(bool),
@@ -93,38 +97,14 @@ class Config():
)
@classmethod
def class_init(cls) -> None | str: # pragma: no cover
try:
# make the default config transparaent by copying it
# in the config.example file
logging.debug('Copy Default Config to config.example.toml')
shutil.copy2("default_config.toml",
"config/config.example.toml")
except Exception:
pass
err_str = cls.read()
del cls.conf_schema
return err_str
def init(cls, ifc: ConfigIfc, path='') -> None | str:
cls.ifc = ifc
cls.act_config = {}
cls.def_config = {}
return cls.read(path)
@classmethod
def _read_config_file(cls) -> dict: # pragma: no cover
usr_config = {}
try:
with open("config/config.toml", "rb") as f:
usr_config = tomllib.load(f)
except Exception as error:
err = f'Config.read: {error}'
logging.error(err)
logging.info(
'\n To create the missing config.toml file, '
'you can rename the template config.example.toml\n'
' and customize it for your scenario.\n')
return usr_config
@classmethod
def read(cls, path='') -> None | str:
def read(cls, path) -> None | str:
'''Read config file, merge it with the default config
and sanitize the result'''
err = None
@@ -140,7 +120,7 @@ class Config():
# overwrite the default values, with values from
# the config.toml file
usr_config = cls._read_config_file()
usr_config = cls.ifc.get_config()
# merge the default and the user config
config = def_config.copy()

View File

@@ -0,0 +1,34 @@
'''Config module handles the proxy configuration in the config.toml file'''
import shutil
import tomllib
import logging
from cnf.config import ConfigIfc
class ConfigIfcProxy(ConfigIfc):
def __init__(self): # pragma: no cover
try:
# make the default config transparaent by copying it
# in the config.example file
logging.info('Copy Default Config to config.example.toml')
shutil.copy2("default_config.toml",
"config/config.example.toml")
except Exception:
pass
def get_config(self, cnf_file="config/config.toml") -> dict:
usr_config = {}
try:
with open(cnf_file, "rb") as f:
usr_config = tomllib.load(f)
except Exception as error:
err = f'Config.read: {error}'
logging.error(err)
logging.info(
'\n To create the missing config.toml file, '
'you can rename the template config.example.toml\n'
' and customize it for your scenario.\n')
return usr_config

View File

@@ -7,7 +7,7 @@ from tzlocal import get_localzone
from async_ifc import AsyncIfc
from messages import Message, State
from modbus import Modbus
from config import Config
from cnf.config import Config
from gen3.infos_g3 import InfosG3
from infos import Register

View File

@@ -6,7 +6,7 @@ from datetime import datetime
from async_ifc import AsyncIfc
from messages import hex_dump_memory, Message, State
from config import Config
from cnf.config import Config
from modbus import Modbus
from gen3plus.infos_g3p import InfosG3P
from infos import Register, Fmt

View File

@@ -12,7 +12,7 @@ from proxy import Proxy
from async_stream import StreamPtr
from async_stream import AsyncStreamClient
from async_stream import AsyncStreamServer
from config import Config
from cnf.config import Config
from infos import Infos
logger_mqtt = logging.getLogger('mqtt')

View File

@@ -2,7 +2,7 @@ import logging
import traceback
import asyncio
from config import Config
from cnf.config import Config
from gen3plus.inverter_g3p import InverterG3P
from infos import Infos

View File

@@ -5,7 +5,7 @@ import traceback
from modbus import Modbus
from messages import Message
from config import Config
from cnf.config import Config
from singleton import Singleton
logger_mqtt = logging.getLogger('mqtt')

View File

@@ -2,7 +2,7 @@ import asyncio
import logging
import json
from config import Config
from cnf.config import Config
from mqtt import Mqtt
from infos import Infos

View File

@@ -10,7 +10,8 @@ from inverter_ifc import InverterIfc
from gen3.inverter_g3 import InverterG3
from gen3plus.inverter_g3p import InverterG3P
from scheduler import Schedule
from config import Config
from cnf.config import Config
from cnf.config_ifc_proxy import ConfigIfcProxy
from modbus_tcp import ModbusTcp
routes = web.RouteTableDef()
@@ -149,7 +150,7 @@ if __name__ == "__main__":
asyncio.set_event_loop(loop)
# read config file
ConfigErr = Config.class_init()
ConfigErr = Config.init(ConfigIfcProxy())
if ConfigErr is not None:
logging.info(f'ConfigErr: {ConfigErr}')
Proxy.class_init()