Files
email-assistant/tests/test_email_entities_ui.py
Hermes Agent 8ca4c4a7c8 feat(entities): метки классификации в детализации письма + автосозданные событие/задача
- db.split_tags(): метки делятся по запятой и пробелу (был один чип «meeting,task»)
- webui/entities.py: связь письмо↔сущность в frontmatter (entity_<kind>_uid/state),
  ensure/disable/enable/create_task_control; disable event = DELETE VEVENT,
  disable task = STATUS:CANCELLED+X-DELETED; task-control только по кнопке
- блок «Отметки» + «Автоматически создано» в детализации, роут POST /api/email/entity
- handlers: общий UID и ICS-билдеры, запись entity_*, пропуск state: disabled,
  --backfill --days/--limit, dry-run больше не пишет в Radicale
- fix: UID ресурса теперь уникален (транслит-слаг + sha1[:8]) — кириллица выпадала
  из регулярки, письма из разных подпапок затирали один ресурс (1121 письмо с
  task/meeting, 554 handled_*, в Radicale 50 задач и 52 события)
- fix: DUE в VTODO пишется в UTC — Radicale отклонял плавающее время (400)
- tests: test_entities.py 10/10, test_email_entities_ui.py 7/7
2026-10-30 09:50:11 +00:00

122 lines
4.3 KiB
Python

"""Тесты блока «Отметки / Автоматически создано» в детализации письма.
Запуск: .venv/bin/python tests/test_email_entities_ui.py
Читается реальный архив (read-only), изменения подменяются заглушками —
фронтматтер писем и Radicale не затрагиваются.
"""
import os
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
os.environ.setdefault("WEBUI_PASSWORD", "test-pass")
from fastapi.testclient import TestClient # noqa: E402
import webui.app as app_module # noqa: E402
from webui import db as dbmod # noqa: E402
EXAMPLE = "INBOX/2026/10/17425/email.md"
def _client() -> TestClient:
c = TestClient(app_module.app)
assert c.post("/login", data={"password": "test-pass"}, follow_redirects=False).status_code == 303
return c
def _example_exists() -> bool:
return (dbmod.EMAIL_ROOT / EXAMPLE).is_file()
def test_detail_shows_all_marks():
if not _example_exists():
print(" (эталонное письмо отсутствует — пропуск)")
return
c = _client()
html = c.get("/emails", params={"path": EXAMPLE}).text
assert 'id="email-ents"' in html
assert "Отметки" in html
assert 'class="tag' in html and ">meeting<" in html and ">task<" in html
assert "2026-11-06 11:00" in html
assert "почему так размечено" in html
def test_detail_fragment_contains_block():
if not _example_exists():
return
c = _client()
html = c.get(f"/emails/{EXAMPLE}", headers={"HX-Request": "true"}).text
assert 'id="email-ents"' in html
assert "meeting" in html
def test_split_tags_used_in_list():
c = _client()
rows = c.get("/emails", params={"folder": "INBOX"}).text
# в списке письмо не должно показывать один слипшийся чип «meeting,task»
assert "meeting,task" not in rows
def test_entity_api_requires_auth():
fresh = TestClient(app_module.app)
assert fresh.post("/api/email/entity",
data={"path": EXAMPLE, "kind": "event", "action": "disable"}).status_code == 401
def test_entity_api_validation():
c = _client()
r = c.post("/api/email/entity", data={"path": EXAMPLE, "kind": "note", "action": "disable"})
assert r.status_code == 400
r = c.post("/api/email/entity", data={"path": EXAMPLE, "kind": "event", "action": "drop"})
assert r.status_code == 400
r = c.post("/api/email/entity", data={"path": "../../etc/passwd", "kind": "event", "action": "enable"})
assert r.status_code == 404
def test_entity_api_calls_entities_and_returns_fragment():
real_disable = app_module.entities.disable
calls = {}
def fake_disable(kind, email_file):
calls["kind"] = kind
calls["file"] = Path(email_file).name
return {"ok": True, "uid": "u-1"}
app_module.entities.disable = fake_disable
try:
c = _client()
r = c.post("/api/email/entity",
data={"path": EXAMPLE, "kind": "event", "action": "disable"},
headers={"HX-Request": "true"})
assert r.status_code == 200, r.text
assert calls == {"kind": "event", "file": "email.md"}
assert 'id="email-ents"' in r.text
# JSON-клиент получает JSON
r = c.post("/api/email/entity",
data={"path": EXAMPLE, "kind": "task", "action": "disable"})
assert r.status_code == 200 and r.json()["ok"] is True
finally:
app_module.entities.disable = real_disable
def test_entity_api_error_maps_to_502():
real_enable = app_module.entities.enable
app_module.entities.enable = lambda kind, email_file: {"error": "Radicale недоступен"}
try:
c = _client()
r = c.post("/api/email/entity",
data={"path": EXAMPLE, "kind": "event", "action": "enable"})
assert r.status_code == 502 and "Radicale" in r.json()["error"]
finally:
app_module.entities.enable = real_enable
if __name__ == "__main__":
for name, fn in sorted(globals().items()):
if name.startswith("test_") and callable(fn):
fn()
print("OK", name)
print("all email-entities-ui tests passed")