"""Theme Manager: source comparison and real browser/API acceptance on an isolated site.""" from __future__ import annotations import argparse import json import os import shutil import socket import tempfile from pathlib import Path from unittest.mock import patch from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from playwright.sync_api import expect, sync_playwright from qa_001 import PASSWORD, ROOT, serve from site_engine.parsing.yamlio import dump_yaml, load_yaml from site_engine.services.auth import hash_password from site_engine.web.app import create_app from site_engine.web.preview_app import create_preview_app def click(page, action, identity=None): selector = f'button[data-action="{action}"]' if identity is not None: selector += f'[data-id="{identity}"]' page.locator(selector).click() def frame_ready(page): page.wait_for_function( """()=>{const f=document.getElementById('theme-preview'),app=document.getElementById('theme-app'),device=document.querySelector('[data-action=device][aria-pressed=true]')?.dataset.id,target=document.getElementById('theme-preview-target')?.value==='sample'?'sample':'page';return f&&f.dataset.revision===app.dataset.revision&&f.dataset.device===device&&f.dataset.target===target&&+f.dataset.viewportWidth===innerWidth}""", timeout=20000, ) page.frame_locator("#theme-preview").locator( ".sample-site, [data-engine-block]" ).first.wait_for(timeout=20000) # Wait for a resolved resource, not an animation frame inside a passive sandbox. expect(page.locator("#source-preview")).not_to_have_text( "Проверяем текущие изменения…", timeout=20000 ) def styles(page, selector): return page.locator(selector).first.evaluate("""e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return { fontSize:s.fontSize,fontWeight:s.fontWeight,borderRadius:s.borderRadius, padding:s.padding,background:s.backgroundColor,width:r.width,height:r.height }}""") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--out", type=Path, default=Path("/tmp/site-engine-manager-002")) args = parser.parse_args() args.out.mkdir(parents=True, exist_ok=True) report = { "checks": [], "comparisons": [], "page_errors": [], "csp_errors": [], "native_dialogs": [], "unexpected_http": [], "expected_http": [], } with tempfile.TemporaryDirectory(prefix="theme-manager-002-") as tmp: work = Path(tmp) site, state = work / "site", work / "state" shutil.copytree(ROOT / "examples/site-studio", site) # Use the exact source default for component comparison, with no live publication. (site / "theme.yaml").write_text( dump_yaml({"schema": 1, "preset": "minimal", "preset_version": 1, "overrides": {}}) ) env = { "SITE_ROOT": str(site), "SITE_DIST": str(work / "dist"), "SITE_STATE_DIR": str(state), "SITE_ADMIN_LOGIN": "admin", "SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10), "SITE_SECRET_KEY": "theme-manager-browser-secret-" * 3, "SITE_COOKIE_SECURE": "0", "SITE_ADMIN_ORIGIN": "", "SITE_PREVIEW_ORIGIN": "", } reference = FastAPI() reference.mount("/", StaticFiles(directory=ROOT / "design", html=True)) with ( patch.dict(os.environ, env), serve(create_app()) as origin, serve(reference) as source_origin, sync_playwright() as pw, ): browser = pw.chromium.launch( channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"] ) context = browser.new_context(viewport={"width": 1440, "height": 1050}) page = context.new_page() source = context.new_page() expected_errors = set() def watch(p): p.on("pageerror", lambda e: report["page_errors"].append(str(e))) p.on( "console", lambda m: ( report["csp_errors"].append(m.text) if "Content Security Policy" in m.text or "violates" in m.text else None ), ) p.on("dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss())) p.on( "response", lambda r: ( ( report["expected_http"] if any(x in r.url for x in expected_errors) else report["unexpected_http"] ).append([r.status, r.url.split("?")[0]]) if r.status >= 400 and not r.url.endswith("/favicon.ico") else None ), ) watch(page) page.goto(origin + "/admin/login") page.locator("[name=login]").fill("admin") page.locator("[name=password]").fill(PASSWORD) page.get_by_role("button", name="Войти", exact=True).click() page.wait_for_url(origin + "/admin/") page.goto(origin + "/admin/theme") source.goto(source_origin + "/theme-studio-antirion.html") frame_ready(page) initial = (site / "theme.yaml").read_bytes() expect(page.locator("[data-action=preset]")).to_have_count(6) assert page.locator("[data-action=preset]").evaluate_all( "(ns)=>ns.map(n=>n.dataset.id)" ) == ["minimal", "dark", "editorial", "bold", "natural", "custom"] # The source shell is deliberately not transplanted: existing admin skin is retained. original_shell = styles(page, ".sidebar") for width in (1440, 1280, 1024, 768, 390, 360): for p in (page, source): p.set_viewport_size({"width": width, "height": 1050}) for step in range(4): print(f"source comparison {width}px step {step + 1}", flush=True) click(page, "step", str(step)) click(source, "step", str(step)) assert page.evaluate("document.documentElement.scrollWidth<=innerWidth+1"), ( width, step, ) # Exact designer component metrics, excluding textual changes and the persistent shell. for selector in ( ".theme-heading h1", ".theme-section-head h2", ".step-button", ".preset-option" if step == 0 else ".wz-subtitle", ): actual, ref = styles(page, selector), styles(source, selector) for key in ("fontSize", "borderRadius", "padding"): assert actual[key] == ref[key], ( width, step, selector, key, actual, ref, ) report["comparisons"].append( { "width": width, "step": step, "selector": selector, "actual": actual, "source": ref, } ) frame_ready(page) if step == 0: actual_hero = ( page.frame_locator("#theme-preview") .locator(".sample-hero") .evaluate("e=>getComputedStyle(e).paddingTop") ) source_hero = source.locator(".sample-hero").evaluate( "e=>getComputedStyle(e).paddingTop" ) assert actual_hero == source_hero, (width, actual_hero, source_hero) actual_nav = ( page.frame_locator("#theme-preview") .locator(".sample-nav-links") .evaluate("e=>getComputedStyle(e).display") ) source_nav = source.locator(".sample-nav-links").evaluate( "e=>getComputedStyle(e).display" ) assert actual_nav == source_nav, (width, actual_nav, source_nav) page.evaluate( "document.getElementById('theme-preview')?.scrollIntoView({block:'center'})" ) page.wait_for_timeout(120) if step == 3: page.screenshot(path=str(args.out / f"manager-{width}-preview.png")) page.evaluate("window.scrollTo(0,0)") page.wait_for_timeout(60) page.screenshot( path=str(args.out / f"manager-{width}-step{step + 1}.png"), full_page=True ) source.screenshot( path=str(args.out / f"source-{width}-step{step + 1}.png"), full_page=True ) click(page, "device", "phone") frame_ready(page) assert page.locator("#theme-preview").bounding_box()["width"] <= 315 click(page, "device", "desktop") frame_ready(page) report["checks"].append( "24 source UI comparisons × 4 components, six widths, all steps and devices, no overflow" ) page.set_viewport_size({"width": 1440, "height": 1050}) click(page, "step", "0") # Every server preset renders through the same stand, with no file writes. for preset in ("minimal", "dark", "editorial", "bold", "natural", "custom"): click(page, "preset", preset) if page.locator("#theme-confirm.open").count(): click(page, "confirm-yes") frame_ready(page) expect(page.locator(f"[data-action=preset][data-id={preset}]")).to_have_attribute( "aria-pressed", "true" ) page.screenshot(path=str(args.out / f"preset-{preset}.png")) assert (site / "theme.yaml").read_bytes() == initial report["checks"].append("Six presets, source confirmation, zero auto-save") click(page, "step", "1") field = page.locator('[data-field="color:primary"]') field.fill("#123456") frame_ready(page) expect(page.locator("#source-preview")).to_contain_text("#123456") # A late response for older input cannot replace the newer snapshot. held = [] def hold_first(route): part = route.request.post_data.split('name="payload"', 1)[1].split("\r\n\r\n", 1)[1] payload = json.loads(part.rsplit("\r\n--", 1)[0]) if not held: held.append((route, payload["revision"])) else: route.continue_() page.route("**/admin/theme/preview", hold_first) with page.expect_request("**/admin/theme/preview"): field.fill("#112233") page.wait_for_timeout(50) assert held field.fill("#334455") frame_ready(page) newest = page.locator("#theme-preview").get_attribute("src") held[0][0].fulfill( status=200, content_type="application/json", body=json.dumps( { "url": "about:blank", "revision": held[0][1], "interactive": False, "snapshot": "obsolete", "expires_at": 0, } ), ) page.wait_for_timeout(100) assert page.locator("#theme-preview").get_attribute("src") == newest page.unroute("**/admin/theme/preview") field.fill("#123456") frame_ready(page) before_step = page.locator("#theme-preview").element_handle() click(page, "step", "2") assert before_step.evaluate("e=>e===document.getElementById('theme-preview')") click(page, "step", "1") report["checks"].append( "Delayed old preview ignored; step selection retains the same iframe" ) page.locator("#new-color-name").fill("promo_highlight") click(page, "add-color") expect(page.locator("[data-extra-color=promo_highlight]")).to_be_visible() page.locator("[data-gradient-toggle]").check() click(page, "add-stop") frame_ready(page) assert page.locator("[data-gradient-stop]").count() == 3 page.locator("#new-gradient-name").fill("promo_bg") click(page, "add-gradient") frame_ready(page) expect(page.locator("[data-action=gradient-role][data-id=promo_bg]")).to_be_visible() click(page, "remove-gradient", "promo_bg") expect(page.locator("button[data-action=confirm-no]")).to_be_focused() page.keyboard.press("Shift+Tab") expect(page.locator("[data-action=confirm-yes]")).to_be_focused() page.keyboard.press("Tab") expect(page.locator("button[data-action=confirm-no]")).to_be_focused() page.keyboard.press("Escape") expect(page.locator("#theme-confirm")).not_to_have_class("open") click(page, "step", "2") click(page, "font-pair", "classic") page.locator('[data-field="type:heading"]').select_option("Arial, sans-serif") frame_ready(page) click(page, "step", "3") click(page, "container-mode", "fluid") page.locator("[data-container-gutter=mobile]").fill("0") click(page, "choice", "button:outline") frame_ready(page) assert (site / "theme.yaml").read_bytes() == initial # Real page and component stand are both immutable snapshots of unsaved input. page.locator("#theme-preview-target").select_option("index") frame_ready(page) expect( page.frame_locator("#theme-preview").locator("[data-engine-block]").first ).to_be_visible() page.screenshot(path=str(args.out / "real-page-overlay.png"), full_page=True) page.locator("#theme-preview-target").select_option("sample") frame_ready(page) report["checks"].append( "Colors, custom tokens, gradients/stops, fonts, widths and real-page overlay; keyboard modal containment" ) with page.expect_download() as dl: click(page, "yaml-download") download = dl.value export = load_yaml(Path(download.path()).read_text()) assert export["schema"] == 1 and export["overrides"]["colors"]["primary"] == "#123456" assert export["overrides"]["ui"]["container"]["gutter"]["mobile"] == 0 report["checks"].append("Server-validated YAML/export, including zero gutters") # Deliberately invalid values: visible error and untouched file, then recovery. click(page, "step", "1") expected_errors.add("/admin/theme/validate") page.locator('[data-field="color:primary"]').fill("bad") expect(page.locator("#theme-diagnostics")).to_contain_text("HEX", timeout=10000) expect(page.locator("[data-action=save]")).to_be_disabled() assert (site / "theme.yaml").read_bytes() == initial page.locator('[data-field="color:primary"]').fill("#123456") frame_ready(page) expect(page.locator("[data-action=save]")).to_be_enabled() # Two real tabs: second commit wins; first receives current snapshot and keeps its edits. second = context.new_page() watch(second) second.goto(origin + "/admin/theme") frame_ready(second) click(second, "preset", "dark") frame_ready(second) click(second, "save") expect(second.locator(".save-note")).to_contain_text( "Сохранено в workspace", timeout=10000 ) expected_errors.add("/admin/theme/save") click(page, "save") expect(page.locator("#theme-request-error")).to_contain_text("conflict", timeout=10000) expect(page.locator('[data-field="color:primary"]')).to_have_value("#123456") assert load_yaml((site / "theme.yaml").read_text())["preset"] == "dark" page.screenshot(path=str(args.out / "conflict-keeps-input.png"), full_page=True) click(page, "conflict-rebase") click(page, "confirm-yes") click(page, "save") expect(page.locator(".save-note")).to_contain_text( "Сохранено в workspace", timeout=10000 ) assert ( load_yaml((site / "theme.yaml").read_text())["overrides"]["colors"]["primary"] == "#123456" ) assert ( json.loads((state / "theme-onboarding.json").read_text())["status"] == "completed" ) assert not (work / "dist/current").exists() report["checks"].append( "Invalid input blocked; two editors 409/current + explicit rebase; Save completes workflow without publishing" ) # A real HTTP 500, then failed transport: edits and focus survive both. page.locator('[data-field="color:primary"]').fill("#654321") frame_ready(page) page.route( "**/admin/theme/save", lambda route: route.fulfill( status=500, content_type="application/json", body=json.dumps( { "error": { "code": "qa_failure", "message": "Ошибка сохранения · QA", "request_id": "test-request-id", } } ), ), ) click(page, "save") expect(page.locator("#theme-request-error")).to_contain_text("test-request-id") expect(page.locator('[data-field="color:primary"]')).to_have_value("#654321") page.unroute("**/admin/theme/save") page.route("**/admin/theme/save", lambda route: route.abort("failed")) click(page, "save") expect(page.locator("#theme-request-error")).to_contain_text("network_error") expect(page.locator('[data-field="color:primary"]')).to_have_value("#654321") page.unroute("**/admin/theme/save") assert ( load_yaml((site / "theme.yaml").read_text())["overrides"]["colors"]["primary"] == "#123456" ) report["checks"].append( "HTTP 500/request_id and transport failure visible; unsaved input and saved file preserved" ) # Leaving asks through source modal; cancellation keeps form. page.locator('a[href="/admin/pages"]').first.click() expect(page.locator("#theme-confirm")).to_have_class("open") click(page, "confirm-no") expect(page.locator('[data-field="color:primary"]')).to_have_value("#654321") click(page, "reset-onboarding") click(page, "confirm-yes") expect(page.locator('[data-action=step][data-id="0"]')).to_have_attribute( "aria-current", "step" ) assert ( json.loads((state / "theme-onboarding.json").read_text())["status"] == "in_progress" ) assert ( load_yaml((site / "theme.yaml").read_text())["overrides"]["colors"]["primary"] == "#123456" ) click(page, "skip") click(page, "confirm-yes") page.wait_for_url(origin + "/admin/") assert json.loads((state / "theme-onboarding.json").read_text())["status"] == "skipped" report["checks"].append( "Navigation cancel, repeat and skip persist independently of theme/live" ) page.goto(origin + "/admin/theme") frame_ready(page) assert styles(page, ".sidebar")["background"] == original_shell["background"] assert not page.evaluate( "Object.keys(localStorage).some(x=>x.includes('theme-manager'))" ) assert not report["page_errors"], report["page_errors"] assert not report["csp_errors"], report["csp_errors"] assert not report["native_dialogs"], report["native_dialogs"] assert not report["unexpected_http"], report["unexpected_http"] second.close() # Separate-origin immutable preview uses the existing nonce bridge/CSP. a = socket.socket() a.bind(("127.0.0.1", 0)) p = socket.socket() p.bind(("127.0.0.1", 0)) with ( patch.dict( os.environ, { "SITE_ADMIN_ORIGIN": f"http://127.0.0.1:{a.getsockname()[1]}", "SITE_PREVIEW_ORIGIN": f"http://127.0.0.1:{p.getsockname()[1]}", }, ), serve(create_app(), a) as admin2, serve(create_preview_app(), p) as preview2, ): interactive_context = browser.new_context(viewport={"width": 1440, "height": 1050}) interactive = interactive_context.new_page() watch(interactive) interactive.goto(admin2 + "/admin/login") interactive.locator("[name=login]").fill("admin") interactive.locator("[name=password]").fill(PASSWORD) interactive.get_by_role("button", name="Войти", exact=True).click() interactive.goto(admin2 + "/admin/theme") frame_ready(interactive) expect(interactive.locator("#theme-preview")).to_have_attribute( "sandbox", "allow-scripts allow-same-origin" ) assert ( interactive.locator("#theme-preview") .get_attribute("src") .startswith(preview2 + "/s/") ) expect( interactive.frame_locator("#theme-preview").locator(".sample-card") ).to_have_count(3) interactive.screenshot(path=str(args.out / "separate-origin.png"), full_page=True) interactive_context.close() report["checks"].append( "Passive and separate-origin nonce preview, unchanged admin skin, no storage/native dialogs/CSP/JS/unexpected HTTP errors" ) assert not report["page_errors"], report["page_errors"] assert not report["csp_errors"], report["csp_errors"] assert not report["native_dialogs"], report["native_dialogs"] assert not report["unexpected_http"], report["unexpected_http"] browser.close() (args.out / "browser.json").write_text(json.dumps(report, ensure_ascii=False, indent=2)) print( json.dumps( { "checks": len(report["checks"]), "comparisons": len(report["comparisons"]), "out": str(args.out), }, ensure_ascii=False, ) ) if __name__ == "__main__": main()