import unittest import os import sys # Ensure the app directory is in the path project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.append(project_root) # Import components to test from app import extract_text_from_file, get_text_splitter, Document from mongochain import MongoDBHandler class TestRAGFunctions(unittest.TestCase): def setUp(self): self.test_data_dir = os.path.join(os.path.dirname(__file__), "test_data") self.txt_file = os.path.join(self.test_data_dir, "sample.txt") self.md_file = os.path.join(self.test_data_dir, "sample.md") def test_txt_extraction(self): print("\nTesting TXT extraction...") text = extract_text_from_file(self.txt_file) self.assertIn("Quantum mechanics", text) self.assertIn("fundamental theory in physics", text) def test_md_extraction(self): print("\nTesting MD extraction...") text = extract_text_from_file(self.md_file) self.assertIn("# Physics and Philosophy", text) self.assertIn("Einstein", text) def test_splitter(self): print("\nTesting text splitter...") splitter = get_text_splitter() long_text = "Word " * 500 # Approx 2500 chars chunks = splitter.split_text(long_text) self.assertTrue(len(chunks) > 1) for chunk in chunks: self.assertLessEqual(len(chunk), 1200) # chunk_size=1000 + some overlap/margin class TestMongoDBHandler(unittest.TestCase): @classmethod def setUpClass(cls): # We assume the portable mongo might not be running during CI-style tests, # but we test the class logic where possible. cls.handler = MongoDBHandler(uri="mongodb://localhost:27017/", db_name="test_db", collection_name="test_coll") def test_handler_init(self): self.assertEqual(self.handler.db_name, "test_db") self.assertEqual(self.handler.collection_name, "test_coll") def test_connection_failure_graceful(self): # Test that it doesn't crash if connection fails (it should return False/empty) # Using a bogus port fail_handler = MongoDBHandler(uri="mongodb://localhost:12345/") success = fail_handler.connect() self.assertFalse(success) if __name__ == "__main__": unittest.main()