""" Unit tests for evaluation cache module """ import pytest import tempfile import shutil import time from pathlib import Path from rag_evaluation.evaluation.cache import ( CacheKey, EvaluationCache, CachedEvaluationExecutor ) @pytest.fixture def temp_cache_dir(): """创建临时缓存目录""" temp_dir = tempfile.mkdtemp() yield temp_dir # 清理临时目录 shutil.rmtree(temp_dir, ignore_errors=True) @pytest.fixture def cache(temp_cache_dir): """创建缓存管理器""" return EvaluationCache(cache_dir=temp_cache_dir, ttl_seconds=60) class TestCacheKey: """测试缓存键生成""" def test_generate_question_key_basic(self): """测试基本问题键生成""" key1 = CacheKey.generate_question_key("什么是机器学习?") key2 = CacheKey.generate_question_key("什么是机器学习?") key3 = CacheKey.generate_question_key("什么是深度学习?") # 相同问题应该生成相同的键 assert key1 == key2 # 不同问题应该生成不同的键 assert key1 != key3 def test_generate_question_key_case_insensitive(self): """测试问题键的大小写不敏感性""" key1 = CacheKey.generate_question_key("What is Machine Learning?") key2 = CacheKey.generate_question_key("WHAT IS MACHINE LEARNING?") key3 = CacheKey.generate_question_key("what is machine learning?") # 应该都生成相同的键(因为转小写) assert key1 == key2 == key3 def test_generate_question_key_with_whitespace(self): """测试问题键的空格处理""" key1 = CacheKey.generate_question_key("什么是机器学习") key2 = CacheKey.generate_question_key(" 什么是机器学习 ") key3 = CacheKey.generate_question_key("什么是 机器学习") # 去除前后空格后应该相同 assert key1 == key2 # 中间空格不同会生成不同键 assert key1 != key3 def test_generate_question_key_with_config(self): """测试带配置的问题键生成""" key1 = CacheKey.generate_question_key( "测试问题", rag_config={"model": "gpt-4"} ) key2 = CacheKey.generate_question_key( "测试问题", rag_config={"model": "gpt-4"} ) key3 = CacheKey.generate_question_key( "测试问题", rag_config={"model": "gpt-3.5"} ) # 相同配置生成相同键 assert key1 == key2 # 不同配置生成不同键 assert key1 != key3 def test_generate_testset_key(self): """测试测评集键生成""" key1 = CacheKey.generate_testset_key("ts-001", "kb-001") key2 = CacheKey.generate_testset_key("ts-001", "kb-001") key3 = CacheKey.generate_testset_key("ts-002", "kb-001") assert key1 == key2 assert key1 != key3 class TestEvaluationCache: """测试评估缓存""" def test_set_and_get(self, cache): """测试设置和获取缓存""" cache_key = "test_key_001" data = {"result": "test_result", "score": 0.95} # 设置缓存 cache.set(cache_key, data) # 获取缓存 retrieved = cache.get(cache_key) assert retrieved is not None assert retrieved["result"] == "test_result" assert retrieved["score"] == 0.95 def test_get_nonexistent_key(self, cache): """测试获取不存在的键""" result = cache.get("nonexistent_key") assert result is None def test_cache_expiration(self, temp_cache_dir): """测试缓存过期""" # 创建TTL为1秒的缓存 short_lived_cache = EvaluationCache( cache_dir=temp_cache_dir, ttl_seconds=1 ) cache_key = "expiring_key" data = {"result": "will_expire"} short_lived_cache.set(cache_key, data) # 立即获取应该成功 assert short_lived_cache.get(cache_key) is not None # 等待2秒后应该过期 time.sleep(2) assert short_lived_cache.get(cache_key) is None def test_delete_cache(self, cache): """测试删除缓存""" cache_key = "delete_key" data = {"result": "to_delete"} cache.set(cache_key, data) assert cache.get(cache_key) is not None # 删除缓存 success = cache.delete(cache_key) assert success is True assert cache.get(cache_key) is None def test_delete_nonexistent_cache(self, cache): """测试删除不存在的缓存""" success = cache.delete("nonexistent_key") assert success is False def test_clear_all_cache(self, cache): """测试清空所有缓存""" # 添加多个缓存项 for i in range(5): cache.set(f"key_{i}", {"data": i}) # 清空所有缓存 count = cache.clear() assert count == 5 # 验证所有缓存都被删除 for i in range(5): assert cache.get(f"key_{i}") is None def test_clear_expired_cache(self, cache): """测试清理过期缓存""" # 这个测试需要较短的TTL pass # 由于时间限制,跳过实时测试 def test_cache_stats(self, cache): """测试缓存统计""" # 添加一些缓存 for i in range(3): cache.set(f"key_{i}", {"data": i}) stats = cache.get_stats() assert stats['total_files'] == 3 assert stats['active_files'] == 3 assert stats['expired_files'] == 0 assert stats['ttl_seconds'] == 60 def test_cache_persistence(self, temp_cache_dir): """测试缓存持久化""" cache1 = EvaluationCache(cache_dir=temp_cache_dir) cache_key = "persistent_key" data = {"result": "persistent_data", "value": 123} cache1.set(cache_key, data) # 创建新的缓存实例(模拟重启) cache2 = EvaluationCache(cache_dir=temp_cache_dir) retrieved = cache2.get(cache_key) assert retrieved is not None assert retrieved["result"] == "persistent_data" assert retrieved["value"] == 123 def test_concurrent_access(self, cache): """测试并发访问""" import threading results = [] errors = [] def set_cache(value): try: cache.set(f"key_{value}", {"data": value}) results.append(value) except Exception as e: errors.append(e) # 创建多个线程同时写入 threads = [] for i in range(10): t = threading.Thread(target=set_cache, args=(i,)) threads.append(t) t.start() for t in threads: t.join() # 验证所有操作都成功 assert len(errors) == 0 assert len(results) == 10 # 验证所有缓存都存在 for i in range(10): assert cache.get(f"key_{i}") is not None class TestCachedEvaluationExecutor: """测试缓存评估执行器""" @pytest.fixture def cached_executor(self, cache): """创建缓存执行器""" return CachedEvaluationExecutor( cache=cache, rag_config={"model": "test-model"}, retrieval_params={"top_k": 5} ) def test_evaluate_question_cache_hit(self, cached_executor): """测试缓存命中""" question = "什么是机器学习?" call_count = [0] def eval_func(q): call_count[0] += 1 return {"answer": f"答案: {q}", "confidence": 0.9} # 第一次调用 - 缓存未命中 result1 = cached_executor.evaluate_question(question, eval_func) assert call_count[0] == 1 assert result1["answer"] == "答案: 什么是机器学习?" # 第二次调用 - 缓存命中 result2 = cached_executor.evaluate_question(question, eval_func) assert call_count[0] == 1 # 没有增加 assert result2["answer"] == "答案: 什么是机器学习?" def test_evaluate_question_cache_miss(self, cached_executor): """测试缓存未命中""" question1 = "问题1" question2 = "问题2" call_count = [0] def eval_func(q): call_count[0] += 1 return {"answer": f"答案: {q}"} # 两个不同的问题 result1 = cached_executor.evaluate_question(question1, eval_func) result2 = cached_executor.evaluate_question(question2, eval_func) assert call_count[0] == 2 # 两次调用 assert result1["answer"] == "答案: 问题1" assert result2["answer"] == "答案: 问题2" def test_evaluate_batch_mixed_cache(self, cached_executor): """测试批量评估的混合缓存情况""" questions = ["问题1", "问题2", "问题3", "问题1", "问题2"] call_count = [0] def eval_func(q_list): call_count[0] += 1 return [{"answer": f"答案: {q}"} for q in q_list] results = cached_executor.evaluate_batch(questions, eval_func) # 应该只调用一次评估函数(去重后) assert len(results) == 5 # 所有结果都应该正确 assert results[0]["answer"] == "答案: 问题1" assert results[3]["answer"] == "答案: 问题1" # 重复的问题 def test_get_cache_stats(self, cached_executor): """测试获取缓存统计""" question = "测试问题" def eval_func(q): return {"answer": f"答案: {q}"} # 第一次调用 - 未命中 cached_executor.evaluate_question(question, eval_func) # 第二次调用 - 命中 cached_executor.evaluate_question(question, eval_func) stats = cached_executor.get_cache_stats() assert stats['cache_hits'] == 1 assert stats['cache_misses'] == 1 assert stats['hit_rate'] == 0.5 def test_reset_stats(self, cached_executor): """测试重置统计""" question = "测试问题" def eval_func(q): return {"answer": f"答案: {q}"} cached_executor.evaluate_question(question, eval_func) cached_executor.evaluate_question(question, eval_func) # 重置前 stats_before = cached_executor.get_cache_stats() assert stats_before['cache_hits'] == 1 # 重置 cached_executor.reset_stats() # 重置后 stats_after = cached_executor.get_cache_stats() assert stats_after['cache_hits'] == 0 assert stats_after['cache_misses'] == 0 class TestCacheIntegration: """缓存集成测试""" def test_cache_integration_workflow(self, temp_cache_dir): """测试缓存的完整工作流程""" # 创建缓存 cache = EvaluationCache(cache_dir=temp_cache_dir, ttl_seconds=3600) # 创建缓存执行器 executor = CachedEvaluationExecutor( cache=cache, rag_config={"model": "gpt-4"} ) questions = [ "什么是机器学习?", "什么是深度学习?", "Python中如何使用列表?" ] call_count = [0] def eval_func(q_list): call_count[0] += 1 return [{ "question": q, "answer": f"这是关于 {q} 的答案", "timestamp": time.time() } for q in q_list] # 第一轮评估 results1 = executor.evaluate_batch(questions, eval_func) assert len(results1) == 3 assert call_count[0] == 1 # 批量调用一次 # 第二轮评估(应该从缓存获取) call_count[0] = 0 results2 = executor.evaluate_batch(questions, eval_func) assert len(results2) == 3 assert call_count[0] == 0 # 没有调用评估函数(全部命中缓存) # 验证结果一致性 for r1, r2 in zip(results1, results2): assert r1["question"] == r2["question"] assert r1["answer"] == r2["answer"] # 验证缓存统计 stats = executor.get_cache_stats() assert stats['cache_hits'] == 3 assert stats['cache_misses'] == 3 assert stats['hit_rate'] == 0.5