"""C1 词库 CRUD + 预览。""" from __future__ import annotations import datetime as dt from app.analytics.sensitive import words as words_svc from app.db.models import Message async def test_create_and_duplicate(make_client): async def seed(session): w = await words_svc.create_word( session, word="飞单", category="私单", exclude_words=["飞单群"] ) assert w.id is not None and w.enabled is True try: await words_svc.create_word(session, word="飞单") raise AssertionError("should raise") except ValueError: pass await make_client(seed) async def test_preview_count_and_excludes(make_client): async def seed(session): ts = 1756900000000 for i, text in enumerate(["今天聊飞单的事", "飞单群公告", "正常聊天"]): session.add(Message(msg_id=f"m{i}", channel="wechat", owner_account_id="wx1", talker_id="t1", timestamp=ts + i, is_send=False, type="text", text=text, fetched_at=dt.datetime(2026, 9, 4))) await session.commit() n1 = await words_svc.preview_count(session, "飞单", None) assert n1 == 2 # SQLite 测试库走 LIKE 路径 n2 = await words_svc.preview_count(session, "飞单", ["飞单群"]) assert n2 == 1 # 排除词剔除「飞单群公告」 await make_client(seed) async def test_api_words_crud(make_client): async def seed(session): ... client = await make_client(seed) r = await client.post("/api/analytics/sensitive/words", json={"word": "私单", "category": "飞单"}) assert r.status_code == 200 and r.json()["word"] == "私单" r = await client.post("/api/analytics/sensitive/words", json={"word": "私单"}) assert r.status_code == 409 r = await client.post("/api/analytics/sensitive/words/preview", json={"word": "私单"}) assert r.status_code == 200 and r.json()["count"] == 0 wid = 1 r = await client.patch(f"/api/analytics/sensitive/words/{wid}", json={"enabled": False}) assert r.status_code == 200 and r.json()["enabled"] is False r = await client.delete(f"/api/analytics/sensitive/words/{wid}") assert r.status_code == 200 # 注:单字词 MySQL 拒预览分支(words.py ValueError)在 SQLite 测试库不可达 # ——dialect 判定不满足,不做单测;由注释 + 路由 400 映射保障。 async def test_api_patch_unknown_404(make_client): async def seed(session): ... client = await make_client(seed) r = await client.patch("/api/analytics/sensitive/words/999", json={"enabled": False}) assert r.status_code == 404 async def test_api_delete_unknown_404(make_client): async def seed(session): ... client = await make_client(seed) r = await client.delete("/api/analytics/sensitive/words/999") assert r.status_code == 404 async def test_api_create_empty_word_409(make_client): async def seed(session): ... client = await make_client(seed) r = await client.post("/api/analytics/sensitive/words", json={"word": " "}) assert r.status_code == 409