Files
email-assistant/tests/test_contacts_ui.py
T
hermes 664f038d28 fix(contacts): строки были 9 px — tojson ломал x-data в атрибуте
Корень: `x-data="{edit:false, val:{{ value|tojson }}, err:''}"` — tojson вставляет
строку в двойных кавычках, атрибут тоже в двойных → `val:""` обрывал атрибут,
Alpine не инициализировал компонент, <span x-show="!edit"> оставался display:none,
ячейки визуально пустые, высота строки = padding + border = 9 px.

- `|tojson|forceescape` в макросе ячейки и в onclick кнопки задачи карточки.
- Плотность строк: td padding 8px 10px, line-height 1.35, min-height 34px,
  заголовки 9px 10px → высота строки 9 → 34 px.
- Регресс-тест test_inline_edit_xdata_is_valid_html (в разметке не должно быть
  x-data="{edit:false, val:" — ловит класс ошибки, не одну страницу).

Проверено headless-Chromium (метрики из DOM): было rowH=9, spanDisp=none;
стало rowH=34, spanDisp=block, valH=17. tests/test_contacts_ui.py — 17/17.
Контейнер пересобран (healthy): x-data экранирован, 7 строк на букве «А».
2026-10-30 07:14:05 +00:00

223 lines
8.3 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_inline_edit_xdata_is_valid_html():
"""x-data не должен ломаться кавычками из значения (регресс: строки были 9 px)."""
c = _client()
html = c.get("/contacts").text
assert "x-data=\"{edit:false, val:&#34;" in html or "x-data=\"{edit:false, val:&quot;" in html
# сырые кавычки внутри значения сломали бы атрибут
assert 'x-data="{edit:false, val:"' not in html
# в карточке контакта тоже
card = c.get("/contacts/" + _first_contact()["id"]).text
assert 'x-data="{edit:false, val:"' not in card
def test_card_column_hidden_until_selected():
c = _client()
page = c.get("/contacts").text
assert "cols no-card" in page # карточка не занимает место
assert "chatOpen: false" in page # ИИ-панель свёрнута на странице контактов
contact = _first_contact()
with_card = c.get("/contacts", params={"cid": contact["id"]}).text
assert "cols no-card" not in with_card
assert 'class="ccard"' in with_card
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")