This commit is contained in:
Florian Bezannier
2024-03-23 15:12:14 +01:00
parent cfd1461ce6
commit a70b5c7d45
2 changed files with 21 additions and 8 deletions
@@ -50,12 +50,12 @@ def replace_key_underscore_by_space(obj, key):
return new_obj
class Hour:
reg = re.compile(r"([0-9]{1,2})h([0-9]{1,2})")
HOUR_REGEX = re.compile(r"([0-9]{1,2})h([0-9]{1,2})")
def __init__(self, hours: int, minutes: int):
self.hours = hours
self.minutes = minutes
class Hour(str):
hours: int
minutes: int
@classmethod
def __get_validators__(cls):
@@ -68,10 +68,13 @@ class Hour:
if len(v) == 0:
return None
m = Hour.reg.fullmatch(v.lower())
m = HOUR_REGEX.fullmatch(v.lower())
if not m:
raise ValueError('invalid hour format')
return cls(int(m.group(1)), int(m.group(2)))
hour = cls(v)
hour.hours = int(m.group(1))
hour.minutes = int(m.group(2))
return hour
def __repr__(self):
return '{}h{}'.format(self.hours, self.minutes)
@@ -188,6 +191,8 @@ class ConfigRepository(BaseModel):
def write_config(self, name=None):
if name is None:
name = CONFIG_FILENAME
self.validate(self)
ConfigRepository(**self.dict()) # validate property before write
config_to_write = ConfigRepository.get_default_config()
self.config_dto_to_config_file(config_to_write)
self._write(name, config_to_write)
+9 -1
View File
@@ -1,3 +1,4 @@
import json
import os
import unittest
from configparser import ConfigParser
@@ -33,8 +34,9 @@ night hour end = 4h42
self.assertEqual(config_written["General"]["currency"].value, "")
self.assertEqual(config_written["Electricity config"]["day price"].value, 42)
self.assertEqual(config_written["Electricity config"]["night price"].value, 0.1)
self.assertEqual(str(config_written["Electricity config"]["night hour start"].value), "1h0")
self.assertEqual(str(config_written["Electricity config"]["night hour start"].value), "1h00")
self.assertEqual(str(config_written["Electricity config"]["night hour end"].value), "4h42")
conf.json()
def test_read_non_existent_config(self):
from psa_car_controller.psacc.repository.config_repository import ConfigRepository
@@ -46,6 +48,12 @@ night hour end = 4h42
expected_result = ConfigRepository.config_file_to_dto(ConfigRepository.get_default_config())
self.assertEqual(result, expected_result)
@patch("psa_car_controller.psacc.repository.config_repository.ConfigRepository._write")
def test_read_invalid_hour(self, mock_write):
conf = ConfigRepository.config_file_to_dto(ConfigRepository.get_default_config())
conf.Electricity_config.night_hour_start = "200"
self.assertRaises(ValueError, lambda: conf.write_config())
if __name__ == '__main__':
my_logger(handler_level=os.environ.get("DEBUG_LEVEL", 20))