Files
auto-ragas/rag_evaluation/test_framework.py
T
2026-01-16 16:01:39 +08:00

360 lines
11 KiB
Python

"""
Test script for Phase 1 functionality
"""
import sys
import os
from pathlib import Path
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))
# Set UTF-8 encoding for Windows
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
def test_phase1():
"""Test Phase 1 - Testset Generation"""
print("=" * 70)
print("Testing Phase 1: Testset Generation")
print("=" * 70)
# Test 1: Configuration loading
print("\n[Test 1] Configuration Loading")
print("-" * 70)
try:
from rag_evaluation.core.config import Config
# Test default config
config = Config()
print("✓ Default config created")
print(f" - Default testset size: {config.testset.default_size}")
print(f" - Database host: {config.database.host}")
# Test config from file
config_file = Path("config.example.yaml")
if config_file.exists():
config = Config.from_file(str(config_file))
print("✓ Config loaded from file")
else:
print("⚠ config.example.yaml not found, using defaults")
except Exception as e:
print(f"✗ Configuration test failed: {e}")
return False
# Test 2: Document loading
print("\n[Test 2] Document Loading")
print("-" * 70)
try:
from rag_evaluation.testset.document_loader import (
TextLoader, MarkdownLoader, load_documents
)
# Create test files
test_dir = Path("./data/test_docs")
test_dir.mkdir(parents=True, exist_ok=True)
test_txt = test_dir / "test.txt"
with open(test_txt, 'w', encoding='utf-8') as f:
f.write("This is a test document for RAG evaluation.")
test_md = test_dir / "test.md"
with open(test_md, 'w', encoding='utf-8') as f:
f.write("# Test Markdown\n\nThis is a markdown test document.")
# Test text loader
loader = TextLoader(str(test_txt))
docs = loader.load()
print(f"✓ TextLoader: loaded {len(docs)} document(s)")
print(f" - File size: {loader.get_file_size()} bytes")
# Test markdown loader
loader = MarkdownLoader(str(test_md))
docs = loader.load()
print(f"✓ MarkdownLoader: loaded {len(docs)} document(s)")
# Test batch loading
docs = load_documents([str(test_txt), str(test_md)])
print(f"✓ Batch loading: loaded {len(docs)} document(s)")
except Exception as e:
print(f"✗ Document loading test failed: {e}")
import traceback
traceback.print_exc()
return False
# Test 3: Sampling and chunking
print("\n[Test 3] Sampling and Chunking")
print("-" * 70)
try:
from rag_evaluation.testset.sampling import (
SamplingStrategy, DocumentChunker
)
from rag_evaluation.testset.document_loader import Document
# Test sampling strategy
sampling = SamplingStrategy(config.testset)
# Test different file sizes
small_size = 500 * 1024 # 500KB
medium_size = 5 * 1024 * 1024 # 5MB
large_size = 50 * 1024 * 1024 # 50MB
print(f"✓ Sampling rates:")
print(f" - Small file (500KB): {sampling.get_sampling_rate(small_size):.2f}")
print(f" - Medium file (5MB): {sampling.get_sampling_rate(medium_size):.2f}")
print(f" - Large file (50MB): {sampling.get_sampling_rate(large_size):.2f}")
# Test chunking
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
test_doc = Document(
content="This is a test document. " * 20,
metadata={'source': 'test.txt'}
)
chunks = chunker.chunk_document(test_doc)
print(f"✓ Chunking: created {len(chunks)} chunks")
except Exception as e:
print(f"✗ Sampling/chunking test failed: {e}")
import traceback
traceback.print_exc()
return False
# Test 4: Testset generation
print("\n[Test 4] Testset Generation")
print("-" * 70)
try:
from rag_evaluation.testset.generator import TestsetGenerator
generator = TestsetGenerator(config)
# Generate testset
testset = generator.generate(
knowledge_base_id="test-kb-001",
file_paths=[str(test_txt), str(test_md)],
test_size=5,
name="Test Testset"
)
print(f"✓ Testset generated:")
print(f" - ID: {testset['id']}")
print(f" - Name: {testset['name']}")
print(f" - Questions: {len(testset['questions'])}")
print(f" - Question types: {set(q['type'] for q in testset['questions'])}")
# Test save/load
file_path = generator.save_testset(testset)
print(f"✓ Testset saved to: {file_path}")
loaded_testset = generator.load_testset(testset['id'])
print(f"✓ Testset loaded: {loaded_testset['name']}")
assert loaded_testset['id'] == testset['id'], "Testset ID mismatch"
print("✓ Save/load verification passed")
except Exception as e:
print(f"✗ Testset generation test failed: {e}")
import traceback
traceback.print_exc()
return False
# Test 5: Database operations
print("\n[Test 5] Database Operations")
print("-" * 70)
try:
from rag_evaluation.storage.database import DatabaseManager
db_manager = DatabaseManager(config.database)
# Test connection
print("⚠ Skipping database test (requires MySQL connection)")
print(" To test database:")
print(" 1. Ensure MySQL is running")
print(" 2. Update config.yaml with correct credentials")
print(" 3. Run: python example.py")
except Exception as e:
print(f"⚠ Database test skipped: {e}")
# Test 6: Utility functions
print("\n[Test 6] Utility Functions")
print("-" * 70)
try:
from rag_evaluation.utils.helpers import (
generate_id, generate_biz_seq, generate_sys_seq,
format_datetime, calculate_file_size_mb
)
# Test ID generation
id1 = generate_id("test")
id2 = generate_id("test")
assert len(id1) == 32, "ID should be 32 characters"
assert id1 != id2, "IDs should be unique"
print(f"✓ ID generation: {id1[:16]}...")
# Test sequence generation
biz_seq = generate_biz_seq("TEST")
sys_seq = generate_sys_seq("TEST")
print(f"✓ Business seq: {biz_seq}")
print(f"✓ System seq: {sys_seq}")
# Test datetime formatting
dt_str = format_datetime()
print(f"✓ Datetime format: {dt_str}")
# Test file size calculation
size_mb = calculate_file_size_mb(5 * 1024 * 1024)
assert size_mb == 5.0, "File size calculation error"
print(f"✓ File size calculation: 5MB")
except Exception as e:
print(f"✗ Utility functions test failed: {e}")
import traceback
traceback.print_exc()
return False
print("\n" + "=" * 70)
print("✅ Phase 1 Tests Completed Successfully!")
print("=" * 70)
return True
def test_phase2():
"""Test Phase 2 - Evaluation Execution"""
print("\n" + "=" * 70)
print("Testing Phase 2: Evaluation Execution")
print("=" * 70)
# Test 1: RAG Adapters
print("\n[Test 1] RAG Adapters")
print("-" * 70)
try:
from rag_evaluation.evaluation import (
MockRAGRetriever, MockRAGGenerator, RAGEvaluationAdapter
)
# Test mock retriever
retriever = MockRAGRetriever()
contexts = retriever.retrieve("test query", top_k=3)
print(f"✓ MockRAGRetriever: retrieved {len(contexts)} contexts")
assert len(contexts) == 3, "Should retrieve 3 contexts"
# Test mock generator
generator = MockRAGGenerator()
answer = generator.generate("test query", ["context1", "context2"])
print(f"✓ MockRAGGenerator: generated answer")
assert len(answer) > 0, "Should generate non-empty answer"
# Test adapter
adapter = RAGEvaluationAdapter(retriever, generator)
result = adapter.evaluate_question("What is RAG?")
print(f"✓ RAGEvaluationAdapter:")
print(f" - Retrieved contexts: {len(result['retrieved_contexts'])}")
print(f" - Generated answer: {result['generated_answer'][:50]}...")
print(f" - Retrieval time: {result['retrieval_time_ms']}ms")
print(f" - Generation time: {result['generation_time_ms']}ms")
except Exception as e:
print(f"✗ RAG adapters test failed: {e}")
import traceback
traceback.print_exc()
return False
# Test 2: Metrics calculation
print("\n[Test 2] Metrics Calculation")
print("-" * 70)
try:
from rag_evaluation.evaluation import MetricsCalculator
calculator = MetricsCalculator()
# Test data
question = "What is RAG?"
retrieved = ["doc1", "doc2", "doc3"]
ground_truth_contexts = ["doc1", "doc4"]
generated_answer = "RAG is a retrieval augmented generation system"
ground_truth_answer = "RAG combines retrieval and generation"
metrics = calculator.calculate_all(
question=question,
retrieved_contexts=retrieved,
generated_answer=generated_answer,
ground_truth_contexts=ground_truth_contexts,
ground_truth_answer=ground_truth_answer
)
print("✓ Metrics calculated:")
for metric_name, value in metrics.items():
print(f" - {metric_name}: {value:.3f}")
# Verify all metrics are present
expected_metrics = [
'context_recall', 'context_precision', 'mrr', 'ndcg',
'faithfulness', 'answer_relevancy', 'correctness'
]
for metric in expected_metrics:
assert metric in metrics, f"Missing metric: {metric}"
print("✓ All 7 metrics present")
except Exception as e:
print(f"✗ Metrics calculation test failed: {e}")
import traceback
traceback.print_exc()
return False
# Test 3: Evaluation executor (without database)
print("\n[Test 3] Evaluation Executor")
print("-" * 70)
try:
print("⚠ Skipping executor test (requires database)")
print(" To test evaluation executor:")
print(" 1. Ensure MySQL is running")
print(" 2. Update config.yaml with correct credentials")
print(" 3. Run: python example_phase2.py")
except Exception as e:
print(f"⚠ Executor test skipped: {e}")
print("\n" + "=" * 70)
print("✅ Phase 2 Tests Completed Successfully!")
print("=" * 70)
return True
def main():
"""Run all tests"""
print("\n" + "=" * 70)
print("RAG Evaluation Framework - Test Suite")
print("=" * 70)
# Run Phase 1 tests
phase1_passed = test_phase1()
# Run Phase 2 tests
phase2_passed = test_phase2()
# Summary
print("\n" + "=" * 70)
print("Test Summary")
print("=" * 70)
print(f"Phase 1: {'✅ PASSED' if phase1_passed else '✗ FAILED'}")
print(f"Phase 2: {'✅ PASSED' if phase2_passed else '✗ FAILED'}")
if phase1_passed and phase2_passed:
print("\n🎉 All tests passed!")
return 0
else:
print("\n⚠ Some tests failed. Please check the output above.")
return 1
if __name__ == "__main__":
sys.exit(main())