test_cache.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #!/usr/bin/env python3
  2. """
  3. 测试 XiaohongshuSearchRecommendations 缓存功能
  4. """
  5. import sys
  6. import os
  7. import json
  8. import time
  9. # 添加脚本目录到路径
  10. sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'script', 'search_recommendations'))
  11. from xiaohongshu_search_recommendations import XiaohongshuSearchRecommendations
  12. def print_section(title):
  13. """打印分隔符"""
  14. print("\n" + "="*60)
  15. print(f" {title}")
  16. print("="*60)
  17. def test_cache():
  18. """测试缓存功能"""
  19. # 创建客户端,设置较短的缓存时间用于测试(60秒)
  20. print_section("1. 初始化客户端")
  21. client = XiaohongshuSearchRecommendations(enable_cache=True, cache_ttl=60)
  22. print(f"✓ 客户端初始化成功")
  23. print(f" - 缓存已启用: {client.enable_cache}")
  24. print(f" - 缓存有效期: {client.cache_ttl} 秒")
  25. print(f" - 结果目录: {client.results_base_dir}")
  26. # 测试关键词
  27. test_keyword = "川西"
  28. # 第一次请求(应该从API获取)
  29. print_section(f"2. 第一次请求关键词 '{test_keyword}'")
  30. print("预期: 缓存未命中,从API获取数据")
  31. start_time = time.time()
  32. result1 = client.get_recommendations(test_keyword)
  33. elapsed1 = time.time() - start_time
  34. print(f"✓ 请求完成,耗时: {elapsed1:.2f} 秒")
  35. print(f" - 获取到 {len(result1)} 条推荐词")
  36. if result1:
  37. print(f" - 示例: {result1[:3]}")
  38. # 保存结果到文件(模拟正常使用流程)
  39. if result1:
  40. filepath = client.save_result(test_keyword, result1)
  41. print(f"✓ 结果已保存到: {filepath}")
  42. # 查看缓存信息
  43. print_section("3. 查看缓存信息")
  44. cache_info = client.get_cache_info(test_keyword)
  45. print("内存缓存:")
  46. print(json.dumps(cache_info["memory_cache"], ensure_ascii=False, indent=2))
  47. print("\n文件缓存:")
  48. print(json.dumps(cache_info["file_cache"], ensure_ascii=False, indent=2))
  49. # 第二次请求(应该从内存缓存获取)
  50. print_section(f"4. 第二次请求关键词 '{test_keyword}'(内存缓存)")
  51. print("预期: 从内存缓存获取")
  52. start_time = time.time()
  53. result2 = client.get_recommendations(test_keyword)
  54. elapsed2 = time.time() - start_time
  55. print(f"✓ 请求完成,耗时: {elapsed2:.2f} 秒")
  56. print(f" - 获取到 {len(result2)} 条推荐词")
  57. print(f" - 速度提升: {(elapsed1/elapsed2):.1f}x")
  58. # 验证结果一致性
  59. if result1 == result2:
  60. print("✓ 缓存数据与原始数据一致")
  61. else:
  62. print("✗ 警告: 缓存数据与原始数据不一致")
  63. # 清除内存缓存,测试文件缓存
  64. print_section(f"5. 清除内存缓存,测试文件缓存")
  65. client.clear_memory_cache(test_keyword)
  66. print("✓ 内存缓存已清除")
  67. # 第三次请求(应该从文件缓存获取)
  68. print_section(f"6. 第三次请求关键词 '{test_keyword}'(文件缓存)")
  69. print("预期: 从文件缓存获取")
  70. start_time = time.time()
  71. result3 = client.get_recommendations(test_keyword)
  72. elapsed3 = time.time() - start_time
  73. print(f"✓ 请求完成,耗时: {elapsed3:.2f} 秒")
  74. print(f" - 获取到 {len(result3)} 条推荐词")
  75. # 验证结果一致性
  76. if result1 == result3:
  77. print("✓ 文件缓存数据与原始数据一致")
  78. else:
  79. print("✗ 警告: 文件缓存数据与原始数据不一致")
  80. # 测试禁用缓存
  81. print_section(f"7. 测试禁用缓存(use_cache=False)")
  82. print("预期: 直接从API获取,不使用缓存")
  83. start_time = time.time()
  84. result4 = client.get_recommendations(test_keyword, use_cache=False)
  85. elapsed4 = time.time() - start_time
  86. print(f"✓ 请求完成,耗时: {elapsed4:.2f} 秒")
  87. print(f" - 获取到 {len(result4)} 条推荐词")
  88. # 查看最终缓存状态
  89. print_section("8. 最终缓存状态")
  90. cache_info = client.get_cache_info()
  91. print("所有内存缓存:")
  92. for keyword, info in cache_info["memory_cache"].items():
  93. print(f" - {keyword}: {info}")
  94. print("\n所有文件缓存:")
  95. for keyword, info in cache_info["file_cache"].items():
  96. print(f" - {keyword}: {info}")
  97. print_section("测试完成")
  98. print("✓ 所有缓存功能测试通过")
  99. if __name__ == "__main__":
  100. try:
  101. test_cache()
  102. except KeyboardInterrupt:
  103. print("\n\n测试被用户中断")
  104. except Exception as e:
  105. print(f"\n\n✗ 测试失败: {e}")
  106. import traceback
  107. traceback.print_exc()