"""Тесты связи письма с автосозданными сущностями (webui/entities.py). Запуск: .venv/bin/python tests/test_entities.py CalDAV подменяется заглушкой (запоминает PUT/GET/DELETE), письмо — временный email.md с frontmatter. Реальные Radicale и архив не затрагиваются. """ import os import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) os.environ.setdefault("WEBUI_PASSWORD", "test-pass") from webui import entities as E # noqa: E402 # UID строится из относительного пути письма: слаг + короткий хэш UID = E.email_uid("INBOX/2026/10/17425/email.md") EMAIL = """--- id: 17425 folder: INBOX subject: "Обучение ISpring" from: "Рудакова Анна Евгеньевна " date: "2026-10-30 11:57+03:00" Message-ID: "" classification: meeting,task classification_reason: приглашение на встречу + поручение обеспечить явку meeting_datetime: "2026-11-06 11:00" --- Добрый день! Дата и время: 6 ноября 2026 года, 11:00. """ class FakeCalDAV: """Подмена сетевого слоя entities: словарь ресурсов по (kind, uid).""" def __init__(self): self.store: dict[tuple[str, str], str] = {} self.calls: list[tuple[str, str, str]] = [] # --- подменяемые функции --- def resource_exists(self, kind, uid): return (kind, uid) in self.store def put(self, kind, uid, body): self.calls.append(("PUT", kind, uid)) self.store[(kind, uid)] = body return {"ok": True, "etag": "E1"} def delete(self, kind, uid): self.calls.append(("DELETE", kind, uid)) self.store.pop((kind, uid), None) return {"ok": True} def cancel_task(self, uid): self.calls.append(("CANCEL", "task", uid)) body = self.store.get(("task", uid)) if body is None: return {"ok": True, "note": "задачи уже нет"} self.store[("task", uid)] = body.replace("STATUS:NEEDS-ACTION", "STATUS:CANCELLED") return {"ok": True} def install(monkeypatch_target=FakeCalDAV()): """Подменить сетевые функции entities заглушкой; вернуть заглушку.""" fake = monkeypatch_target E.resource_exists = fake.resource_exists E._put = fake.put E._delete_resource = fake.delete E._cancel_task = fake.cancel_task # саммари локальной моделью в тестах не нужно: описание собирается без него E.CTX.summarize = lambda *a, **k: None return fake def make_email(tmp: Path, text: str = EMAIL) -> Path: # относительный путь (и UID ресурса) считаем от временного каталога E.EMAIL_ROOTS = (tmp,) d = tmp / "INBOX" / "2026" / "10" / "17425" d.mkdir(parents=True, exist_ok=True) path = d / "email.md" path.write_text(text, encoding="utf-8") return path # ─── разбор и frontmatter ──────────────────────────────────────────────────── def test_headers_and_uid(): headers = E.headers_of(EMAIL) assert headers["classification"] == "meeting,task" assert headers["meeting_datetime"] == "2026-11-06 11:00" # UID считается от относительного пути письма (как в обработчиках) with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) assert E.email_uid(E.rel_path_of(path)) == UID assert E.email_uid("INBOX/2026/10/17425/email.md") == UID assert UID.startswith("inbox-2026-10-17425-email-md-") # слаг в нижнем регистре + хэш # разные подпапки с одинаковым хвостом пути больше не совпадают assert E.email_uid("INBOX/Контрагенты/ИП/2026/04/6/email.md") != E.email_uid("INBOX/2026/04/6/email.md") assert E.meeting_start(headers) == "2026-11-06 11:00" assert E.meeting_start({"meeting_datetime": "не дата"}) is None def test_update_frontmatter_adds_and_replaces(): with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) E.update_frontmatter(path, {"entity_event_uid": "u-1", "entity_event_state": "created"}) text = path.read_text(encoding="utf-8") assert "entity_event_uid: u-1" in text assert "entity_event_state: created" in text E.update_frontmatter(path, {"entity_event_state": "disabled"}) text = path.read_text(encoding="utf-8") assert text.count("entity_event_state:") == 1 assert "entity_event_state: disabled" in text assert "Добрый день!" in text # тело письма не тронуто # ─── создание сущностей ────────────────────────────────────────────────────── def test_ensure_creates_event_and_task_with_meeting_time(): fake = install() with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) ev = E.ensure("event", path) tk = E.ensure("task", path) assert ev.get("ok") and tk.get("ok"), (ev, tk) event_ics = fake.store[("event", UID)] assert "BEGIN:VEVENT" in event_ics assert "DTSTART:20261106T110000" in event_ics # время встречи из письма assert "SUMMARY:Обучение ISpring" in event_ics task_ics = fake.store[("task", UID)] assert "BEGIN:VTODO" in task_ics # DUE пишется в UTC (Radicale отклоняет «плавающее» время в VTODO): 11:00 MSK = 08:00Z assert "DUE:20261106T080000Z" in task_ics headers = E.headers_of(path.read_text(encoding="utf-8")) assert headers["entity_event_state"] == "created" assert headers["entity_task_state"] == "created" def test_disabled_is_not_recreated(): fake = install() with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) E.update_frontmatter(path, {"entity_event_state": "disabled"}) res = E.ensure("event", path) assert res.get("skipped") == "disabled" assert ("event", UID) not in fake.store def test_disable_event_deletes_resource(): fake = install() with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) E.ensure("event", path) res = E.disable("event", path) assert res.get("ok"), res assert ("event", UID) not in fake.store assert ("DELETE", "event", UID) in fake.calls headers = E.headers_of(path.read_text(encoding="utf-8")) assert headers["entity_event_state"] == "disabled" def test_disable_task_cancels_softly(): fake = install() with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) E.ensure("task", path) res = E.disable("task", path) assert res.get("ok"), res assert "STATUS:CANCELLED" in fake.store[("task", UID)] headers = E.headers_of(path.read_text(encoding="utf-8")) assert headers["entity_task_state"] == "disabled" def test_enable_recreates_after_disable(): fake = install() with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) E.ensure("event", path) E.disable("event", path) res = E.enable("event", path) assert res.get("ok"), res assert ("event", UID) in fake.store headers = E.headers_of(path.read_text(encoding="utf-8")) assert headers["entity_event_state"] == "created" def test_task_control_uses_meeting_time(): fake = install() with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) res = E.create_task_control(path) assert res.get("ok") and res["due"] == "2026-11-06 11:00" ics = fake.store[("task", UID)] assert "SUMMARY:Контроль: Обучение ISpring" in ics assert "DUE:20261106T080000Z" in ics headers = E.headers_of(path.read_text(encoding="utf-8")) assert headers["entity_task_state"] == "created" def test_describe_reports_state_and_existence(): fake = install() with tempfile.TemporaryDirectory() as t: path = make_email(Path(t)) E.ensure("event", path) state = E.describe(path) assert state["event"]["exists"] is True assert state["event"]["state"] == "created" assert state["task"]["exists"] is False assert state["task"]["uid"] == UID def test_next_workday_skip_weekend(): from datetime import datetime friday = datetime(2026, 10, 30, 15, 0) # пятница assert E.next_workday_1100(friday) == "2026-11-02 11:00" # понедельник saturday = datetime(2026, 10, 31, 15, 0) assert E.next_workday_1100(saturday) == "2026-11-02 11:00" if __name__ == "__main__": for name, fn in sorted(globals().items()): if name.startswith("test_") and callable(fn): fn() print("OK", name) print("all entities tests passed")