""" backend/tests/test_faq_cache.py 用途:FAQ 缓存在线匹配规则。 逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中。 """ from app import db from app.models import Agent, QuickQuestion from app.services.faq_cache import FaqCacheService def _create_agent() -> Agent: """写入测试 Agent,供 FAQ 条目关联。""" agent = Agent(name='faq-cache-agent', type='api', dify_app_id='app-faq-cache', dify_api_key='key-faq-cache') db.session.add(agent) db.session.commit() return agent def _create_faq(agent_id: int, **overrides) -> QuickQuestion: """写入一条全局 FAQ,默认启用缓存且有标准答案。""" payload = { 'user_id': None, 'agent_id': agent_id, 'title': '公司的企业文化', 'question': '公司的企业文化', 'answer': '客户满意、员工乐意、经营得意', 'aliases': ['企业文化'], 'cache_enabled': True, 'is_enabled': True, } payload.update(overrides) faq = QuickQuestion(**payload) db.session.add(faq) db.session.commit() return faq def test_try_match_hits_when_cache_on_even_if_not_shown_on_home(app): """关闭前台展示时,启用缓存的问句仍应直答,不走 Dify。""" with app.app_context(): agent = _create_agent() _create_faq(agent.id, is_enabled=False) hit = FaqCacheService.try_match('公司的企业文化', agent.id) alias_hit = FaqCacheService.try_match('企业文化', agent.id) assert hit is not None assert hit.answer == '客户满意、员工乐意、经营得意' assert alias_hit is not None assert alias_hit.id == hit.id def test_try_match_skips_when_cache_disabled(app): """仅在首页展示、未启用缓存时,提问仍应回退 Dify。""" with app.app_context(): agent = _create_agent() _create_faq(agent.id, cache_enabled=False, is_enabled=True) assert FaqCacheService.try_match('公司的企业文化', agent.id) is None