Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix lint

Bingxi Zhao74fbaf752d28
diff --git a/.env.example b/.env.example
index b1274db6b..03e231903 100644
--- a/.env.example
+++ b/.env.example
@@ -113,6 +113,3 @@ NEXT_PUBLIC_API_BASE=
# [Optional] Disable SSL verification (not recommended for production)
DISABLE_SSL_VERIFY=false
-
-# [Optional] RAG tool module log level: DEBUG, INFO, WARNING, ERROR
-RAG_TOOL_MODULE_LOG_LEVEL=INFO
diff --git a/.env.example_CN b/.env.example_CN
index e8b3798f6..dee5c6108 100644
--- a/.env.example_CN
+++ b/.env.example_CN
@@ -112,4 +112,4 @@ NEXT_PUBLIC_API_BASE=
# ==============================================================================
# [可选] 禁用 SSL 证书验证(生产环境不建议启用)
-DISABLE_SSL_VERIFY=false
\ No newline at end of file
+DISABLE_SSL_VERIFY=false
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 3c2e5b052..e21601473 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -88,16 +88,6 @@ repos:
args: [-c, pyproject.toml, -q]
exclude: ^tests/
- # ============================================
- # Docstring coverage checking
- # ============================================
- - repo: https://github.com/econchick/interrogate
- rev: 1.7.0
- hooks:
- - id: interrogate
- args: [-v, -q, --exclude=tests/, --exclude=scripts/, --ignore-init-method, --ignore-private]
- pass_filenames: false
-
# ============================================
# Type checking
# ============================================
diff --git a/assets/releases/ver0-5-1.md b/assets/releases/ver0-5-1.md
new file mode 100644
index 000000000..eaf49db74
--- /dev/null
+++ b/assets/releases/ver0-5-1.md
@@ -0,0 +1,32 @@
+# 🔧 DeepTutor v0.5.1 Release Notes
+
+**Release Date:** 2026.01.18
+
+Hey everyone! We just released v0.5.1!
+
+## ✨ Highlights
+
+### 📄 Docling Support for RAG-Anything
+
+Added alternative RAG-Anything initialization using **Docling** as the document parser:
+- For users whose local environment is not suitable for MinerU
+- Provides a lightweight alternative for document processing
+- Same multimodal graph capabilities with different backend
+
+### 📝 Logging System Optimization
+
+Refactored the logging system for better management:
+- Improved log output control across all modules
+- Better structured logging adapters
+- Enhanced console, file, and WebSocket handlers
+
+### 🐛 Bug Fixes & Code Improvements
+
+- Optimized code structure across multiple modules
+- Fixed several bugs affecting user experience
+- Improved CI/CD workflows with Python 3.10/3.11 matrix testing
+
+---
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v0.5.0...v0.5.1
+
diff --git a/src/knowledge/manager.py b/src/knowledge/manager.py
index ebba790da..32c04525c 100644
--- a/src/knowledge/manager.py
+++ b/src/knowledge/manager.py
@@ -413,7 +413,6 @@ class KnowledgeBaseManager:
files.extend(folder.glob(f"**/*{ext}"))
# Generate folder ID
- import hashlib
folder_id = hashlib.md5( # noqa: S324
str(folder).encode(), usedforsecurity=False
diff --git a/tests/services/rag/test_pipeline_integration.py b/tests/services/rag/test_pipeline_integration.py
index 9f617f459..0f2212dbf 100644
--- a/tests/services/rag/test_pipeline_integration.py
+++ b/tests/services/rag/test_pipeline_integration.py
@@ -9,10 +9,10 @@ Tests the full workflow: initialize -> search -> delete
Usage:
# Test specific pipeline
python tests/services/rag/test_pipeline_integration.py --pipeline llamaindex
-
+
# Test all pipelines
python tests/services/rag/test_pipeline_integration.py --pipeline all
-
+
# Using pytest
pytest tests/services/rag/test_pipeline_integration.py -v --pipeline llamaindex
"""
@@ -20,16 +20,17 @@ Usage:
import argparse
import asyncio
import os
+from pathlib import Path
import shutil
import sys
import tempfile
-from pathlib import Path
# Add project root to path
project_root = Path(__file__).resolve().parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from dotenv import load_dotenv
+
load_dotenv(project_root / "DeepTutor.env", override=False)
load_dotenv(project_root / ".env", override=False)
@@ -40,6 +41,7 @@ TEST_FILE = project_root / "tests" / "services" / "rag" / "testfile.txt"
class Colors:
"""Terminal colors"""
+
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
@@ -73,59 +75,57 @@ def print_info(text: str):
class PipelineIntegrationTest:
"""
Integration test for a specific RAG pipeline.
-
+
Tests:
1. Knowledge base initialization with test file
2. Search/retrieval
3. Knowledge base deletion
"""
-
+
def __init__(self, pipeline_name: str, test_file: Path = TEST_FILE):
self.pipeline_name = pipeline_name
self.test_file = test_file
self.temp_dir = None
self.kb_name = f"test_kb_{pipeline_name}"
self.service = None
-
+
async def setup(self):
"""Setup test environment"""
# Create temporary directory
self.temp_dir = tempfile.mkdtemp(prefix=f"rag_test_{self.pipeline_name}_")
print_info(f"Created temp directory: {self.temp_dir}")
-
+
# Initialize service with temp directory
from src.services.rag import RAGService
- self.service = RAGService(
- kb_base_dir=self.temp_dir,
- provider=self.pipeline_name
- )
-
+
+ self.service = RAGService(kb_base_dir=self.temp_dir, provider=self.pipeline_name)
+
# Verify test file exists
if not self.test_file.exists():
raise FileNotFoundError(f"Test file not found: {self.test_file}")
-
+
print_info(f"Test file: {self.test_file}")
print_info(f"Provider: {self.pipeline_name}")
-
+
async def teardown(self):
"""Cleanup test environment"""
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
print_info(f"Cleaned up temp directory: {self.temp_dir}")
-
+
async def test_initialize(self) -> bool:
"""Test knowledge base initialization"""
print("\n 📚 Testing initialization...")
-
+
try:
success = await self.service.initialize(
kb_name=self.kb_name,
file_paths=[str(self.test_file)],
)
-
+
if success:
print_success("Knowledge base initialized successfully")
-
+
# Verify KB directory was created
kb_dir = Path(self.temp_dir) / self.kb_name
if kb_dir.exists():
@@ -135,22 +135,23 @@ class PipelineIntegrationTest:
print_info(f"KB contains {len(contents)} files/directories")
else:
print_warning("KB directory not found after initialization")
-
+
return True
else:
print_error("Initialization returned False")
return False
-
+
except Exception as e:
print_error(f"Initialization failed: {e}")
import traceback
+
traceback.print_exc()
return False
-
+
async def test_search(self) -> bool:
"""Test search/retrieval"""
print("\n 🔍 Testing search...")
-
+
# Test query based on test file content
# testfile.txt contains: "Shandong province has a pancake."
test_queries = [
@@ -158,31 +159,31 @@ class PipelineIntegrationTest:
("pancake", "Search for 'pancake'"),
("What does Shandong have?", "Natural question"),
]
-
+
all_passed = True
-
+
for query, description in test_queries:
try:
print_info(f"Query: {query} ({description})")
-
+
result = await self.service.search(
query=query,
kb_name=self.kb_name,
mode="naive" if self.pipeline_name in ["llamaindex"] else "hybrid",
)
-
+
# Check result structure
if not isinstance(result, dict):
print_error(f"Result is not a dict: {type(result)}")
all_passed = False
continue
-
+
# Check required fields
required_fields = ["query", "answer", "content", "provider"]
missing = [f for f in required_fields if f not in result]
if missing:
print_warning(f"Missing fields: {missing}")
-
+
# Check content
answer = result.get("answer", "")
if answer:
@@ -192,22 +193,23 @@ class PipelineIntegrationTest:
print_info(f"Preview: {preview}")
else:
print_warning("Empty answer")
-
+
except Exception as e:
print_error(f"Search failed: {e}")
import traceback
+
traceback.print_exc()
all_passed = False
-
+
return all_passed
-
+
async def test_search_via_rag_tool(self) -> bool:
"""Test search via rag_tool.py (the actual interface used by agents)"""
print("\n 🔧 Testing via rag_tool.py...")
-
+
try:
from src.tools.rag_tool import rag_search
-
+
result = await rag_search(
query="What does Shandong have?",
kb_name=self.kb_name,
@@ -215,52 +217,53 @@ class PipelineIntegrationTest:
kb_base_dir=self.temp_dir,
mode="naive",
)
-
+
if result and result.get("answer"):
- print_success(f"rag_tool.py search successful")
+ print_success("rag_tool.py search successful")
print_info(f"Provider: {result.get('provider')}")
print_info(f"Answer preview: {result['answer'][:100]}...")
return True
else:
print_warning("rag_tool.py returned empty result")
return False
-
+
except Exception as e:
print_error(f"rag_tool.py search failed: {e}")
import traceback
+
traceback.print_exc()
return False
-
+
async def test_delete(self) -> bool:
"""Test knowledge base deletion"""
print("\n 🗑️ Testing deletion...")
-
+
try:
success = await self.service.delete(kb_name=self.kb_name)
-
+
if success:
print_success("Knowledge base deleted successfully")
-
+
# Verify KB directory was removed
kb_dir = Path(self.temp_dir) / self.kb_name
if not kb_dir.exists():
print_success("KB directory removed")
else:
print_warning("KB directory still exists after deletion")
-
+
return True
else:
print_warning("Deletion returned False (KB may not exist)")
return True # Not necessarily a failure
-
+
except Exception as e:
print_error(f"Deletion failed: {e}")
return False
-
+
async def run_all_tests(self) -> dict:
"""Run all tests for this pipeline"""
print_header(f"Testing Pipeline: {self.pipeline_name}")
-
+
results = {
"pipeline": self.pipeline_name,
"setup": False,
@@ -270,26 +273,27 @@ class PipelineIntegrationTest:
"delete": False,
"cleanup": False,
}
-
+
try:
# Setup
await self.setup()
results["setup"] = True
-
+
# Initialize
results["initialize"] = await self.test_initialize()
-
+
# Search (only if initialize succeeded)
if results["initialize"]:
results["search"] = await self.test_search()
results["rag_tool"] = await self.test_search_via_rag_tool()
-
+
# Delete
results["delete"] = await self.test_delete()
-
+
except Exception as e:
print_error(f"Test failed with exception: {e}")
import traceback
+
traceback.print_exc()
finally:
# Cleanup
@@ -298,13 +302,14 @@ class PipelineIntegrationTest:
results["cleanup"] = True
except Exception as e:
print_error(f"Cleanup failed: {e}")
-
+
return results
def get_available_pipelines():
"""Get list of available pipelines"""
from src.services.rag import RAGService
+
return [p["id"] for p in RAGService.list_providers()]
@@ -318,43 +323,43 @@ async def run_all_pipeline_tests() -> list:
"""Run tests for all pipelines"""
pipelines = get_available_pipelines()
results = []
-
+
for pipeline in pipelines:
result = await run_pipeline_test(pipeline)
results.append(result)
-
+
return results
def print_summary(results: list):
"""Print test summary"""
print_header("Test Summary")
-
+
all_passed = True
-
+
for result in results:
pipeline = result["pipeline"]
tests = ["setup", "initialize", "search", "rag_tool", "delete", "cleanup"]
passed = sum(1 for t in tests if result.get(t, False))
total = len(tests)
-
+
if passed == total:
print_success(f"{pipeline}: {passed}/{total} tests passed")
else:
print_error(f"{pipeline}: {passed}/{total} tests passed")
all_passed = False
-
+
# Show failed tests
for test in tests:
if not result.get(test, False):
print_error(f" - {test} failed")
-
+
print()
if all_passed:
print(f"{Colors.GREEN}{Colors.BOLD}All tests passed!{Colors.END}")
else:
print(f"{Colors.RED}{Colors.BOLD}Some tests failed.{Colors.END}")
-
+
return all_passed
@@ -362,26 +367,23 @@ async def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description="RAG Pipeline Integration Tests")
parser.add_argument(
- "--pipeline", "-p",
+ "--pipeline",
+ "-p",
type=str,
default="llamaindex",
- help="Pipeline to test (or 'all' for all pipelines). Default: llamaindex"
- )
- parser.add_argument(
- "--list", "-l",
- action="store_true",
- help="List available pipelines"
+ help="Pipeline to test (or 'all' for all pipelines). Default: llamaindex",
)
-
+ parser.add_argument("--list", "-l", action="store_true", help="List available pipelines")
+
args = parser.parse_args()
-
+
# List pipelines
if args.list:
print_header("Available Pipelines")
for pipeline in get_available_pipelines():
print_info(pipeline)
return
-
+
# Run tests
if args.pipeline.lower() == "all":
results = await run_all_pipeline_tests()
@@ -392,9 +394,9 @@ async def main():
print_error(f"Unknown pipeline: {args.pipeline}")
print_info(f"Available: {available}")
sys.exit(1)
-
+
results = [await run_pipeline_test(args.pipeline)]
-
+
# Print summary
success = print_summary(results)
sys.exit(0 if success else 1)
@@ -403,28 +405,23 @@ async def main():
# Pytest support
def pytest_addoption(parser):
"""Add pytest command line options"""
- parser.addoption(
- "--pipeline",
- action="store",
- default="llamaindex",
- help="Pipeline to test"
- )
+ parser.addoption("--pipeline", action="store", default="llamaindex", help="Pipeline to test")
class TestPipelineIntegration:
"""Pytest test class"""
-
+
@staticmethod
def test_pipeline(request):
"""Test the specified pipeline"""
pipeline_name = request.config.getoption("--pipeline")
-
+
async def _run():
if pipeline_name.lower() == "all":
results = await run_all_pipeline_tests()
else:
results = [await run_pipeline_test(pipeline_name)]
-
+
# Assert all tests passed
for result in results:
assert result["setup"], f"{result['pipeline']}: Setup failed"
@@ -432,12 +429,12 @@ class TestPipelineIntegration:
assert result["search"], f"{result['pipeline']}: Search failed"
assert result["rag_tool"], f"{result['pipeline']}: rag_tool test failed"
assert result["delete"], f"{result['pipeline']}: Delete failed"
-
+
asyncio.run(_run())
if __name__ == "__main__":
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
-
+
asyncio.run(main())
diff --git a/tests/services/rag/test_rag_pipelines.py b/tests/services/rag/test_rag_pipelines.py
index bef019720..a20ac1fbc 100644
--- a/tests/services/rag/test_rag_pipelines.py
+++ b/tests/services/rag/test_rag_pipelines.py
@@ -10,19 +10,16 @@ RAG Pipeline Integration Tests
运行方式:
python -m pytest tests/services/rag/test_rag_pipelines.py -v
-
+
或直接运行:
python tests/services/rag/test_rag_pipelines.py
"""
-import asyncio
-import json
import os
+from pathlib import Path
import shutil
import sys
import tempfile
-from pathlib import Path
-from typing import Dict, List, Optional
import unittest
# Add project root to path
@@ -30,24 +27,25 @@ project_root = Path(__file__).resolve().parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from dotenv import load_dotenv
+
load_dotenv(project_root / "DeepTutor.env", override=False)
load_dotenv(project_root / ".env", override=False)
class RAGPipelineTestBase:
"""Base class for RAG pipeline tests"""
-
+
TEST_KB_NAME = "test_rag_pipeline"
TEST_QUERY = "What is machine learning?"
-
+
@classmethod
def create_test_document(cls, temp_dir: str) -> str:
"""Create a test document for testing"""
test_content = """
# Introduction to Machine Learning
-Machine learning is a subset of artificial intelligence (AI) that provides systems
-the ability to automatically learn and improve from experience without being explicitly
+Machine learning is a subset of artificial intelligence (AI) that provides systems
+the ability to automatically learn and improve from experience without being explicitly
programmed.
## Types of Machine Learning
@@ -60,7 +58,7 @@ Examples:
- Classification: Predicting discrete labels
- Regression: Predicting continuous values
-### Unsupervised Learning
+### Unsupervised Learning
Unsupervised learning is a type of machine learning where the model is trained on unlabeled data.
The model learns to find patterns and structures in the data.
@@ -94,185 +92,185 @@ Machine learning has many applications in various fields including:
- Recommendation systems
- Autonomous vehicles
"""
-
+
# Create both .md and .txt versions
md_path = os.path.join(temp_dir, "ml_intro.md")
with open(md_path, "w", encoding="utf-8") as f:
f.write(test_content)
-
+
return md_path
class TestRAGToolIntegration(unittest.IsolatedAsyncioTestCase):
"""Test rag_tool.py interface with all pipelines"""
-
+
async def test_list_available_providers(self):
"""Test listing available RAG providers"""
- from src.tools.rag_tool import get_available_providers, list_pipelines
-
+ from src.tools.rag_tool import get_available_providers
+
providers = get_available_providers()
print("\n=== Available RAG Providers ===")
for p in providers:
print(f" - {p['id']}: {p['name']} - {p['description']}")
-
+
self.assertIsInstance(providers, list)
self.assertGreater(len(providers), 0)
-
+
# Check expected providers
provider_ids = [p["id"] for p in providers]
expected = ["raganything", "lightrag", "llamaindex", "academic"]
for expected_id in expected:
self.assertIn(expected_id, provider_ids, f"Missing provider: {expected_id}")
-
+
async def test_get_current_provider(self):
"""Test getting current RAG provider"""
from src.tools.rag_tool import get_current_provider
-
+
provider = get_current_provider()
print(f"\n=== Current Provider: {provider} ===")
-
+
self.assertIsInstance(provider, str)
self.assertIn(provider, ["raganything", "lightrag", "llamaindex", "academic"])
-
+
async def test_has_pipeline_valid(self):
"""Test has_pipeline with valid pipeline names"""
from src.services.rag.factory import has_pipeline
-
+
for name in ["raganything", "lightrag", "llamaindex", "academic"]:
self.assertTrue(has_pipeline(name), f"Pipeline {name} should exist")
-
+
async def test_has_pipeline_invalid(self):
"""Test has_pipeline with invalid pipeline name"""
from src.services.rag.factory import has_pipeline
-
+
self.assertFalse(has_pipeline("nonexistent"))
self.assertFalse(has_pipeline(""))
class TestPipelineFactory(unittest.IsolatedAsyncioTestCase):
"""Test pipeline factory functionality"""
-
+
async def test_get_pipeline_raganything(self):
"""Test getting RAGAnything pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipelines.raganything import RAGAnythingPipeline
-
+
pipeline = get_pipeline("raganything")
self.assertIsInstance(pipeline, RAGAnythingPipeline)
print(f"\n✓ RAGAnything pipeline created: {type(pipeline).__name__}")
-
+
async def test_get_pipeline_lightrag(self):
"""Test getting LightRAG pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipeline import RAGPipeline
-
+
pipeline = get_pipeline("lightrag")
self.assertIsInstance(pipeline, RAGPipeline)
self.assertEqual(pipeline.name, "lightrag")
print(f"\n✓ LightRAG pipeline created: {pipeline.name}")
-
+
async def test_get_pipeline_llamaindex(self):
"""Test getting LlamaIndex pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipeline import RAGPipeline
-
+
pipeline = get_pipeline("llamaindex")
self.assertIsInstance(pipeline, RAGPipeline)
self.assertEqual(pipeline.name, "llamaindex")
print(f"\n✓ LlamaIndex pipeline created: {pipeline.name}")
-
+
async def test_get_pipeline_academic(self):
"""Test getting Academic pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipeline import RAGPipeline
-
+
pipeline = get_pipeline("academic")
self.assertIsInstance(pipeline, RAGPipeline)
self.assertEqual(pipeline.name, "academic")
print(f"\n✓ Academic pipeline created: {pipeline.name}")
-
+
async def test_get_pipeline_invalid(self):
"""Test getting invalid pipeline raises error"""
from src.services.rag.factory import get_pipeline
-
+
with self.assertRaises(ValueError) as context:
get_pipeline("nonexistent")
-
+
self.assertIn("Unknown pipeline", str(context.exception))
- print(f"\n✓ Invalid pipeline correctly raises error")
+ print("\n✓ Invalid pipeline correctly raises error")
class TestRAGAnythingPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test RAGAnything pipeline (requires RAG-Anything library)"""
-
+
def setUp(self):
"""Set up test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.test_doc = self.create_test_document(self.temp_dir)
self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")
os.makedirs(self.test_kb_dir, exist_ok=True)
-
+
def tearDown(self):
"""Clean up test fixtures"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
-
+
async def test_raganything_availability(self):
"""Test if RAGAnything dependencies are available"""
print("\n=== Testing RAGAnything Availability ===")
-
+
try:
from src.services.rag.pipelines.raganything import RAGAnythingPipeline
+
pipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)
print("✓ RAGAnythingPipeline class available")
-
+
# Check RAG-Anything import
try:
pipeline._setup_raganything_path()
from raganything import RAGAnything, RAGAnythingConfig
+
print("✓ RAG-Anything library available")
return True
except ImportError as e:
print(f"⚠ RAG-Anything library not available: {e}")
print(" Install RAG-Anything to enable full functionality")
return False
-
+
except ImportError as e:
print(f"✗ Failed to import RAGAnythingPipeline: {e}")
return False
-
+
@unittest.skipUnless(
os.environ.get("TEST_RAG_ANYTHING", "").lower() == "true",
- "Set TEST_RAG_ANYTHING=true to run RAGAnything tests"
+ "Set TEST_RAG_ANYTHING=true to run RAGAnything tests",
)
async def test_raganything_full_workflow(self):
"""Test RAGAnything full workflow: initialize -> search -> delete"""
print("\n=== Testing RAGAnything Full Workflow ===")
-
+
from src.services.rag.pipelines.raganything import RAGAnythingPipeline
-
+
pipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)
-
+
# Test initialization
print(f"Initializing KB with document: {self.test_doc}")
success = await pipeline.initialize(
kb_name=self.TEST_KB_NAME,
file_paths=[self.test_doc],
- extract_numbered_items=False # Skip for speed
+ extract_numbered_items=False, # Skip for speed
)
self.assertTrue(success)
print("✓ Knowledge base initialized")
-
+
# Test search
print(f"Searching: {self.TEST_QUERY}")
result = await pipeline.search(
- query=self.TEST_QUERY,
- kb_name=self.TEST_KB_NAME,
- mode="naive"
+ query=self.TEST_QUERY, kb_name=self.TEST_KB_NAME, mode="naive"
)
self.assertIn("answer", result)
self.assertIn("content", result)
print(f"✓ Search result: {result['answer'][:100]}...")
-
+
# Test delete
deleted = await pipeline.delete(kb_name=self.TEST_KB_NAME)
self.assertTrue(deleted)
@@ -281,275 +279,267 @@ class TestRAGAnythingPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestB
class TestLlamaIndexPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test LlamaIndex pipeline (lightweight implementation)"""
-
+
def setUp(self):
"""Set up test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.test_doc = self.create_test_document(self.temp_dir)
self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")
os.makedirs(self.test_kb_dir, exist_ok=True)
-
+
def tearDown(self):
"""Clean up test fixtures"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
-
+
async def test_llamaindex_components(self):
"""Test LlamaIndex pipeline components are properly configured"""
print("\n=== Testing LlamaIndex Pipeline Components ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("llamaindex")
-
+
# Check components
self.assertIsNotNone(pipeline._parser)
self.assertGreater(len(pipeline._chunkers), 0)
self.assertIsNotNone(pipeline._embedder)
self.assertGreater(len(pipeline._indexers), 0)
self.assertIsNotNone(pipeline._retriever)
-
+
print(f"✓ Parser: {pipeline._parser.name}")
print(f"✓ Chunkers: {[c.name for c in pipeline._chunkers]}")
print(f"✓ Embedder: {pipeline._embedder.name}")
print(f"✓ Indexers: {[i.name for i in pipeline._indexers]}")
print(f"✓ Retriever: {pipeline._retriever.name}")
-
+
@unittest.skipUnless(
- os.environ.get("TEST_LLAMAINDEX", "").lower() == "true" or
- os.environ.get("TEST_ALL_PIPELINES", "").lower() == "true",
- "Set TEST_LLAMAINDEX=true to run LlamaIndex tests"
+ os.environ.get("TEST_LLAMAINDEX", "").lower() == "true"
+ or os.environ.get("TEST_ALL_PIPELINES", "").lower() == "true",
+ "Set TEST_LLAMAINDEX=true to run LlamaIndex tests",
)
async def test_llamaindex_full_workflow(self):
"""Test LlamaIndex pipeline full workflow"""
print("\n=== Testing LlamaIndex Full Workflow ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("llamaindex")
-
+
# Patch the kb_base_dir for indexer and retriever
for indexer in pipeline._indexers:
indexer.kb_base_dir = self.test_kb_dir
pipeline._retriever.kb_base_dir = self.test_kb_dir
-
+
# Test initialization
print(f"Initializing KB with document: {self.test_doc}")
try:
success = await pipeline.initialize(
- kb_name=self.TEST_KB_NAME,
- file_paths=[self.test_doc]
+ kb_name=self.TEST_KB_NAME, file_paths=[self.test_doc]
)
self.assertTrue(success)
print("✓ Knowledge base initialized")
except Exception as e:
print(f"⚠ Initialization failed (may need PDF support): {e}")
return
-
+
# Test search
print(f"Searching: {self.TEST_QUERY}")
- result = await pipeline.search(
- query=self.TEST_QUERY,
- kb_name=self.TEST_KB_NAME
- )
+ result = await pipeline.search(query=self.TEST_QUERY, kb_name=self.TEST_KB_NAME)
self.assertIn("answer", result)
print(f"✓ Search result: {result.get('answer', '')[:100]}...")
class TestLightRAGPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test LightRAG pipeline (requires RAG-Anything)"""
-
+
async def test_lightrag_components(self):
"""Test LightRAG pipeline components are properly configured"""
print("\n=== Testing LightRAG Pipeline Components ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("lightrag")
-
+
# Check components
self.assertIsNotNone(pipeline._parser)
self.assertGreater(len(pipeline._chunkers), 0)
self.assertIsNotNone(pipeline._embedder)
self.assertGreater(len(pipeline._indexers), 0)
self.assertIsNotNone(pipeline._retriever)
-
+
print(f"✓ Parser: {pipeline._parser.name}")
print(f"✓ Chunkers: {[c.name for c in pipeline._chunkers]}")
print(f"✓ Embedder: {pipeline._embedder.name}")
print(f"✓ Indexers: {[i.name for i in pipeline._indexers]}")
print(f"✓ Retriever: {pipeline._retriever.name}")
-
+
# Note: This pipeline requires RAG-Anything for full functionality
print("\n⚠ Note: LightRAG pipeline requires RAG-Anything for search/indexing")
class TestAcademicPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test Academic pipeline (requires RAG-Anything)"""
-
+
async def test_academic_components(self):
"""Test Academic pipeline components are properly configured"""
print("\n=== Testing Academic Pipeline Components ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("academic")
-
+
# Check components - Academic has 2 chunkers
self.assertIsNotNone(pipeline._parser)
self.assertEqual(len(pipeline._chunkers), 2) # SemanticChunker + NumberedItemExtractor
self.assertIsNotNone(pipeline._embedder)
self.assertGreater(len(pipeline._indexers), 0)
self.assertIsNotNone(pipeline._retriever)
-
+
print(f"✓ Parser: {pipeline._parser.name}")
print(f"✓ Chunkers: {[c.name for c in pipeline._chunkers]}")
print(f"✓ Embedder: {pipeline._embedder.name}")
print(f"✓ Indexers: {[i.name for i in pipeline._indexers]}")
print(f"✓ Retriever: {pipeline._retriever.name}")
-
+
# Note: This pipeline requires RAG-Anything for full functionality
print("\n⚠ Note: Academic pipeline requires RAG-Anything for search/indexing")
class TestRAGToolWithProviders(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test rag_tool.py with different providers"""
-
+
def setUp(self):
"""Set up test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.test_doc = self.create_test_document(self.temp_dir)
self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")
os.makedirs(self.test_kb_dir, exist_ok=True)
-
+
def tearDown(self):
"""Clean up test fixtures"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
-
+
async def test_rag_search_invalid_provider(self):
"""Test rag_search with invalid provider raises error"""
from src.tools.rag_tool import rag_search
-
+
print("\n=== Testing Invalid Provider Error ===")
-
+
with self.assertRaises(ValueError) as context:
await rag_search(
- query=self.TEST_QUERY,
- kb_name=self.TEST_KB_NAME,
- provider="nonexistent"
+ query=self.TEST_QUERY, kb_name=self.TEST_KB_NAME, provider="nonexistent"
)
-
+
self.assertIn("not found", str(context.exception))
print(f"✓ Invalid provider correctly raises error: {context.exception}")
-
+
async def test_rag_search_default_provider(self):
"""Test rag_search uses default provider from env"""
- from src.tools.rag_tool import get_current_provider, DEFAULT_RAG_PROVIDER
-
+ from src.tools.rag_tool import DEFAULT_RAG_PROVIDER, get_current_provider
+
print("\n=== Testing Default Provider ===")
-
+
current = get_current_provider()
print(f"✓ Default provider from env: {DEFAULT_RAG_PROVIDER}")
print(f"✓ Current provider: {current}")
-
+
# They should match
self.assertEqual(current, os.getenv("RAG_PROVIDER", "raganything"))
class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):
"""Test individual component availability"""
-
+
async def test_parsers_available(self):
"""Test all parsers can be imported"""
print("\n=== Testing Parser Availability ===")
-
- from src.services.rag.components.parsers import PDFParser, MarkdownParser
-
+
+ from src.services.rag.components.parsers import MarkdownParser, PDFParser
+
pdf_parser = PDFParser()
print(f"✓ PDFParser: {pdf_parser.name}")
-
+
md_parser = MarkdownParser()
print(f"✓ MarkdownParser: {md_parser.name}")
-
+
async def test_chunkers_available(self):
"""Test all chunkers can be imported"""
print("\n=== Testing Chunker Availability ===")
-
+
from src.services.rag.components.chunkers import (
- SemanticChunker, FixedSizeChunker, NumberedItemExtractor
+ FixedSizeChunker,
+ NumberedItemExtractor,
+ SemanticChunker,
)
-
+
semantic = SemanticChunker()
print(f"✓ SemanticChunker: {semantic.name}")
-
+
fixed = FixedSizeChunker()
print(f"✓ FixedSizeChunker: {fixed.name}")
-
+
numbered = NumberedItemExtractor()
print(f"✓ NumberedItemExtractor: {numbered.name}")
-
+
async def test_embedders_available(self):
"""Test all embedders can be imported"""
print("\n=== Testing Embedder Availability ===")
-
+
from src.services.rag.components.embedders import OpenAIEmbedder
-
+
embedder = OpenAIEmbedder()
print(f"✓ OpenAIEmbedder: {embedder.name}")
-
+
async def test_indexers_available(self):
"""Test all indexers can be imported"""
print("\n=== Testing Indexer Availability ===")
-
- from src.services.rag.components.indexers import VectorIndexer, GraphIndexer
-
+
+ from src.services.rag.components.indexers import GraphIndexer, VectorIndexer
+
vector = VectorIndexer()
print(f"✓ VectorIndexer: {vector.name}")
-
+
graph = GraphIndexer()
print(f"✓ GraphIndexer: {graph.name}")
-
+
async def test_retrievers_available(self):
"""Test all retrievers can be imported"""
print("\n=== Testing Retriever Availability ===")
-
+
from src.services.rag.components.retrievers import DenseRetriever, HybridRetriever
-
+
dense = DenseRetriever()
print(f"✓ DenseRetriever: {dense.name}")
-
+
hybrid = HybridRetriever()
print(f"✓ HybridRetriever: {hybrid.name}")
class TestExistingKnowledgeBase(unittest.IsolatedAsyncioTestCase):
"""Test search on existing knowledge bases"""
-
+
@unittest.skipUnless(
os.environ.get("TEST_EXISTING_KB", "").lower() == "true",
- "Set TEST_EXISTING_KB=true to test existing KBs"
+ "Set TEST_EXISTING_KB=true to test existing KBs",
)
async def test_search_existing_kb(self):
"""Test search on an existing knowledge base"""
print("\n=== Testing Existing Knowledge Base ===")
-
+
from src.tools.rag_tool import rag_search
-
+
# Use default or specified KB
kb_name = os.environ.get("TEST_KB_NAME", "ai-textbook")
query = os.environ.get("TEST_QUERY", "What is machine learning?")
-
+
print(f"KB: {kb_name}")
print(f"Query: {query}")
-
+
# Test with different modes
for mode in ["naive", "hybrid"]:
print(f"\n--- Mode: {mode} ---")
try:
- result = await rag_search(
- query=query,
- kb_name=kb_name,
- mode=mode
- )
+ result = await rag_search(query=query, kb_name=kb_name, mode=mode)
print(f"✓ Provider: {result.get('provider', 'unknown')}")
print(f"✓ Answer length: {len(result.get('answer', ''))} chars")
print(f"✓ Preview: {result.get('answer', '')[:200]}...")
@@ -562,19 +552,19 @@ def run_quick_tests():
print("=" * 60)
print("Running Quick RAG Pipeline Tests")
print("=" * 60)
-
+
# Run only fast tests
loader = unittest.TestLoader()
suite = unittest.TestSuite()
-
+
# Add quick tests
suite.addTests(loader.loadTestsFromTestCase(TestRAGToolIntegration))
suite.addTests(loader.loadTestsFromTestCase(TestPipelineFactory))
suite.addTests(loader.loadTestsFromTestCase(TestComponentAvailability))
-
+
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
-
+
return result.wasSuccessful()
@@ -591,18 +581,18 @@ def run_all_tests():
print(" TEST_KB_NAME=<name> - KB name for existing KB test")
print(" TEST_QUERY=<query> - Query for existing KB test")
print("=" * 60 + "\n")
-
+
unittest.main(verbosity=2)
if __name__ == "__main__":
import argparse
-
+
parser = argparse.ArgumentParser(description="RAG Pipeline Tests")
parser.add_argument("--quick", action="store_true", help="Run only quick tests")
parser.add_argument("--all", action="store_true", help="Run all tests")
args = parser.parse_args()
-
+
if args.quick:
success = run_quick_tests()
sys.exit(0 if success else 1)
diff --git a/tests/services/rag/testfile.txt b/tests/services/rag/testfile.txt
index 774a88dff..d8b190987 100644
--- a/tests/services/rag/testfile.txt
+++ b/tests/services/rag/testfile.txt
@@ -1,2 +1,2 @@
this is a test file
-Shandong province has a pancake.
\ No newline at end of file
+Shandong province has a pancake.