test_chat.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import os
  2. import unittest
  3. from unittest.mock import patch
  4. from embedchain import App
  5. class TestApp(unittest.TestCase):
  6. os.environ["OPENAI_API_KEY"] = "test_key"
  7. def setUp(self):
  8. self.app = App()
  9. @patch("embedchain.embedchain.memory", autospec=True)
  10. @patch.object(App, "retrieve_from_database", return_value=["Test context"])
  11. @patch.object(App, "get_answer_from_llm", return_value="Test answer")
  12. def test_chat_with_memory(self, mock_answer, mock_retrieve, mock_memory):
  13. """
  14. This test checks the functionality of the 'chat' method in the App class with respect to the chat history
  15. memory.
  16. The 'chat' method is called twice. The first call initializes the chat history memory.
  17. The second call is expected to use the chat history from the first call.
  18. Key assumptions tested:
  19. - After the first call, 'memory.chat_memory.add_user_message' and 'memory.chat_memory.add_ai_message' are
  20. called with correct arguments, adding the correct chat history.
  21. - During the second call, the 'chat' method uses the chat history from the first call.
  22. The test isolates the 'chat' method behavior by mocking out 'retrieve_from_database', 'get_answer_from_llm' and
  23. 'memory' methods.
  24. """
  25. mock_memory.load_memory_variables.return_value = {"history": []}
  26. app = App()
  27. # First call to chat
  28. first_answer = app.chat("Test query 1")
  29. self.assertEqual(first_answer, "Test answer")
  30. mock_memory.chat_memory.add_user_message.assert_called_once_with("Test query 1")
  31. mock_memory.chat_memory.add_ai_message.assert_called_once_with("Test answer")
  32. mock_memory.chat_memory.add_user_message.reset_mock()
  33. mock_memory.chat_memory.add_ai_message.reset_mock()
  34. # Second call to chat
  35. second_answer = app.chat("Test query 2")
  36. self.assertEqual(second_answer, "Test answer")
  37. mock_memory.chat_memory.add_user_message.assert_called_once_with("Test query 2")
  38. mock_memory.chat_memory.add_ai_message.assert_called_once_with("Test answer")