"""Тесты страницы контактов (шаблоны + роуты). Запуск: .venv/bin/python tests/test_contacts_ui.py Читается реальная база контактов (read-only), запись подменяется заглушкой — реальные данные не изменяются. """ import os import re 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 _expected_rows(letter: str = "А", per_page: int = 50) -> int: everyone = C.visible(C.load()) subset = [x for x in everyone if C.letter_of(x) == letter] if letter else everyone return min(len(subset), per_page) 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 assert 'class="al all act"' in html.replace('class="al all act"', 'class="al all act"') or "al all" in html total = len(C.visible(C.load())) assert f"из {total}" in html # по умолчанию — только буква «А» assert 'class="crow"' in html assert html.count('class="crow"') == _expected_rows("А") assert 'буква А' in html def test_filter_narrows_rows(): c = _client() html = c.get("/contacts", params={"last_name": "иван", "letter": "all"}).text assert 0 < html.count('class="crow"') < len(C.visible(C.load())) def test_default_letter_a_and_all_chip(): c = _client() default = c.get("/contacts").text every = c.get("/contacts", params={"letter": "all"}).text assert default.count('class="crow"') <= every.count('class="crow"') assert "al all act" not in default # по умолчанию активна буква А, чип «Все» — нет assert "al all act" in every # при letter=all активен чип «Все» def test_pagination_slices_rows(): c = _client() per_page = 25 p1 = c.get("/contacts", params={"letter": "all", "per_page": per_page, "page": 1}).text p2 = c.get("/contacts", params={"letter": "all", "per_page": per_page, "page": 2}).text assert p1.count('class="crow"') == per_page assert p2.count('class="crow"') > 0 assert "стр. 1 из" in p1 and "стр. 2 из" in p2 assert "← Назад" in p1 and "Вперёд →" in p1 # страницы не пересекаются по набору id ids1 = set(re.findall(r'hx-get="/contacts/([^"]+)"', p1)) ids2 = set(re.findall(r'hx-get="/contacts/([^"]+)"', p2)) assert ids1 and ids2 and not (ids1 & ids2) def test_page_param_clamped(): c = _client() html = c.get("/contacts", params={"letter": "all", "page": 9999, "per_page": 25}).text assert 'class="crow"' in html assert "стр. " 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")