Files
miem_workers/tests/browser_directory_loading.py
T
codex 7f268abde1
CI / test (pull_request) Successful in 12m6s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Skipped
fix: show directory loading and lock filter controls
2026-11-20 11:44:35 +03:00

177 lines
7.8 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.
"""Directory request states with delayed responses; no production access.
Run: python tests/browser_directory_loading.py (Playwright + Chromium required).
"""
import os
from pathlib import Path
import sys
from tempfile import mkdtemp
from urllib.parse import urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from fastapi.testclient import TestClient
from playwright.sync_api import expect, sync_playwright
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.config import Settings, get_settings
from app.db import Base, get_db
from app.main import app
from app.models import Employee
from app.security import SESSION_COOKIE, sign_session
def main():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
factory = sessionmaker(bind=engine)
with factory() as db:
db.add_all([
Employee(profile_key="staff:1", canonical_url="https://www.hse.ru/staff/1",
full_name="Иванов Иван", current_data={"positions": ["Кафедра математики"]}),
Employee(profile_key="staff:2", canonical_url="https://www.hse.ru/staff/2",
full_name="Петров Пётр", current_data={"positions": ["Администрация"]}),
])
db.commit()
def database():
with factory() as db:
yield db
settings = Settings(_env_file=None, session_secret="browser-loading-test-secret")
app.dependency_overrides[get_db] = database
app.dependency_overrides[get_settings] = lambda: settings
client = TestClient(app)
client.cookies.set(SESSION_COOKIE, sign_session(settings.admin_username, settings))
pending = []
output = Path(mkdtemp(prefix="miem-directory-loading-"))
def fulfill(route):
url = urlsplit(route.request.url)
response = client.get(url.path + ("?" + url.query if url.query else ""))
route.fulfill(status=response.status_code, body=response.content,
content_type=response.headers.get("content-type", "text/plain"))
def serve(route):
if route.request.resource_type == "fetch" and urlsplit(route.request.url).path == "/admin/directory":
pending.append(route)
else:
fulfill(route)
try:
with sync_playwright() as playwright:
browser = playwright.chromium.launch(executable_path=os.getenv("BROWSER_EXECUTABLE"))
page = browser.new_page(viewport={"width": 1440, "height": 1000})
page.route("**/*", serve)
errors = []
page.on("pageerror", lambda error: errors.append(str(error)))
page.goto("http://miem.test/admin/directory")
summary = page.locator("[data-directory-summary]")
results = page.locator("[data-directory-results]")
overlay = page.locator("[data-directory-loading]")
search = page.get_by_label("ФИО или ссылка")
pps = page.get_by_label("ППС", exact=True)
apply = page.get_by_role("button", name="Применить фильтры", include_hidden=True)
columns = page.get_by_role("button", name="Настроить колонки")
panel = page.locator(".directory__filter-panel")
# Immediate filter feedback, actual disabled controls, inert links.
pps.check()
expect(overlay).to_be_visible()
expect(summary).to_have_text("Обновляем список…")
expect(pps).to_be_disabled()
expect(columns).to_be_disabled()
expect(apply).to_be_disabled()
expect(search).to_be_disabled()
expect(page.locator("[data-directory-export]")).to_have_attribute("inert", "")
expect(results).to_have_attribute("aria-busy", "true")
page.wait_for_timeout(100)
assert len(pending) == 1
assert "pps=true" in pending[0].request.url
page.screenshot(path=str(output / "desktop-loading.png"), full_page=True)
page.set_viewport_size({"width": 390, "height": 844})
assert page.evaluate("document.documentElement.scrollWidth <= innerWidth")
page.screenshot(path=str(output / "mobile-loading.png"), full_page=True)
fulfill(pending.pop(0))
expect(summary).to_have_text("Показаны 1–1 из 1")
expect(pps).to_be_enabled()
expect(overlay).to_be_hidden()
expect(results).to_have_attribute("aria-busy", "false")
assert "pps=True" in page.locator("[data-directory-export]").get_attribute("href")
# Live search leaves ALL controls usable, including during debounce.
search.fill("Иван")
expect(summary).to_have_text("Идёт поиск…")
expect(search).to_be_enabled()
expect(pps).to_be_enabled()
expect(columns).to_be_enabled()
expect(overlay).to_be_hidden()
page.wait_for_timeout(350)
assert len(pending) == 1
stale = pending.pop(0)
search.fill("Петр")
page.wait_for_timeout(350)
assert len(pending) == 1
fulfill(pending.pop(0))
expect(summary).to_have_text("Показаны 0–0 из 0")
fulfill(stale)
page.wait_for_timeout(100)
expect(summary).to_have_text("Показаны 0–0 из 0")
expect(search).to_have_value("Петр")
# Cancelling back to the applied query must clear the indicator.
search.fill("Петров")
page.wait_for_timeout(350)
stale = pending.pop(0)
search.fill("Петр")
expect(summary).to_have_text("Показаны 0–0 из 0")
fulfill(stale)
page.wait_for_timeout(350)
assert not pending
expect(results).to_have_attribute("aria-busy", "false")
# Manual submission serializes values BEFORE disabling controls.
panel.locator("summary").click()
panel.locator('[name="has_email"]').select_option("true")
apply.click()
expect(apply).to_be_disabled()
expect(overlay).to_be_visible()
page.wait_for_timeout(100)
assert len(pending) == 1
assert "has_email=true" in pending[0].request.url and "pps=true" in pending[0].request.url
fulfill(pending.pop(0))
expect(overlay).to_be_hidden()
expect(panel.locator("summary")).to_contain_text("применены")
assert "has_email=true" in page.url
# Failure preserves results and releases every lock; retry works.
pps.uncheck()
expect(overlay).to_be_visible()
page.wait_for_timeout(100)
pending.pop(0).fulfill(status=503, body="unavailable")
expect(summary).to_contain_text("Не удалось обновить список")
expect(overlay).to_be_hidden()
expect(pps).to_be_enabled()
expect(columns).to_be_enabled()
expect(search).to_be_enabled()
expect(page.locator("[data-directory-export]")).not_to_have_attribute("inert", "")
panel.locator("summary").click()
apply.click()
page.wait_for_timeout(100)
fulfill(pending.pop(0))
expect(summary).to_have_text("Показаны 0–0 из 0")
expect(overlay).to_be_hidden()
assert not errors, errors
browser.close()
finally:
app.dependency_overrides.clear()
client.close()
engine.dispose()
print(f"Directory loading checks passed; screenshots: {output}")
if __name__ == "__main__":
main()