chat: added validation during initialization
This commit is contained in:
parent
a35b751506
commit
487898e640
@ -119,6 +119,25 @@ class Chat:
|
|||||||
|
|
||||||
messages: list[Message]
|
messages: list[Message]
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
self.validate()
|
||||||
|
|
||||||
|
def validate(self) -> None:
|
||||||
|
"""
|
||||||
|
Validate this Chat instance.
|
||||||
|
"""
|
||||||
|
def msg_paths(stem: str) -> list[str]:
|
||||||
|
return [str(fp) for fp in file_paths if fp.stem == stem]
|
||||||
|
file_paths: set[Path] = {m.file_path for m in self.messages if m.file_path is not None}
|
||||||
|
file_stems = [m.file_path.stem for m in self.messages if m.file_path is not None]
|
||||||
|
error = False
|
||||||
|
for fp in file_paths:
|
||||||
|
if file_stems.count(fp.stem) > 1:
|
||||||
|
print(f"ERROR: Found multiple copies of message '{fp.stem}': {msg_paths(fp.stem)}")
|
||||||
|
error = True
|
||||||
|
if error:
|
||||||
|
raise ChatError("Validation failed")
|
||||||
|
|
||||||
def msg_name_matches(self, file_path: Path, name: str) -> bool:
|
def msg_name_matches(self, file_path: Path, name: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Return True if the given name matches the given file_path.
|
Return True if the given name matches the given file_path.
|
||||||
@ -276,6 +295,7 @@ class ChatDB(Chat):
|
|||||||
# make all paths absolute
|
# make all paths absolute
|
||||||
self.cache_path = self.cache_path.absolute()
|
self.cache_path = self.cache_path.absolute()
|
||||||
self.db_path = self.db_path.absolute()
|
self.db_path = self.db_path.absolute()
|
||||||
|
self.validate()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dir(cls: Type[ChatDBInst],
|
def from_dir(cls: Type[ChatDBInst],
|
||||||
|
|||||||
@ -198,6 +198,17 @@ class TestChatDB(unittest.TestCase):
|
|||||||
self.cache_path.cleanup()
|
self.cache_path.cleanup()
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def test_validate(self) -> None:
|
||||||
|
duplicate_message = Message(Question('Question 4'),
|
||||||
|
Answer('Answer 4'),
|
||||||
|
{Tag('tag4')},
|
||||||
|
file_path=pathlib.Path('0004.txt'))
|
||||||
|
duplicate_message.to_file(pathlib.Path(self.db_path.name, '0004.txt'))
|
||||||
|
with self.assertRaises(ChatError) as cm:
|
||||||
|
ChatDB.from_dir(pathlib.Path(self.cache_path.name),
|
||||||
|
pathlib.Path(self.db_path.name))
|
||||||
|
self.assertEqual(str(cm.exception), "Validation failed")
|
||||||
|
|
||||||
def test_from_dir(self) -> None:
|
def test_from_dir(self) -> None:
|
||||||
chat_db = ChatDB.from_dir(pathlib.Path(self.cache_path.name),
|
chat_db = ChatDB.from_dir(pathlib.Path(self.cache_path.name),
|
||||||
pathlib.Path(self.db_path.name))
|
pathlib.Path(self.db_path.name))
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user