feat(интерфейс): полоса «сайт в разработке» и адрес для обратной связи
Распоряжения Хозяина 08.09.2026: на странице входа добавить полосу о том, что сайт ещё в разработке (не заменяя страницу), а внизу чата — адрес info@infosmeta.ru. Полоса стоит над посадочной частью и уходит вместе с экраном входа; адрес живёт вне ленты сообщений, поэтому не стирается при создании нового диалога. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RuEU1u9Rz24zmoy9TuvWc2
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
"""Адрес для обратной связи внизу экрана чата: разметка и стили.
|
||||
|
||||
Распоряжение Хозяина 08.09.2026: «добавь на страницу чата, снизу адрес для обратной связи:
|
||||
info@infosmeta.ru». Канал «поговорить с человеком» — про доступ, оплату, регистрацию и про
|
||||
случаи, когда само приложение не работает; кнопка «Сообщить об ошибке» под ответом решает
|
||||
другую задачу и живёт внутри пузыря ответа.
|
||||
|
||||
Red-green: написано ДО правки static/chat.html.
|
||||
"""
|
||||
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
CHAT = os.path.join(ROOT, "static", "chat.html")
|
||||
ADDRESS = "info@infosmeta.ru"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def html():
|
||||
return open(CHAT, encoding="utf-8").read()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def chat_block(html):
|
||||
"""Разметка экрана чата — от его начала до закрытия основной колонки."""
|
||||
start = html.index('id="chat-screen"')
|
||||
return html[start:html.index("<!-- /.main-col -->", start)]
|
||||
|
||||
|
||||
def _rule(html, prefix):
|
||||
return next((ln for ln in html.splitlines() if ln.startswith(prefix)), None)
|
||||
|
||||
|
||||
def test_contact_line_lives_at_the_bottom_of_chat_screen(html, chat_block):
|
||||
"""Строка с адресом одна и стоит на экране чата ниже поля ввода.
|
||||
Порча: перенести её выше поля ввода или на экран входа → проверка упадёт."""
|
||||
assert html.count('id="contact-line"') == 1
|
||||
assert 'id="contact-line"' in chat_block, "строки нет на экране чата"
|
||||
assert (chat_block.index('id="input-area"') < chat_block.index('id="msg-input"')
|
||||
< chat_block.index('id="contact-line"'))
|
||||
|
||||
|
||||
def test_contact_is_a_mail_link_showing_the_address(chat_block):
|
||||
"""Это ссылка почты, и в тексте виден сам адрес: на телефоне нажатие открывает почту,
|
||||
на компьютере без почтовой программы адрес можно выделить и скопировать.
|
||||
|
||||
Порча: написать «Написать нам» вместо адреса или подставить href="#" → упадёт."""
|
||||
link = re.search(r"<a[^>]*id=\"contact-email\"[^>]*>(.*?)</a>", chat_block, re.S)
|
||||
assert link, "ссылки с адресом нет"
|
||||
tag, text = link.group(0), link.group(1)
|
||||
assert f'href="mailto:{ADDRESS}"' in tag
|
||||
assert text.strip() == ADDRESS
|
||||
assert "javascript:" not in tag and "onclick" not in tag
|
||||
|
||||
|
||||
def test_only_one_contact_address_across_pages():
|
||||
"""Во всех страницах живёт ровно один адрес на этом домене — два адреса человек
|
||||
воспринимает как два разных места, и одно из них всегда окажется мёртвым.
|
||||
|
||||
Порча: вписать support@infosmeta.ru куда-нибудь ещё → проверка упадёт."""
|
||||
found = set()
|
||||
for path in glob.glob(os.path.join(ROOT, "static", "*.html")):
|
||||
found |= set(re.findall(r"[\w.+-]+@infosmeta\.ru", open(path, encoding="utf-8").read()))
|
||||
assert found == {ADDRESS}, f"адреса на страницах: {sorted(found)}"
|
||||
|
||||
|
||||
def test_contact_styles_readable_and_in_flow(html, chat_block):
|
||||
"""Строка читаемая и в обычном потоке: соседняя служебная строка стоит с прозрачностью
|
||||
0,4 и почти не видна — для адреса этот приём не годится.
|
||||
|
||||
Порча: вписать opacity или position: fixed → проверка упадёт."""
|
||||
rule = _rule(html, "#contact-line {")
|
||||
assert rule, "нет правила стилей для строки с адресом"
|
||||
assert "var(--text-muted)" in rule
|
||||
assert not re.search(r"#[0-9a-fA-F]{3,6}\b", rule) and "rgb(" not in rule
|
||||
for forbidden in ("opacity", "position: fixed", "position: absolute", "white-space: nowrap"):
|
||||
assert forbidden not in rule, f"в правиле {forbidden}"
|
||||
tag = re.search(r"<p[^>]*id=\"contact-line\"[^>]*>", chat_block).group(0)
|
||||
assert "style=" not in tag, "встроенные стили в теге — их не переопределить темой"
|
||||
|
||||
|
||||
def test_link_colour_follows_theme(html):
|
||||
"""У самой ссылки задан цвет темы: иначе браузер нарисует её своей синей, и в тёмной
|
||||
теме её будет не прочитать. Порча: убрать правило → проверка упадёт."""
|
||||
rule = _rule(html, "#contact-line a {")
|
||||
assert rule and "var(--" in rule
|
||||
assert not re.search(r"#[0-9a-fA-F]{3,6}\b", rule)
|
||||
|
||||
|
||||
def test_contact_variables_exist_in_both_themes(html):
|
||||
"""Каждая переменная объявлена и в светлой, и в тёмной теме.
|
||||
Порча: взять несуществующую --muted → проверка упадёт."""
|
||||
used = set()
|
||||
for prefix in ("#contact-line {", "#contact-line a {", "#contact-line a:hover {"):
|
||||
rule = _rule(html, prefix)
|
||||
if rule:
|
||||
used |= set(re.findall(r"var\((--[a-z0-9-]+)", rule))
|
||||
assert used, "правила не используют переменные темы"
|
||||
light = html[html.index(":root {"):]
|
||||
light = light[:light.index("}")]
|
||||
dark = html[html.index(':root[data-theme="dark"] {'):]
|
||||
dark = dark[:dark.index("}")]
|
||||
for name in used:
|
||||
assert f"{name}:" in light, f"{name} нет в светлой теме"
|
||||
if not name.startswith(("--s", "--radius")):
|
||||
assert f"{name}:" in dark, f"{name} нет в тёмной теме"
|
||||
|
||||
|
||||
def test_address_not_duplicated_in_error_report_form(html):
|
||||
"""В форме «Сообщить об ошибке» адреса нет: у неё одно действие, второй путь в ней
|
||||
сбивает. Порча: вписать адрес в форму → проверка упадёт."""
|
||||
part = html[html.index("function openFeedbackForm"):html.index("async function sendMessage")]
|
||||
assert "infosmeta.ru" not in part
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Адрес для обратной связи глазами браузера: экран чата.
|
||||
|
||||
Стенд собирается с ключом входа (в хранилище лежит пропуск), поэтому сразу виден чат,
|
||||
а не экран входа.
|
||||
|
||||
Red-green: написано ДО правки static/chat.html.
|
||||
"""
|
||||
|
||||
import functools
|
||||
import http.server
|
||||
import os
|
||||
import socketserver
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
pytest.importorskip("playwright.sync_api", reason="playwright не установлен")
|
||||
|
||||
import ui_smoke_harness # noqa: E402
|
||||
from test_password_reset_ui import _launch, browser # noqa: E402,F401
|
||||
|
||||
ADDRESS = "info@infosmeta.ru"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site_in(tmp_path_factory):
|
||||
"""Стенд с пропуском в хранилище — открывается сразу экран чата."""
|
||||
d = tmp_path_factory.mktemp("ui_chat")
|
||||
ui_smoke_harness.build_stub(d / "index.html")
|
||||
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(d))
|
||||
|
||||
class Quiet(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
srv = Quiet(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{srv.server_address[1]}/index.html"
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def _open(browser, site_in, width=1280, height=900):
|
||||
ctx = browser.new_context(viewport={"width": width, "height": height})
|
||||
pg = ctx.new_page()
|
||||
pg.set_default_timeout(5000)
|
||||
pg.goto(site_in)
|
||||
pg.wait_for_selector("#chat-screen", state="visible")
|
||||
return ctx, pg
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def page(browser, site_in):
|
||||
ctx, pg = _open(browser, site_in)
|
||||
yield pg
|
||||
ctx.close()
|
||||
|
||||
|
||||
def _box(page, selector):
|
||||
return page.locator(selector).bounding_box()
|
||||
|
||||
|
||||
def _contrast(fg, bg):
|
||||
def lum(css):
|
||||
r, g, b = [int(v) / 255 for v in css[css.index("(") + 1:css.index(")")].split(",")[:3]]
|
||||
f = lambda c: c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 # noqa: E731
|
||||
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)
|
||||
a, b = sorted((lum(fg), lum(bg)), reverse=True)
|
||||
return (a + 0.05) / (b + 0.05)
|
||||
|
||||
|
||||
def test_contact_visible_under_input_row(page):
|
||||
"""Строка видна, стоит ниже строки ввода и помещается в окно.
|
||||
Порча: убрать строку или поднять её над полем ввода → проверка упадёт."""
|
||||
assert page.is_visible("#contact-line")
|
||||
c, row = _box(page, "#contact-line"), _box(page, "#input-row")
|
||||
assert c["y"] >= row["y"] + row["height"] - 1, "адрес оказался выше строки ввода"
|
||||
assert c["y"] + c["height"] <= 900
|
||||
assert ADDRESS in page.inner_text("#contact-line")
|
||||
|
||||
|
||||
def test_contact_link_is_clickable_and_not_covered(page):
|
||||
"""Ссылку ничем не перекрывает и она ведёт на почту.
|
||||
Порча: накрыть подвал чем-нибудь висящим поверх → точка попадёт не в ссылку."""
|
||||
assert page.get_attribute("#contact-email", "href") == f"mailto:{ADDRESS}"
|
||||
b = _box(page, "#contact-email")
|
||||
hit = page.evaluate(
|
||||
"([x, y]) => { const e = document.elementFromPoint(x, y);"
|
||||
" return e && e.closest('#contact-email') !== null; }",
|
||||
[b["x"] + b["width"] / 2, b["y"] + b["height"] / 2])
|
||||
assert hit, "ссылку что-то перекрывает"
|
||||
|
||||
|
||||
def test_contact_stays_put_in_long_chat_and_after_new_chat(page):
|
||||
"""Адрес не уезжает с перепиской и не пропадает при создании нового диалога — он вне
|
||||
ленты сообщений. Порча: перенести строку внутрь ленты → уедет и исчезнет."""
|
||||
before = _box(page, "#contact-line")
|
||||
page.evaluate("for (let i = 0; i < 80; i++) addMsg('ai', 'Строка ' + i)")
|
||||
page.wait_for_timeout(200)
|
||||
assert page.evaluate("const m = document.getElementById('messages');"
|
||||
" m.scrollHeight > m.clientHeight + 200"), "лента не прокручивается"
|
||||
after = _box(page, "#contact-line")
|
||||
assert abs(after["y"] - before["y"]) <= 1, "строка уехала вместе с перепиской"
|
||||
assert after["height"] >= 12
|
||||
page.evaluate("newChat()")
|
||||
page.wait_for_timeout(300)
|
||||
assert page.locator("#contact-line").count() == 1 and page.is_visible("#contact-line")
|
||||
|
||||
|
||||
def test_contact_visible_on_phone_no_sideways_scroll(browser, site_in):
|
||||
"""На телефоне адрес виден, поле ввода над ним, страница не уезжает вбок — в том числе
|
||||
при открытой боковой колонке. Порча: запретить перенос строки → появится прокрутка."""
|
||||
ctx, pg = _open(browser, site_in, 360, 740)
|
||||
c, inp = _box(pg, "#contact-line"), _box(pg, "#msg-input")
|
||||
over = pg.evaluate(
|
||||
"document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
pg.evaluate("toggleSidebar()")
|
||||
pg.wait_for_timeout(300)
|
||||
over_open = pg.evaluate(
|
||||
"document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
ctx.close()
|
||||
assert c["y"] + c["height"] <= 740, "адрес не помещается в экран телефона"
|
||||
assert inp["y"] + inp["height"] <= c["y"] + 1, "поле ввода уехало под адрес"
|
||||
assert over <= 1 and over_open <= 1, f"страница шире экрана: {over} и {over_open}"
|
||||
|
||||
|
||||
def test_contact_readable_in_both_themes(browser, site_in):
|
||||
"""Адрес читается в обеих темах: цвет меняется вместе с темой, прозрачности нет,
|
||||
контраст не ниже 4,5. Порча: задать цвет числом или вписать opacity → проверка упадёт."""
|
||||
ctx, pg = _open(browser, site_in)
|
||||
seen = {}
|
||||
for theme in ("light", "dark"):
|
||||
pg.evaluate(f"document.documentElement.setAttribute('data-theme','{theme}')")
|
||||
seen[theme] = (
|
||||
pg.evaluate("getComputedStyle(document.getElementById('contact-email')).color"),
|
||||
pg.evaluate("getComputedStyle(document.getElementById('input-area')).backgroundColor"),
|
||||
pg.evaluate("getComputedStyle(document.getElementById('contact-line')).opacity"),
|
||||
)
|
||||
ctx.close()
|
||||
for theme, (fg, bg, op) in seen.items():
|
||||
assert float(op) == 1.0, f"{theme}: прозрачность {op}"
|
||||
assert _contrast(fg, bg) >= 4.5, f"{theme}: контраст {_contrast(fg, bg):.1f}"
|
||||
assert seen["light"][0] != seen["dark"][0], "цвет не меняется вместе с темой"
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Полоса «Сайт ещё в разработке» на экране входа: разметка и стили.
|
||||
|
||||
Распоряжение Хозяина 08.09.2026: «добавь банер на главной странице входа, что сайт ещё в
|
||||
разработке. Не менять всю страницу на баннер, а добавить его!» — то есть посадочная часть и
|
||||
форма входа остаются как были, полоса добавляется сверху.
|
||||
|
||||
Red-green: написано ДО правки static/chat.html.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
CHAT = os.path.join(ROOT, "static", "chat.html")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def html():
|
||||
return open(CHAT, encoding="utf-8").read()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def login_block(html):
|
||||
start = html.index('id="login-screen"')
|
||||
end = html.index('id="chat-screen"')
|
||||
return html[start:end]
|
||||
|
||||
|
||||
def _rule(html, prefix):
|
||||
"""Строка правила стилей, начинающаяся ровно с этого селектора: искать подстрокой
|
||||
нельзя — под неё попадают правила тёмной темы, начинающиеся с :root[...]."""
|
||||
return next((ln for ln in html.splitlines() if ln.startswith(prefix)), None)
|
||||
|
||||
|
||||
def _banner_tag(login_block):
|
||||
return re.search(r"<div[^>]*id=\"dev-banner\"[^>]*>", login_block).group(0)
|
||||
|
||||
|
||||
def test_banner_is_inside_login_screen_and_says_in_development(login_block):
|
||||
"""Полоса есть, лежит на экране входа и говорит именно то, что просили.
|
||||
Порча: убрать полосу или сменить текст на «скоро открытие» → проверка упадёт."""
|
||||
assert 'id="dev-banner"' in login_block, "полосы нет на экране входа"
|
||||
body = re.search(r"<div[^>]*id=\"dev-banner\"[^>]*>(.*?)</div>", login_block, re.S).group(1)
|
||||
assert "в разработке" in body.lower()
|
||||
|
||||
|
||||
def test_banner_comes_before_landing(login_block):
|
||||
"""Полоса стоит ПЕРЕД посадочной частью, а не внутри неё: иначе на широком экране это
|
||||
не полоса, а плашка в левом столбце. Порча: перенести внутрь .landing → упадёт."""
|
||||
assert login_block.index('id="dev-banner"') < login_block.index('class="landing"')
|
||||
|
||||
|
||||
def test_banner_is_a_note_not_a_landmark(login_block, html):
|
||||
"""Полоса объявлена примечанием и описывает поле входа. role=banner брать нельзя —
|
||||
он уже занят шапкой чата, двух шапок на странице быть не должно.
|
||||
|
||||
Порча: убрать role или поставить banner → проверка упадёт."""
|
||||
tag = _banner_tag(login_block)
|
||||
assert 'role="note"' in tag
|
||||
assert 'role="banner"' not in tag and "aria-live" not in tag
|
||||
user = re.search(r"<input[^>]*id=\"login-user\"[^>]*>", login_block).group(0)
|
||||
assert 'aria-describedby="dev-banner"' in user, "поле входа не ссылается на примечание"
|
||||
|
||||
|
||||
def test_banner_has_no_controls(login_block):
|
||||
"""Внутри полосы нет кнопок и ссылок: закрытая полоса перестаёт предупреждать того,
|
||||
для кого написана. Порча: добавить крестик → проверка упадёт."""
|
||||
body = re.search(r"<div[^>]*id=\"dev-banner\"[^>]*>(.*?)</div>", login_block, re.S).group(1)
|
||||
assert "<button" not in body and "<a " not in body
|
||||
|
||||
|
||||
def test_banner_layout_rules(html):
|
||||
"""Экран входа выстроен столбцом (иначе полоса встанет узким столбцом сбоку), а сама
|
||||
полоса не растягивается и не вынимается из потока.
|
||||
|
||||
Порча: убрать flex-direction или вписать position: fixed → проверка упадёт."""
|
||||
screen = _rule(html, "#login-screen {")
|
||||
assert screen and "flex-direction: column" in screen
|
||||
band = _rule(html, "#dev-banner {")
|
||||
assert band, "нет правила стилей для полосы"
|
||||
assert "flex: 0 0 auto" in band
|
||||
for forbidden in ("position: fixed", "position: absolute", "white-space: nowrap"):
|
||||
assert forbidden not in band, f"в правиле полосы {forbidden}"
|
||||
|
||||
|
||||
def test_banner_styles_use_theme_variables_only(html):
|
||||
"""Только переменные темы: число вместо переменной не переопределится в тёмной теме.
|
||||
Порча: вписать #fff → проверка упадёт."""
|
||||
band = _rule(html, "#dev-banner {")
|
||||
assert "var(--" in band
|
||||
assert not re.search(r"#[0-9a-fA-F]{3,6}\b", band) and "rgb(" not in band
|
||||
|
||||
|
||||
def test_banner_variables_exist_in_both_themes(html):
|
||||
"""Каждая использованная переменная объявлена и в светлой, и в тёмной теме — иначе
|
||||
цвет молча выпадет. Порча: взять несуществующую --warning → проверка упадёт."""
|
||||
band = _rule(html, "#dev-banner {")
|
||||
used = set(re.findall(r"var\((--[a-z0-9-]+)", band))
|
||||
light = html[html.index(":root {"):]
|
||||
light = light[:light.index("}")]
|
||||
dark = html[html.index(':root[data-theme="dark"] {'):]
|
||||
dark = dark[:dark.index("}")]
|
||||
for name in used:
|
||||
assert f"{name}:" in light, f"{name} не объявлена в светлой теме"
|
||||
if not name.startswith(("--s", "--radius")): # отступы и скругления тема не меняет
|
||||
assert f"{name}:" in dark, f"{name} не объявлена в тёмной теме"
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Полоса «Сайт ещё в разработке» глазами браузера.
|
||||
|
||||
Гоняем настоящий static/chat.html через стенд tests/ui_smoke_harness.py: важно не только
|
||||
наличие полосы в исходнике, но и то, что она не сломала раскладку экрана входа.
|
||||
|
||||
Red-green: написано ДО правки static/chat.html.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
pytest.importorskip("playwright.sync_api", reason="playwright не установлен")
|
||||
|
||||
import ui_smoke_harness # noqa: E402
|
||||
# Стенд и запуск браузера общие с проверками восстановления доступа — второй копии не нужно.
|
||||
from test_password_reset_ui import _launch, browser, site # noqa: E402,F401
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def page(browser, site):
|
||||
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
|
||||
pg = ctx.new_page()
|
||||
pg.set_default_timeout(5000)
|
||||
pg.goto(site)
|
||||
pg.wait_for_selector("#login-form")
|
||||
yield pg
|
||||
ctx.close()
|
||||
|
||||
|
||||
def _box(page, selector):
|
||||
return page.locator(selector).bounding_box()
|
||||
|
||||
|
||||
def test_banner_visible_on_wide_screen(page):
|
||||
"""Полоса одна, видна и целиком помещается в окно.
|
||||
Порча: спрятать полосу или удалить её → проверка упадёт."""
|
||||
assert page.locator("#dev-banner").count() == 1
|
||||
assert page.is_visible("#dev-banner")
|
||||
b = _box(page, "#dev-banner")
|
||||
assert b["y"] >= 0 and b["y"] + b["height"] <= 900
|
||||
assert "в разработке" in page.inner_text("#dev-banner").lower()
|
||||
|
||||
|
||||
def test_banner_spans_top_above_landing(page):
|
||||
"""Полоса тянется во всю ширину и стоит НАД посадочной частью.
|
||||
Порча: убрать flex-direction: column у экрана входа → полоса станет узким столбцом сбоку."""
|
||||
b = _box(page, "#dev-banner")
|
||||
land = _box(page, ".landing")
|
||||
assert b["width"] >= 0.95 * 1280, f"полоса шириной {b['width']}"
|
||||
assert b["y"] + b["height"] <= land["y"] + 1, "полоса не над посадочной частью"
|
||||
|
||||
|
||||
def test_form_stays_beside_hero_on_wide_screen(page):
|
||||
"""Форма входа осталась справа от рассказа о сервисе и целиком в окне — «не менять всю
|
||||
страницу на баннер». Порча: перенос строк у .landing или толстые отступы у полосы →
|
||||
форма уедет вниз или за нижний край."""
|
||||
form = _box(page, "#login-form")
|
||||
hero = _box(page, ".landing-hero")
|
||||
assert form["x"] >= hero["x"] + hero["width"] - 1, "форма съехала под рассказ о сервисе"
|
||||
assert form["y"] < hero["y"] + hero["height"]
|
||||
assert form["y"] + form["height"] <= 900
|
||||
|
||||
|
||||
def test_banner_visible_on_phone_no_sideways_scroll(browser, site):
|
||||
"""На телефоне полоса видна сразу, страница не уезжает вбок и экран не прокручен к форме.
|
||||
Порча: white-space: nowrap → появится боковая прокрутка."""
|
||||
ctx = browser.new_context(viewport={"width": 360, "height": 740})
|
||||
pg = ctx.new_page()
|
||||
pg.set_default_timeout(5000)
|
||||
pg.goto(site)
|
||||
pg.wait_for_selector("#login-form")
|
||||
b = _box(pg, "#dev-banner")
|
||||
over = pg.evaluate(
|
||||
"document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
top = pg.evaluate("document.getElementById('login-screen').scrollTop")
|
||||
hit = pg.evaluate(
|
||||
"([x, y]) => { const e = document.elementFromPoint(x, y);"
|
||||
" return e && e.closest('#dev-banner') !== null; }",
|
||||
[180, b["y"] + b["height"] / 2])
|
||||
ctx.close()
|
||||
assert b["y"] >= 0 and b["y"] + b["height"] <= 740, "полоса не видна на телефоне"
|
||||
assert over <= 1, f"страница шире экрана на {over} точек"
|
||||
assert top == 0, "экран прокручен к форме, полосу человек не увидит"
|
||||
assert hit, "полосу что-то перекрывает"
|
||||
|
||||
|
||||
def test_banner_readable_in_dark_theme(browser, site):
|
||||
"""В тёмной теме текст полосы того же цвета, что заголовок рядом, а фон и рамка меняются
|
||||
вместе с темой. Порча: задать цвет числом → в тёмной теме он останется светлым."""
|
||||
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
|
||||
pg = ctx.new_page()
|
||||
pg.set_default_timeout(5000)
|
||||
pg.goto(site)
|
||||
pg.wait_for_selector("#dev-banner")
|
||||
light_bg = pg.evaluate("getComputedStyle(document.getElementById('dev-banner')).backgroundColor")
|
||||
light_border = pg.evaluate(
|
||||
"getComputedStyle(document.getElementById('dev-banner')).borderBottomColor")
|
||||
pg.evaluate("document.documentElement.setAttribute('data-theme','dark')")
|
||||
dark_bg = pg.evaluate("getComputedStyle(document.getElementById('dev-banner')).backgroundColor")
|
||||
dark_border = pg.evaluate(
|
||||
"getComputedStyle(document.getElementById('dev-banner')).borderBottomColor")
|
||||
color = pg.evaluate("getComputedStyle(document.getElementById('dev-banner')).color")
|
||||
h1 = pg.evaluate("getComputedStyle(document.querySelector('.landing-hero h1')).color")
|
||||
ctx.close()
|
||||
assert color == h1, f"текст полосы {color}, а заголовок {h1}"
|
||||
assert dark_bg != light_bg and dark_border != light_border, "фон полосы не меняется с темой"
|
||||
|
||||
|
||||
def test_login_still_works_and_banner_leaves_with_the_screen(page):
|
||||
"""Вход работает, а после входа полоса уходит вместе с экраном входа — в чате её нет.
|
||||
Порча: вынести полосу на уровень страницы → останется висеть над чатом."""
|
||||
assert page.locator("#dev-banner").count() == 1
|
||||
page.fill("#login-user", "kto@x.ru")
|
||||
page.fill("#login-pass", "parol1")
|
||||
page.click("#login-form button[type=submit]")
|
||||
page.wait_for_selector("#chat-screen", state="visible")
|
||||
assert not page.is_visible("#dev-banner")
|
||||
Reference in New Issue
Block a user