"""Тесты страницы контактов (шаблоны + роуты). Запуск: .venv/bin/python tests/test_contacts_ui.py Читается реальная база контактов (read-only), запись подменяется заглушкой — реальные данные не изменяются. """ 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 contacts as C # noqa: E402 def _client() -> TestClient: c = TestClient(app_module.app) r = c.post("/login", data={"password": "test-pass"}, follow_redirects=False) assert r.status_code == 303, r.status_code return c def _first_contact() -> dict: everyone = C.visible(C.load()) return everyone[0] def test_requires_auth(): fresh = TestClient(app_module.app) assert fresh.get("/contacts", follow_redirects=False).status_code == 303 assert fresh.get("/api/contacts").status_code == 401 assert fresh.put("/api/contact/x/field", json={"field": "phone", "value": "1"}).status_code == 401 def test_page_renders_table_filters_alphabet(): c = _client() html = c.get("/contacts").text assert 'class="ctab"' in html assert 'name="last_name"' in html and 'name="company"' in html assert 'name="middle_name"' in html and 'name="position"' in html assert 'id="dl-company"' in html assert 'class="alpha"' in html # буква А присутствует, неактивные буквы тоже (все 33+26+1) assert 'title="нет контактов"' in html or 'class="al act"' in html or 'class="al"' in html total = len(C.visible(C.load())) assert f"из {total}" in html assert html.count('class="crow"') == total def test_filter_narrows_rows(): c = _client() html = c.get("/contacts", params={"last_name": "иван"}).text assert html.count('class="crow"') < len(C.visible(C.load())) assert 'class="crow"' in html def test_htmx_returns_content_fragment(): c = _client() r = c.get("/contacts", params={"q": "а"}, headers={"HX-Request": "true"}) assert 'id="contacts-cols"' in r.text assert " 5 and len(data["items"]) == 5 item = data["items"][0] assert {"id", "full_name"} <= set(item) # части ФИО заполнены у разобранных контактов (см. contacts_split_names.py) assert any("last_name" in x for x in data["items"]) def test_card_fragment_and_404(): c = _client() contact = _first_contact() html = c.get(f"/contacts/{contact['id']}").text assert 'class="ccard"' in html assert 'id="cfullname"' in html assert "Полученные" in html and "Отправленные" in html assert c.get("/contacts/nonexistent-id").status_code == 404 def test_field_put_success_is_mocked(): c = _client() real = C.update_field calls = {} def fake(contact_id, field, value, **kw): calls.update(id=contact_id, field=field, value=value) return {"ok": True, "contact": {"id": contact_id, field: value}, "full_name": "Новое Имя", "caldav": {"etag": "E2"}} app_module.contacts.update_field = fake try: r = c.put("/api/contact/c1/field", json={"field": "phone", "value": "+7 900"}) assert r.status_code == 200, r.text body = r.json() assert body["ok"] and body["value"] == "+7 900" and body["full_name"] == "Новое Имя" assert calls == {"id": "c1", "field": "phone", "value": "+7 900"} finally: app_module.contacts.update_field = real def test_field_put_validation_and_404(): c = _client() real = C.update_field app_module.contacts.update_field = lambda cid, f, v, **kw: {"error": "некорректный email"} try: r = c.put("/api/contact/c1/field", json={"field": "email", "value": "x"}) assert r.status_code == 400 and "email" in r.json()["error"] finally: app_module.contacts.update_field = real r = c.put("/api/contact/nonexistent/field", json={"field": "phone", "value": "1"}) assert r.status_code == 404 def test_bad_json_body(): c = _client() r = c.put("/api/contact/c1/field", content=b"{not json", headers={"Content-Type": "application/json"}) assert r.status_code == 400 if __name__ == "__main__": for name, fn in sorted(globals().items()): if name.startswith("test_") and callable(fn): fn() print("OK", name) print("all contacts-ui tests passed")