Files
email-assistant/tests/test_contacts_ui.py
T
hermes 9f0f99bdfc fix(contacts): пагинация, по умолчанию буква «А», читаемые ширины колонок
Жалоба: при загрузке список широкий, затем узкий — текста не видно; после
фильтра по алфавиту карточки всё равно узкие.

- Пагинация: page/per_page (25/50/100/200, по умолчанию 50), «← Назад /
  Вперёд →», «стр. N из M», селектор размера страницы; page клампится.
- По умолчанию открывается буква «А» (letter=А), чип «Все» снимает фильтр
  (letter=all), повторный клик по активной букве ведёт в «Все».
- Ширины: .ctab min-width 860px + минимумы колонок 120/90/100/140/130/130/150,
  overflow:auto у списка вместо сжатия текста; c2 flex:2.6, карточка max-width
  460px, у значений в ячейках title с полным текстом.
- Страница: 872 КБ → 56 КБ (7 строк на букву А), 127 мс.
- spec contacts-ui: добавлены требования «Пагинация и буква по умолчанию» и
  «Читаемая ширина колонок».

Замерено headless-Chromium (метрики из DOM): 1600 px с закрытой ИИ-панелью —
c2=938 px, таблица 860 помещается целиком; с открытой — c2=628 и скролл при
сохранении минимальных ширин. tests/test_contacts_ui.py — 15/15; контейнер
пересобран (healthy), живые запросы: letter=all&per_page=25 → 25 строк,
«стр. 1 из 9», page=2 — другие 25.
2026-10-29 09:12:07 +00:00

200 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Тесты страницы контактов (шаблоны + роуты).
Запуск: .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 "<html" not in r.text.lower()
def test_sort_header_links_have_dir():
c = _client()
html = c.get("/contacts").text
assert "sort=last_name" in html and "dir=desc" in html
def test_letter_and_alphabet_flow():
c = _client()
everyone = C.visible(C.load())
letter = C.letter_of(everyone[0])
html = c.get("/contacts", params={"letter": letter, "letter": letter}).text
rows = html.count('class="crow"')
expected = min(50, sum(1 for x in everyone if C.letter_of(x) == letter))
assert rows == expected, (rows, expected)
assert f"буква {letter}" in html
def test_letter_all_shows_everything_paged():
c = _client()
html = c.get("/contacts", params={"letter": "all", "per_page": 100}).text
everyone = C.visible(C.load())
assert html.count('class="crow"') == min(100, len(everyone))
def test_api_contacts_json():
c = _client()
data = c.get("/api/contacts", params={"limit": 5}).json()
assert data["total"] > 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")