Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
304 lines
9.5 KiB
Python
304 lines
9.5 KiB
Python
"""
|
||
Tests for optimized RAG adapter with retry and monitoring
|
||
"""
|
||
|
||
import pytest
|
||
import time
|
||
from unittest.mock import Mock, patch
|
||
|
||
from rag_evaluation.evaluation.rag_adapter import (
|
||
RetryConfig,
|
||
retry_with_exponential_backoff,
|
||
HTTPRAGRetriever,
|
||
HTTPRAGGenerator,
|
||
RAGEvaluationAdapter,
|
||
MockRAGRetriever,
|
||
MockRAGGenerator
|
||
)
|
||
|
||
|
||
class TestRetryConfig:
|
||
"""测试重试配置"""
|
||
|
||
def test_default_config(self):
|
||
"""测试默认配置"""
|
||
config = RetryConfig()
|
||
assert config.max_retries == 3
|
||
assert config.initial_delay == 1.0
|
||
assert config.max_delay == 60.0
|
||
assert config.exponential_base == 2.0
|
||
assert config.timeout == 30
|
||
|
||
def test_custom_config(self):
|
||
"""测试自定义配置"""
|
||
config = RetryConfig(
|
||
max_retries=5,
|
||
initial_delay=0.5,
|
||
max_delay=30.0,
|
||
exponential_base=3.0,
|
||
timeout=60
|
||
)
|
||
assert config.max_retries == 5
|
||
assert config.initial_delay == 0.5
|
||
assert config.max_delay == 30.0
|
||
assert config.exponential_base == 3.0
|
||
assert config.timeout == 60
|
||
|
||
|
||
class TestRetryWithExponentialBackoff:
|
||
"""测试指数退避重试"""
|
||
|
||
def test_success_on_first_try(self):
|
||
"""测试第一次尝试成功"""
|
||
call_count = [0]
|
||
|
||
def func():
|
||
call_count[0] += 1
|
||
return "success"
|
||
|
||
config = RetryConfig(max_retries=3, initial_delay=0.1)
|
||
result = retry_with_exponential_backoff(func, config)
|
||
|
||
assert result == "success"
|
||
assert call_count[0] == 1
|
||
|
||
def test_success_after_retries(self):
|
||
"""测试重试后成功"""
|
||
call_count = [0]
|
||
|
||
def func():
|
||
call_count[0] += 1
|
||
if call_count[0] < 3:
|
||
raise ValueError("Temporary error")
|
||
return "success"
|
||
|
||
config = RetryConfig(max_retries=3, initial_delay=0.1)
|
||
result = retry_with_exponential_backoff(func, config)
|
||
|
||
assert result == "success"
|
||
assert call_count[0] == 3
|
||
|
||
def test_failure_after_all_retries(self):
|
||
"""测试所有重试后失败"""
|
||
call_count = [0]
|
||
|
||
def func():
|
||
call_count[0] += 1
|
||
raise ValueError("Permanent error")
|
||
|
||
config = RetryConfig(max_retries=2, initial_delay=0.1)
|
||
|
||
with pytest.raises(ValueError, match="Permanent error"):
|
||
retry_with_exponential_backoff(func, config)
|
||
|
||
assert call_count[0] == 3 # 初始尝试 + 2次重试
|
||
|
||
def test_exponential_backoff_timing(self):
|
||
"""测试指数退避时间"""
|
||
call_times = []
|
||
|
||
def func():
|
||
call_times.append(time.time())
|
||
if len(call_times) < 3:
|
||
raise ValueError("Retry")
|
||
return "success"
|
||
|
||
config = RetryConfig(max_retries=3, initial_delay=0.1, exponential_base=2.0)
|
||
retry_with_exponential_backoff(func, config)
|
||
|
||
# 验证延迟时间递增
|
||
assert len(call_times) == 3
|
||
delay1 = call_times[1] - call_times[0]
|
||
delay2 = call_times[2] - call_times[1]
|
||
|
||
# 第二次延迟应该大约是第一次的2倍
|
||
assert delay2 > delay1 * 1.5
|
||
|
||
|
||
class TestHTTPRAGRetrieverOptimized:
|
||
"""测试优化后的HTTP检索器"""
|
||
|
||
def test_initialization_with_retry_config(self):
|
||
"""测试带重试配置的初始化"""
|
||
config = RetryConfig(max_retries=5)
|
||
retriever = HTTPRAGRetriever(
|
||
endpoint="http://test.com/retrieve",
|
||
api_key="test_key",
|
||
retry_config=config
|
||
)
|
||
|
||
assert retriever.endpoint == "http://test.com/retrieve"
|
||
assert retriever.api_key == "test_key"
|
||
assert retriever.retry_config.max_retries == 5
|
||
|
||
def test_stats_tracking(self):
|
||
"""测试统计信息跟踪"""
|
||
retriever = HTTPRAGRetriever(endpoint="http://test.com/retrieve")
|
||
|
||
# 初始统计
|
||
stats = retriever.get_stats()
|
||
assert stats['total_requests'] == 0
|
||
assert stats['successful_requests'] == 0
|
||
assert stats['failed_requests'] == 0
|
||
|
||
@patch('requests.post')
|
||
def test_successful_retrieval_with_stats(self, mock_post):
|
||
"""测试成功检索并记录统计"""
|
||
mock_response = Mock()
|
||
mock_response.json.return_value = {
|
||
'contexts': [
|
||
{'content': 'test context', 'score': 0.9}
|
||
]
|
||
}
|
||
mock_post.return_value = mock_response
|
||
|
||
retriever = HTTPRAGRetriever(endpoint="http://test.com/retrieve")
|
||
result = retriever.retrieve("test query")
|
||
|
||
assert len(result) == 1
|
||
assert result[0]['content'] == 'test context'
|
||
|
||
# 验证统计
|
||
stats = retriever.get_stats()
|
||
assert stats['total_requests'] == 1
|
||
assert stats['successful_requests'] == 1
|
||
assert stats['failed_requests'] == 0
|
||
assert stats['avg_latency_ms'] >= 0 # 可能为0(mock很快)
|
||
|
||
|
||
class TestHTTPRAGGeneratorOptimized:
|
||
"""测试优化后的HTTP生成器"""
|
||
|
||
def test_initialization_with_custom_timeout(self):
|
||
"""测试自定义超时初始化"""
|
||
config = RetryConfig(timeout=120)
|
||
generator = HTTPRAGGenerator(
|
||
endpoint="http://test.com/generate",
|
||
retry_config=config
|
||
)
|
||
|
||
assert generator.retry_config.timeout == 120
|
||
|
||
@patch('requests.post')
|
||
def test_successful_generation_with_stats(self, mock_post):
|
||
"""测试成功生成并记录统计"""
|
||
mock_response = Mock()
|
||
mock_response.json.return_value = {'answer': 'test answer'}
|
||
mock_post.return_value = mock_response
|
||
|
||
generator = HTTPRAGGenerator(endpoint="http://test.com/generate")
|
||
result = generator.generate("test query", ["context1", "context2"])
|
||
|
||
assert result == 'test answer'
|
||
|
||
# 验证统计
|
||
stats = generator.get_stats()
|
||
assert stats['total_requests'] == 1
|
||
assert stats['successful_requests'] == 1
|
||
assert stats['avg_latency_ms'] >= 0 # 可能为0(mock很快)
|
||
|
||
|
||
class TestRAGEvaluationAdapterOptimized:
|
||
"""测试优化后的RAG评估适配器"""
|
||
|
||
def test_adapter_with_stats(self):
|
||
"""测试适配器统计功能"""
|
||
retriever = MockRAGRetriever()
|
||
generator = MockRAGGenerator()
|
||
adapter = RAGEvaluationAdapter(retriever, generator)
|
||
|
||
# 初始统计
|
||
stats = adapter.get_stats()
|
||
assert stats['total_evaluations'] == 0
|
||
assert stats['successful_evaluations'] == 0
|
||
|
||
# 执行评估
|
||
result = adapter.evaluate_question("test question")
|
||
|
||
assert result['question'] == "test question"
|
||
assert 'retrieved_contexts' in result
|
||
assert 'generated_answer' in result
|
||
|
||
# 验证统计
|
||
stats = adapter.get_stats()
|
||
assert stats['total_evaluations'] == 1
|
||
assert stats['successful_evaluations'] == 1
|
||
assert stats['avg_retrieval_time_ms'] >= 0
|
||
assert stats['avg_generation_time_ms'] >= 0
|
||
|
||
def test_adapter_reset_stats(self):
|
||
"""测试重置统计"""
|
||
retriever = MockRAGRetriever()
|
||
generator = MockRAGGenerator()
|
||
adapter = RAGEvaluationAdapter(retriever, generator)
|
||
|
||
# 执行一些评估
|
||
adapter.evaluate_question("test 1")
|
||
adapter.evaluate_question("test 2")
|
||
|
||
stats_before = adapter.get_stats()
|
||
assert stats_before['total_evaluations'] == 2
|
||
|
||
# 重置统计
|
||
adapter.reset_stats()
|
||
|
||
stats_after = adapter.get_stats()
|
||
assert stats_after['total_evaluations'] == 0
|
||
assert stats_after['successful_evaluations'] == 0
|
||
|
||
def test_adapter_error_handling(self):
|
||
"""测试适配器错误处理"""
|
||
# 创建会抛出异常的mock
|
||
retriever = Mock()
|
||
retriever.retrieve.side_effect = Exception("Retrieval error")
|
||
|
||
generator = MockRAGGenerator()
|
||
adapter = RAGEvaluationAdapter(retriever, generator)
|
||
|
||
# 应该抛出异常
|
||
with pytest.raises(Exception, match="Retrieval error"):
|
||
adapter.evaluate_question("test question")
|
||
|
||
# 验证失败统计
|
||
stats = adapter.get_stats()
|
||
assert stats['total_evaluations'] == 1
|
||
assert stats['failed_evaluations'] == 1
|
||
assert stats['successful_evaluations'] == 0
|
||
|
||
|
||
class TestIntegrationWithOptimizations:
|
||
"""集成测试:验证所有优化功能"""
|
||
|
||
def test_end_to_end_with_monitoring(self):
|
||
"""端到端测试:包含监控和统计"""
|
||
retriever = MockRAGRetriever()
|
||
generator = MockRAGGenerator()
|
||
adapter = RAGEvaluationAdapter(retriever, generator)
|
||
|
||
# 执行多次评估
|
||
questions = ["Q1", "Q2", "Q3", "Q4", "Q5"]
|
||
results = []
|
||
|
||
for q in questions:
|
||
result = adapter.evaluate_question(q)
|
||
results.append(result)
|
||
|
||
# 验证所有结果
|
||
assert len(results) == 5
|
||
|
||
# 验证统计信息
|
||
stats = adapter.get_stats()
|
||
assert stats['total_evaluations'] == 5
|
||
assert stats['successful_evaluations'] == 5
|
||
assert stats['failed_evaluations'] == 0
|
||
assert stats['avg_retrieval_time_ms'] >= 0
|
||
assert stats['avg_generation_time_ms'] >= 0
|
||
assert stats['avg_total_time_ms'] >= 0
|
||
|
||
print(f"\n性能统计:")
|
||
print(f" 总评估数: {stats['total_evaluations']}")
|
||
print(f" 成功数: {stats['successful_evaluations']}")
|
||
print(f" 平均检索时间: {stats['avg_retrieval_time_ms']:.2f}ms")
|
||
print(f" 平均生成时间: {stats['avg_generation_time_ms']:.2f}ms")
|
||
print(f" 平均总时间: {stats['avg_total_time_ms']:.2f}ms")
|