Первый визит больше не уходит в тёмную тему из-за системной настройки: без сохранённого выбора страница светлая. Переключатель по-прежнему главнее системы, выбор остаётся после перезагрузки. Проверка на первую страницу смотрит системную тёмную настройку и повторный визит. Co-Authored-By: Claude Code <noreply@anthropic.com>
266 lines
16 KiB
Python
266 lines
16 KiB
Python
"""Первая страница (вариант А, 18.11.2026): витрина для сметчика.
|
||
|
||
Что проверяем:
|
||
* герой с обещанием результата, «Знакомо?» и пары «боль → снимок → решение»;
|
||
* снимки — настоящие файлы продукта, с alt и размерами, все загрузились;
|
||
* форма входа ОДНА, с прежними id и обработчиками: «Забыли пароль?» открывает
|
||
восстановление, «Вернуться ко входу» возвращает;
|
||
* на телефоне 360 px нет горизонтальной прокрутки;
|
||
* тёмная тема применяется к первой странице (карточка входа не белая);
|
||
* обещание пробного доступа и ссылка на цены на месте.
|
||
|
||
Мутации: убрать снимок → падает проверка картинок; убрать openReset → падает
|
||
проверка восстановления; вернуть фиксированную ширину → падает проверка 360 px.
|
||
"""
|
||
import functools
|
||
import http.server
|
||
import shutil
|
||
import socketserver
|
||
import sys
|
||
import threading
|
||
|
||
import pytest
|
||
|
||
ROOT = __file__.rsplit("/tests/", 1)[0]
|
||
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
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def site(tmp_path_factory):
|
||
d = tmp_path_factory.mktemp("ui-landing")
|
||
ui_smoke_harness.build_stub(d / "index.html", logged_in=False)
|
||
# Страница ссылается на боевые пути /static/... — кладём рядом те же файлы.
|
||
(d / "static").mkdir()
|
||
shutil.copytree(f"{ROOT}/static/landing", d / "static" / "landing")
|
||
for имя in ("contacts.png", "contacts-dark.png"):
|
||
shutil.copy(f"{ROOT}/static/{имя}", d / "static" / имя)
|
||
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()
|
||
srv.server_close()
|
||
|
||
|
||
def _страница(browser, site, width=1280, height=900, color_scheme=None):
|
||
opts = {"viewport": {"width": width, "height": height}}
|
||
if color_scheme:
|
||
opts["color_scheme"] = color_scheme
|
||
ctx = browser.new_context(**opts)
|
||
pg = ctx.new_page()
|
||
pg.set_default_timeout(8000)
|
||
pg._errors = []
|
||
pg.on("pageerror", lambda e: pg._errors.append(str(e)))
|
||
try:
|
||
pg.goto(site)
|
||
pg.wait_for_selector("#login-screen", state="visible")
|
||
except Exception:
|
||
ctx.close() # упавший до yield тест не должен оставлять контекст висеть
|
||
raise
|
||
return pg, ctx
|
||
|
||
|
||
@pytest.fixture()
|
||
def page(browser, site):
|
||
pg, ctx = _страница(browser, site)
|
||
try:
|
||
yield pg
|
||
finally:
|
||
ctx.close()
|
||
|
||
|
||
def test_герой_боли_и_решения_на_месте(page):
|
||
"""Страница показывает боль сметчика и решение — а не только список возможностей."""
|
||
assert "Сметчик, выдыхай" in page.inner_text("h1")
|
||
assert page.locator(".pain").count() == 3, "нет трёх типичных ситуаций"
|
||
assert page.locator(".pair.landing-card").count() == 3, "нет пар «боль → решение»"
|
||
assert "Знакомо" in page.inner_text("#pains-h")
|
||
assert "А если так" in page.inner_text("#pairs-h")
|
||
|
||
|
||
def test_снимки_продукта_загрузились_и_описаны(page):
|
||
"""Снимки — настоящие файлы продукта: все загрузились, у каждого alt."""
|
||
# Нижние снимки помечены loading="lazy": без прокрутки браузер их законно не грузит.
|
||
page.evaluate("() => { const el = document.getElementById('login-screen'); el.scrollTo(0, el.scrollHeight); }")
|
||
page.wait_for_function("""() => [...document.querySelectorAll('img[src^="/static/landing/"]')]
|
||
.every(i => i.complete && i.naturalWidth > 0)""")
|
||
снимки = page.locator('img[src^="/static/landing/"]')
|
||
assert снимки.count() == 4, "ожидалось четыре места со снимками интерфейса"
|
||
файлы = set(page.evaluate("""() => [...document.querySelectorAll('img[src^="/static/landing/"]')]
|
||
.map(i => i.getAttribute('src'))"""))
|
||
assert len(файлы) == 3, f"должно быть три разных снимка: {sorted(файлы)}"
|
||
данные = page.evaluate("""() => [...document.querySelectorAll('img[src^="/static/landing/"]')]
|
||
.map(i => ({src: i.getAttribute('src'), ok: i.complete && i.naturalWidth > 0,
|
||
alt: (i.getAttribute('alt') || '').trim(),
|
||
w: i.getAttribute('width'), h: i.getAttribute('height')}))""")
|
||
for с in данные:
|
||
assert с["ok"], f"снимок не загрузился: {с['src']}"
|
||
assert с["alt"], f"у снимка нет alt: {с['src']}"
|
||
assert с["w"] and с["h"], f"не заданы размеры снимка: {с['src']}"
|
||
|
||
|
||
def test_форма_входа_одна_и_восстановление_работает(page):
|
||
"""Одна форма входа с прежними id; ссылка «Забыли пароль?» открывает восстановление."""
|
||
assert page.locator("#login-form").count() == 1, "форм входа должно быть ровно одна"
|
||
assert page.locator("#reset-form").count() == 1, "форма восстановления пропала"
|
||
assert not page.locator("#reset-form").is_visible()
|
||
page.click("#forgot-link")
|
||
page.wait_for_selector("#reset-form", state="visible")
|
||
assert not page.locator("#login-form").is_visible()
|
||
page.click("#reset-back")
|
||
page.wait_for_selector("#login-form", state="visible")
|
||
assert not page.locator("#reset-form").is_visible()
|
||
assert not page._errors, page._errors
|
||
|
||
|
||
def test_пробный_доступ_и_цены_на_месте(page):
|
||
"""Обещание пробы и ссылка на цены — как на прежней странице (число подставит сервер)."""
|
||
текст = page.inner_text("#login-screen")
|
||
assert "Попробовать можно без оплаты" in текст
|
||
assert page.locator('a[href="/static/pricing.html"]').count() >= 2
|
||
assert page.get_attribute("a.btn-ghost", "href") == "/register"
|
||
|
||
|
||
def test_кнопка_войти_ведёт_к_форме(page):
|
||
"""Кнопка героя не дублирует форму, а прокручивает к единственной — и та видна."""
|
||
page.evaluate("() => document.getElementById('login-screen').scrollTo(0, 0)")
|
||
page.click(".btn-primary")
|
||
page.wait_for_timeout(500)
|
||
данные = page.evaluate("""() => {
|
||
const el = document.getElementById('login-screen');
|
||
const r = document.getElementById('login-card').getBoundingClientRect();
|
||
return {top: Math.round(r.top), scrollTop: Math.round(el.scrollTop)};
|
||
}""")
|
||
assert данные["scrollTop"] > 300, f"страница не прокрутилась к форме: {данные}"
|
||
assert 0 <= данные["top"] < 900, f"форма не попала в экран: {данные}"
|
||
# Если было открыто восстановление, «Войти» обязан вернуть форму входа, а не привести
|
||
# к форме восстановления (нашёл GPT 18.11.2026).
|
||
page.click("#forgot-link")
|
||
page.wait_for_selector("#reset-form", state="visible")
|
||
page.evaluate("() => document.getElementById('login-screen').scrollTo(0, 0)")
|
||
page.click(".btn-primary")
|
||
page.wait_for_timeout(500)
|
||
assert page.locator("#login-form").is_visible(), "кнопка «Войти» оставила восстановление"
|
||
assert not page.locator("#reset-form").is_visible()
|
||
|
||
|
||
def test_ошибка_входа_видна_человеку(page):
|
||
"""Путь отказа формы работает после переноса разметки: сервер сказал причину — она на экране."""
|
||
page.evaluate("() => { window._mode = 'unconfirmed'; }")
|
||
page.fill("#login-user", "кто-то@пример.рф")
|
||
page.fill("#login-pass", "пароль")
|
||
page.click('#login-form button[type="submit"]')
|
||
page.wait_for_selector("#login-error", state="visible")
|
||
assert "подтвержд" in page.inner_text("#login-error").lower()
|
||
assert not page._errors, page._errors
|
||
|
||
|
||
def test_двухфакторный_вход_работает_после_переноса_формы(page):
|
||
"""Сервер просит код 2FA — поле появляется и второй запрос завершает вход."""
|
||
page.evaluate("() => { window._mode = 'totp'; }")
|
||
page.fill("#login-user", "кто-то@пример.рф")
|
||
page.fill("#login-pass", "пароль")
|
||
page.click('#login-form button[type="submit"]')
|
||
page.wait_for_selector("#login-totp", state="visible")
|
||
# текст сообщения ставится через 30 мс (showBox) — ждём его, а не читаем сразу
|
||
page.wait_for_function(
|
||
"() => document.getElementById('login-notice').textContent.toLowerCase().includes('код')")
|
||
assert "код" in page.inner_text("#login-notice").lower()
|
||
page.evaluate("() => { window._mode = null; }")
|
||
page.fill("#login-totp", "123456")
|
||
page.click('#login-form button[type="submit"]')
|
||
page.wait_for_selector("#chat-screen", state="visible")
|
||
assert not page._errors, page._errors
|
||
|
||
|
||
def test_фокус_после_показа_на_заголовке(page):
|
||
"""Клавиатурный человек начинает с заголовка витрины, а не прыгает в поле внизу."""
|
||
активен = page.evaluate("() => document.activeElement && document.activeElement.tagName")
|
||
assert активен == "H1", f"фокус не на заголовке: {активен}"
|
||
assert not page._errors, page._errors
|
||
|
||
|
||
def test_на_телефоне_нет_горизонтальной_прокрутки(browser, site):
|
||
"""360 px — самый узкий из поддерживаемых: страница не должна ехать вбок."""
|
||
pg, ctx = _страница(browser, site, width=360, height=800)
|
||
try:
|
||
# Прокрутка живёт внутри #login-screen (overflow-y:auto) — меряем именно его.
|
||
размеры = pg.evaluate("""() => {
|
||
const el = document.getElementById('login-screen');
|
||
return [el.scrollWidth, el.clientWidth,
|
||
document.documentElement.scrollWidth, document.documentElement.clientWidth];
|
||
}""")
|
||
assert размеры[0] == размеры[1], f"горизонтальная прокрутка на экране входа: {размеры}"
|
||
assert размеры[2] == размеры[3], f"горизонтальная прокрутка страницы: {размеры}"
|
||
assert pg.locator("#login-form").is_visible()
|
||
assert not pg._errors, pg._errors
|
||
finally:
|
||
ctx.close()
|
||
|
||
|
||
def test_витрина_следует_теме_и_помнит_выбор(browser, site):
|
||
"""Схема сохраняется при переходе между страницами и для незалогиненного: витрина
|
||
следует сохранённому выбору (светлая — палитра макета А, тёмная — палитра чата),
|
||
а переключатель на ней меняет тему и запоминает выбор."""
|
||
pg, ctx = _страница(browser, site)
|
||
try:
|
||
pg.evaluate("() => localStorage.setItem('theme', 'dark')")
|
||
pg.reload()
|
||
pg.wait_for_selector("#login-screen", state="visible")
|
||
assert pg.evaluate("() => document.documentElement.getAttribute('data-theme')") == "dark"
|
||
фон = pg.evaluate("() => getComputedStyle(document.getElementById('login-screen')).backgroundImage")
|
||
карточка = pg.evaluate("() => getComputedStyle(document.getElementById('login-form')).backgroundColor")
|
||
текст = pg.evaluate("() => getComputedStyle(document.querySelector('.landing-trial')).color")
|
||
assert "rgb(27, 24, 19)" in фон, f"витрина не в тёмной палитре: {фон}"
|
||
assert карточка == "rgb(33, 29, 23)", f"карточка не тёмная: {карточка}"
|
||
assert текст == "rgb(236, 228, 215)", f"текст не светлый: {текст}"
|
||
assert pg.inner_text("#login-fab") == "☀"
|
||
# переключатель на витрине: тёмная → светлая, выбор запоминается
|
||
pg.click("#login-fab")
|
||
assert pg.evaluate("() => localStorage.getItem('theme')") == "light"
|
||
assert pg.evaluate("() => document.documentElement.getAttribute('data-theme')") == "light"
|
||
фон2 = pg.evaluate("() => getComputedStyle(document.getElementById('login-screen')).backgroundColor")
|
||
assert фон2 == "rgb(246, 241, 234)", f"светлая витрина не в палитре макета: {фон2}"
|
||
assert pg.inner_text("#login-fab") == "☾"
|
||
# чат после входа — тоже по выбранной светлой теме
|
||
pg.fill("#login-user", "кто-то@пример.рф")
|
||
pg.fill("#login-pass", "пароль")
|
||
pg.click('#login-form button[type="submit"]')
|
||
pg.wait_for_selector("#chat-screen", state="visible")
|
||
шапка = pg.evaluate("() => getComputedStyle(document.getElementById('header')).backgroundColor")
|
||
assert шапка == "rgb(255, 255, 255)", f"чат не в светлой теме: {шапка}"
|
||
assert not pg._errors, pg._errors
|
||
finally:
|
||
ctx.close()
|
||
|
||
|
||
def test_первый_визит_светлый_даже_при_тёмной_системе(browser, site):
|
||
"""Первый визит без сохранённого выбора — светлая тема, даже если система тёмная.
|
||
Выбор пользователя по-прежнему главнее: переключил в тёмную — она и останется."""
|
||
pg, ctx = _страница(browser, site, color_scheme="dark")
|
||
try:
|
||
assert pg.evaluate("() => localStorage.getItem('theme')") is None
|
||
assert pg.evaluate("() => document.documentElement.getAttribute('data-theme')") == "light"
|
||
фон = pg.evaluate("() => getComputedStyle(document.getElementById('login-screen')).backgroundColor")
|
||
assert фон == "rgb(246, 241, 234)", f"первый визит не в светлой палитре: {фон}"
|
||
pg.click("#login-fab")
|
||
assert pg.evaluate("() => localStorage.getItem('theme')") == "dark"
|
||
assert pg.evaluate("() => document.documentElement.getAttribute('data-theme')") == "dark"
|
||
pg.reload()
|
||
pg.wait_for_selector("#login-screen", state="visible")
|
||
assert pg.evaluate("() => document.documentElement.getAttribute('data-theme')") == "dark"
|
||
assert not pg._errors, pg._errors
|
||
finally:
|
||
ctx.close()
|