287 lines
8.5 KiB
Python
287 lines
8.5 KiB
Python
"""
|
||||
|
|
Unit tests for parallel execution module
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
import pytest
|
|||
|
|
import time
|
|||
|
|
from concurrent.futures import ThreadPoolExecutor
|
|||
|
|
|
|||
|
|
from rag_evaluation.evaluation.parallel_executor import (
|
|||
|
|
ParallelExecutor,
|
|||
|
|
ParallelConfig,
|
|||
|
|
BatchEvaluator
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class TestParallelConfig:
|
|||
|
|
"""测试并行配置"""
|
|||
|
|
|
|||
|
|
def test_default_config(self):
|
|||
|
|
"""测试默认配置"""
|
|||
|
|
config = ParallelConfig()
|
|||
|
|
|
|||
|
|
assert config.max_workers == 5
|
|||
|
|
assert config.use_processes is False
|
|||
|
|
assert config.chunk_size == 1
|
|||
|
|
|
|||
|
|
def test_custom_config(self):
|
|||
|
|
"""测试自定义配置"""
|
|||
|
|
config = ParallelConfig(
|
|||
|
|
max_workers=10,
|
|||
|
|
use_processes=True,
|
|||
|
|
chunk_size=5
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
assert config.max_workers == 10
|
|||
|
|
assert config.use_processes is True
|
|||
|
|
assert config.chunk_size == 5
|
|||
|
|
|
|||
|
|
|
|||
|
|
class TestParallelExecutor:
|
|||
|
|
"""测试并行执行器"""
|
|||
|
|
|
|||
|
|
@pytest.fixture
|
|||
|
|
def executor(self):
|
|||
|
|
"""创建并行执行器"""
|
|||
|
|
config = ParallelConfig(max_workers=3)
|
|||
|
|
return ParallelExecutor(config)
|
|||
|
|
|
|||
|
|
def test_execute_empty_tasks(self, executor):
|
|||
|
|
"""测试执行空任务列表"""
|
|||
|
|
results = executor.execute_tasks([], lambda x: x * 2)
|
|||
|
|
assert results == []
|
|||
|
|
|
|||
|
|
def test_execute_single_task(self, executor):
|
|||
|
|
"""测试执行单个任务"""
|
|||
|
|
def task_func(x):
|
|||
|
|
return x * 2
|
|||
|
|
|
|||
|
|
results = executor.execute_tasks([5], task_func)
|
|||
|
|
assert results == [10]
|
|||
|
|
|
|||
|
|
def test_execute_multiple_tasks(self, executor):
|
|||
|
|
"""测试执行多个任务"""
|
|||
|
|
def task_func(x):
|
|||
|
|
return x * 2
|
|||
|
|
|
|||
|
|
tasks = [1, 2, 3, 4, 5]
|
|||
|
|
results = executor.execute_tasks(tasks, task_func)
|
|||
|
|
|
|||
|
|
assert len(results) == 5
|
|||
|
|
assert set(results) == {2, 4, 6, 8, 10}
|
|||
|
|
|
|||
|
|
def test_execute_with_delay(self, executor):
|
|||
|
|
"""测试带延迟的任务执行"""
|
|||
|
|
def delayed_task(x):
|
|||
|
|
time.sleep(0.1)
|
|||
|
|
return x
|
|||
|
|
|
|||
|
|
tasks = [1, 2, 3]
|
|||
|
|
start_time = time.time()
|
|||
|
|
results = executor.execute_tasks(tasks, delayed_task)
|
|||
|
|
elapsed_time = time.time() - start_time
|
|||
|
|
|
|||
|
|
# 并行执行应该比串行快
|
|||
|
|
assert len(results) == 3
|
|||
|
|
# 3个任务串行需要0.3秒,并行应该小于0.3秒
|
|||
|
|
assert elapsed_time < 0.25
|
|||
|
|
|
|||
|
|
def test_execute_with_exception(self, executor):
|
|||
|
|
"""测试任务执行中的异常处理"""
|
|||
|
|
def failing_task(x):
|
|||
|
|
if x == 2:
|
|||
|
|
raise ValueError("Test error")
|
|||
|
|
return x * 2
|
|||
|
|
|
|||
|
|
tasks = [1, 2, 3, 4, 5]
|
|||
|
|
results = executor.execute_tasks(tasks, failing_task)
|
|||
|
|
|
|||
|
|
# 应该返回成功的结果
|
|||
|
|
assert len(results) == 4 # 排除x=2的任务
|
|||
|
|
assert 2 not in [r // 2 for r in results] # x=2的结果不应该存在
|
|||
|
|
|
|||
|
|
def test_execute_with_progress(self, executor):
|
|||
|
|
"""测试带进度回调的执行"""
|
|||
|
|
progress_updates = []
|
|||
|
|
|
|||
|
|
def progress_callback(current, total):
|
|||
|
|
progress_updates.append((current, total))
|
|||
|
|
|
|||
|
|
def task_func(x):
|
|||
|
|
return x * 2
|
|||
|
|
|
|||
|
|
tasks = [1, 2, 3]
|
|||
|
|
results = executor.execute_with_progress(
|
|||
|
|
tasks=tasks,
|
|||
|
|
task_func=task_func,
|
|||
|
|
progress_callback=progress_callback
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
assert len(results) == 3
|
|||
|
|
assert len(progress_updates) == 3
|
|||
|
|
assert progress_updates[-1] == (3, 3) # 最后一次更新应该是3/3
|
|||
|
|
|
|||
|
|
|
|||
|
|
class TestBatchEvaluator:
|
|||
|
|
"""测试批量评估器"""
|
|||
|
|
|
|||
|
|
@pytest.fixture
|
|||
|
|
def evaluator(self):
|
|||
|
|
"""创建批量评估器"""
|
|||
|
|
config = ParallelConfig(max_workers=3)
|
|||
|
|
return BatchEvaluator(config)
|
|||
|
|
|
|||
|
|
def test_evaluate_empty_batch(self, evaluator):
|
|||
|
|
"""测试空批次评估"""
|
|||
|
|
results = evaluator.evaluate_questions_batch([], lambda x: x)
|
|||
|
|
assert results == []
|
|||
|
|
|
|||
|
|
def test_evaluate_small_batch(self, evaluator):
|
|||
|
|
"""测试小批次评估(小于chunk_size)"""
|
|||
|
|
def eval_func(item):
|
|||
|
|
return item['value'] * 2
|
|||
|
|
|
|||
|
|
batch = [{'value': 1}, {'value': 2}]
|
|||
|
|
results = evaluator.evaluate_questions_batch(batch, eval_func)
|
|||
|
|
|
|||
|
|
assert len(results) == 2
|
|||
|
|
assert results[0] == 2
|
|||
|
|
assert results[1] == 4
|
|||
|
|
|
|||
|
|
def test_evaluate_large_batch(self, evaluator):
|
|||
|
|
"""测试大批次评估(大于chunk_size)"""
|
|||
|
|
def eval_func(item):
|
|||
|
|
return item['value'] * 2
|
|||
|
|
|
|||
|
|
# 创建10个项目,chunk_size=1
|
|||
|
|
batch = [{'value': i} for i in range(10)]
|
|||
|
|
results = evaluator.evaluate_questions_batch(
|
|||
|
|
batch,
|
|||
|
|
eval_func,
|
|||
|
|
batch_size=3
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
assert len(results) == 10
|
|||
|
|
# 由于并行执行顺序不确定,使用集合比较
|
|||
|
|
expected_set = {i * 2 for i in range(10)}
|
|||
|
|
results_set = set(results)
|
|||
|
|
assert results_set == expected_set
|
|||
|
|
|
|||
|
|
def test_evaluate_with_retry_success(self, evaluator):
|
|||
|
|
"""测试带重试的评估(全部成功)"""
|
|||
|
|
call_count = {}
|
|||
|
|
|
|||
|
|
def eval_func(item):
|
|||
|
|
key = item['key']
|
|||
|
|
call_count[key] = call_count.get(key, 0) + 1
|
|||
|
|
|
|||
|
|
# 前两次失败,第三次成功
|
|||
|
|
if call_count[key] < 3:
|
|||
|
|
raise ValueError(f"Temporary error for {key}")
|
|||
|
|
|
|||
|
|
return key
|
|||
|
|
|
|||
|
|
batch = [{'key': 'a'}, {'key': 'b'}]
|
|||
|
|
results = evaluator.evaluate_with_retry(batch, eval_func, max_retries=3)
|
|||
|
|
|
|||
|
|
assert len(results) == 2
|
|||
|
|
assert 'a' in results
|
|||
|
|
assert 'b' in results
|
|||
|
|
|
|||
|
|
def test_evaluate_with_retry_partial_failure(self, evaluator):
|
|||
|
|
"""测试带重试的评估(部分失败)"""
|
|||
|
|
def always_failing_eval(item):
|
|||
|
|
raise ValueError("Always fails")
|
|||
|
|
|
|||
|
|
batch = [{'key': 'a'}, {'key': 'b'}]
|
|||
|
|
results = evaluator.evaluate_with_retry(batch, always_failing_eval, max_retries=2)
|
|||
|
|
|
|||
|
|
# 全部失败,应该返回空结果
|
|||
|
|
assert len(results) == 0
|
|||
|
|
|
|||
|
|
|
|||
|
|
class TestPerformanceComparison:
|
|||
|
|
"""性能对比测试"""
|
|||
|
|
|
|||
|
|
def test_parallel_vs_sequential(self):
|
|||
|
|
"""测试并行与串行执行的性能对比"""
|
|||
|
|
def slow_task(x):
|
|||
|
|
time.sleep(0.1)
|
|||
|
|
return x * 2
|
|||
|
|
|
|||
|
|
tasks = list(range(10))
|
|||
|
|
|
|||
|
|
# 串行执行
|
|||
|
|
start = time.time()
|
|||
|
|
sequential_results = [slow_task(t) for t in tasks]
|
|||
|
|
sequential_time = time.time() - start
|
|||
|
|
|
|||
|
|
# 并行执行
|
|||
|
|
config = ParallelConfig(max_workers=5)
|
|||
|
|
executor = ParallelExecutor(config)
|
|||
|
|
start = time.time()
|
|||
|
|
parallel_results = executor.execute_tasks(tasks, slow_task)
|
|||
|
|
parallel_time = time.time() - start
|
|||
|
|
|
|||
|
|
# 验证结果一致(使用集合比较,因为顺序可能不同)
|
|||
|
|
assert set(sequential_results) == set(parallel_results)
|
|||
|
|
|
|||
|
|
# 并行应该更快(至少快2倍)
|
|||
|
|
assert parallel_time < sequential_time / 2
|
|||
|
|
|
|||
|
|
print(f"\nSequential time: {sequential_time:.2f}s")
|
|||
|
|
print(f"Parallel time: {parallel_time:.2f}s")
|
|||
|
|
print(f"Speedup: {sequential_time / parallel_time:.2f}x")
|
|||
|
|
|
|||
|
|
def test_different_worker_counts(self):
|
|||
|
|
"""测试不同工作线程数的性能"""
|
|||
|
|
def moderate_task(x):
|
|||
|
|
time.sleep(0.05)
|
|||
|
|
return x
|
|||
|
|
|
|||
|
|
tasks = list(range(20))
|
|||
|
|
worker_counts = [1, 2, 4, 8]
|
|||
|
|
times = []
|
|||
|
|
|
|||
|
|
for workers in worker_counts:
|
|||
|
|
config = ParallelConfig(max_workers=workers)
|
|||
|
|
executor = ParallelExecutor(config)
|
|||
|
|
|
|||
|
|
start = time.time()
|
|||
|
|
executor.execute_tasks(tasks, moderate_task)
|
|||
|
|
elapsed = time.time() - start
|
|||
|
|
times.append(elapsed)
|
|||
|
|
|
|||
|
|
print(f"\nWorker count performance:")
|
|||
|
|
for workers, elapsed in zip(worker_counts, times):
|
|||
|
|
print(f" {workers} workers: {elapsed:.2f}s")
|
|||
|
|
|
|||
|
|
# 8个工作线程应该比1个工作线程快
|
|||
|
|
assert times[-1] < times[0] * 0.5
|
|||
|
|
|
|||
|
|
|
|||
|
|
class TestThreadSafety:
|
|||
|
|
"""线程安全测试"""
|
|||
|
|
|
|||
|
|
def test_concurrent_database_operations(self):
|
|||
|
|
"""测试并发数据库操作的安全性"""
|
|||
|
|
# 模拟数据库操作
|
|||
|
|
results = []
|
|||
|
|
lock_tests = []
|
|||
|
|
|
|||
|
|
def db_operation(task_id):
|
|||
|
|
# 模拟数据库操作
|
|||
|
|
time.sleep(0.01)
|
|||
|
|
result = f"result_{task_id}"
|
|||
|
|
results.append(result)
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
config = ParallelConfig(max_workers=10)
|
|||
|
|
executor = ParallelExecutor(config)
|
|||
|
|
|
|||
|
|
tasks = list(range(50))
|
|||
|
|
results_list = executor.execute_tasks(tasks, db_operation)
|
|||
|
|
|
|||
|
|
# 验证所有任务都完成
|
|||
|
|
assert len(results_list) == 50
|
|||
|
|
assert len(set(results_list)) == 50 # 所有结果都是唯一的
|