diff --git a/chatmastermind/chat.py b/chatmastermind/chat.py index 41d12b9..fdfc3d3 100644 --- a/chatmastermind/chat.py +++ b/chatmastermind/chat.py @@ -119,6 +119,25 @@ class Chat: 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: """ Return True if the given name matches the given file_path. @@ -276,6 +295,7 @@ class ChatDB(Chat): # make all paths absolute self.cache_path = self.cache_path.absolute() self.db_path = self.db_path.absolute() + self.validate() @classmethod def from_dir(cls: Type[ChatDBInst], diff --git a/tests/test_chat.py b/tests/test_chat.py index 4962688..18cc4ef 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -198,6 +198,17 @@ class TestChatDB(unittest.TestCase): self.cache_path.cleanup() 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: chat_db = ChatDB.from_dir(pathlib.Path(self.cache_path.name), pathlib.Path(self.db_path.name))