Integrate Content Editor and Publication workflow
This commit is contained in:
+10
-10
@@ -57,7 +57,7 @@ def main():
|
||||
work = Path(temp)
|
||||
site = work / "site"
|
||||
shutil.copytree(
|
||||
ROOT / "examples/studio-site", site, ignore=shutil.ignore_patterns(".engine")
|
||||
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
|
||||
)
|
||||
env = {
|
||||
"SITE_ROOT": str(site),
|
||||
@@ -69,7 +69,7 @@ def main():
|
||||
"SITE_COOKIE_SECURE": "0",
|
||||
}
|
||||
with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
|
||||
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 960})
|
||||
page.on("pageerror", lambda exc: results["console_errors"].append(str(exc)))
|
||||
page.goto(origin + "/admin/login")
|
||||
@@ -82,7 +82,7 @@ def main():
|
||||
("/admin/", "overview"),
|
||||
("/admin/pages", "pages"),
|
||||
("/admin/pages/index", "page"),
|
||||
("/admin/pages/index/blocks/b_hero", "block"),
|
||||
("/admin/pages/index/blocks/hero_home", "block"),
|
||||
("/admin/content", "collections"),
|
||||
("/admin/content/services", "entries"),
|
||||
("/admin/content/services/bots", "entry"),
|
||||
@@ -140,24 +140,24 @@ def main():
|
||||
results["widths"].append([mode + "-dark", width])
|
||||
page.screenshot(path=str(args.out / "expert-dark-mobile.png"))
|
||||
page.goto(origin + "/admin/publish")
|
||||
invoker = page.get_by_role(
|
||||
"button", name="Опубликовать текущий черновик сайта", exact=True
|
||||
)
|
||||
page.locator('[data-pub-action=candidate]').first.click()
|
||||
page.locator('[data-publication-root][aria-busy=false]').wait_for()
|
||||
invoker = page.locator('[data-pub-action=publish]')
|
||||
invoker.click()
|
||||
page.locator("#confirm-dialog").wait_for(state="visible")
|
||||
page.locator("#publication-modal-root dialog[open]").wait_for(state="visible")
|
||||
for _ in range(4):
|
||||
page.keyboard.press("Tab")
|
||||
assert page.locator("#confirm-dialog").evaluate(
|
||||
assert page.locator("#publication-modal-root dialog").evaluate(
|
||||
"(e)=>e.contains(document.activeElement)"
|
||||
)
|
||||
page.keyboard.press("Escape")
|
||||
assert not page.locator("#confirm-dialog").is_visible()
|
||||
assert not page.locator("#publication-modal-root dialog").is_visible()
|
||||
assert invoker.evaluate("(e)=>e===document.activeElement")
|
||||
assert not results["console_errors"], results["console_errors"]
|
||||
browser.close()
|
||||
# Reference is rendered from its own assets, independent of the runtime package.
|
||||
with sync_playwright() as pw:
|
||||
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 960})
|
||||
page.goto((ROOT / "design/antirion-rework.html").as_uri())
|
||||
page.screenshot(path=str(args.out / "reference-antirion.png"), full_page=True)
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
"""Original Content design versus real FastAPI: geometry, flows and both preview origins."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from contextlib import ExitStack
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
from qa_001 import PASSWORD, ROOT, serve
|
||||
from qa_editor_updates import idle, reserve
|
||||
from starlette.applications import Starlette
|
||||
from starlette.routing import Mount
|
||||
from starlette.staticfiles import StaticFiles
|
||||
|
||||
from site_engine.build.pipeline import build_site
|
||||
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
|
||||
|
||||
OUT = Path(os.environ.get("QA_CONTENT_OUT", "/tmp/site-engine-content-001"))
|
||||
|
||||
|
||||
def metrics(page, selectors):
|
||||
return page.evaluate(
|
||||
"""selectors=>Object.fromEntries(selectors.map(s=>{
|
||||
const e=document.querySelector(s),c=getComputedStyle(e),r=e.getBoundingClientRect();
|
||||
return [s,{width:r.width,height:r.height,font:c.fontSize,padding:c.padding,
|
||||
color:c.color,background:c.backgroundColor,columns:c.gridTemplateColumns}];
|
||||
}))""",
|
||||
selectors,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
report = {
|
||||
"runs": [],
|
||||
"comparisons": [],
|
||||
"page_errors": [],
|
||||
"native_dialogs": [],
|
||||
"console_errors": [],
|
||||
"expected_errors": [],
|
||||
}
|
||||
with sync_playwright() as pw:
|
||||
browser = pw.chromium.launch(
|
||||
channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
|
||||
)
|
||||
for interactive in (False, True):
|
||||
run = {"interactive": interactive, "checks": []}
|
||||
report["runs"].append(run)
|
||||
with (
|
||||
tempfile.TemporaryDirectory(prefix="content-design-qa-") as tmp,
|
||||
ExitStack() as stack,
|
||||
):
|
||||
work, site = Path(tmp), Path(tmp) / "site"
|
||||
shutil.copytree(
|
||||
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
|
||||
)
|
||||
original_file = (site / "content/services/bots.md").read_bytes()
|
||||
build_site(site, work / "dist")
|
||||
admin_socket, preview_socket = reserve(), reserve()
|
||||
admin = "http://127.0.0.1:" + str(admin_socket.getsockname()[1])
|
||||
preview = "http://127.0.0.1:" + str(preview_socket.getsockname()[1])
|
||||
stack.enter_context(
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"SITE_ROOT": str(site),
|
||||
"SITE_DIST": str(work / "dist"),
|
||||
"SITE_STATE_DIR": str(work / "state"),
|
||||
"SITE_ADMIN_LOGIN": "admin",
|
||||
"SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
|
||||
"SITE_SECRET_KEY": "content-browser-secret-" * 4,
|
||||
"SITE_COOKIE_SECURE": "0",
|
||||
"SITE_ADMIN_ORIGIN": admin if interactive else "",
|
||||
"SITE_PREVIEW_ORIGIN": preview if interactive else "",
|
||||
},
|
||||
)
|
||||
)
|
||||
app, gate = create_app(), {"delay": 0}
|
||||
|
||||
@app.middleware("http")
|
||||
async def delay(request, call_next, gate=gate):
|
||||
if (
|
||||
request.url.path.endswith("/update")
|
||||
and request.url.path.startswith("/admin/editor/")
|
||||
and gate["delay"]
|
||||
):
|
||||
delay, gate["delay"] = gate["delay"], 0
|
||||
await asyncio.sleep(delay)
|
||||
return await call_next(request)
|
||||
|
||||
stack.enter_context(serve(app, admin_socket))
|
||||
if interactive:
|
||||
stack.enter_context(serve(create_preview_app(), preview_socket))
|
||||
else:
|
||||
preview_socket.close()
|
||||
design_origin = stack.enter_context(
|
||||
serve(
|
||||
Starlette(
|
||||
routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))]
|
||||
)
|
||||
)
|
||||
)
|
||||
context = browser.new_context(
|
||||
viewport={"width": 1440, "height": 1050}, reduced_motion="reduce"
|
||||
)
|
||||
stack.callback(context.close)
|
||||
page, ref = context.new_page(), context.new_page()
|
||||
page.set_default_timeout(10000)
|
||||
page.on("pageerror", lambda e: report["page_errors"].append(str(e)))
|
||||
|
||||
def console(message):
|
||||
if message.type != "error":
|
||||
return
|
||||
expected = (
|
||||
any(str(code) in message.text for code in (401, 403, 409, 422, 500))
|
||||
or "net::ERR_FAILED" in message.text
|
||||
)
|
||||
report["expected_errors" if expected else "console_errors"].append(
|
||||
{"message": message.text, "url": message.location.get("url")}
|
||||
)
|
||||
|
||||
page.on("console", console)
|
||||
page.on(
|
||||
"dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss())
|
||||
)
|
||||
posts = []
|
||||
page.on(
|
||||
"request",
|
||||
lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None,
|
||||
)
|
||||
page.goto(admin + "/admin/login")
|
||||
page.locator("[name=login]").fill("admin")
|
||||
page.locator("[name=password]").fill(PASSWORD)
|
||||
page.get_by_role("button", name="Войти", exact=True).click()
|
||||
page.goto(admin + "/admin/content/services/bots")
|
||||
idle(page)
|
||||
ref.goto(design_origin + "/content-antirion.html")
|
||||
if not interactive:
|
||||
selectors = [
|
||||
".entry-workspace",
|
||||
".collection-pane .pane-title",
|
||||
".entry-pane .pane-title",
|
||||
".entry-tabs button",
|
||||
".field-label",
|
||||
".preview-pane .pane-title",
|
||||
".workspace-footer",
|
||||
]
|
||||
for skin in ("light", "dark"):
|
||||
page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin)
|
||||
# Approved dark Antirion tokens; the source has no Antirion dark palette.
|
||||
for width in (1440, 1280, 1024, 768, 390, 360):
|
||||
page.set_viewport_size({"width": width, "height": 1050})
|
||||
ref.set_viewport_size({"width": width, "height": 1050})
|
||||
actual, original = metrics(page, selectors), metrics(ref, selectors)
|
||||
assert not page.evaluate(
|
||||
"document.documentElement.scrollWidth>innerWidth+1"
|
||||
), (skin, width)
|
||||
for selector in selectors[1:]:
|
||||
assert actual[selector]["font"] == original[selector]["font"], (
|
||||
selector,
|
||||
width,
|
||||
)
|
||||
assert (
|
||||
actual[selector]["padding"] == original[selector]["padding"]
|
||||
), (selector, width)
|
||||
if width >= 1280:
|
||||
a, b = (
|
||||
actual[".entry-workspace"]["columns"].split(),
|
||||
original[".entry-workspace"]["columns"].split(),
|
||||
)
|
||||
for i in (0, 1, 3):
|
||||
assert a[i] == b[i], (width, a, b)
|
||||
if skin == "light":
|
||||
for selector in selectors[1:]:
|
||||
assert (
|
||||
actual[selector]["background"]
|
||||
== original[selector]["background"]
|
||||
), (selector, width)
|
||||
report["comparisons"].append(
|
||||
{
|
||||
"skin": skin,
|
||||
"width": width,
|
||||
"runtime": actual,
|
||||
"reference": original,
|
||||
}
|
||||
)
|
||||
page.screenshot(
|
||||
path=str(OUT / f"content-{skin}-{width}.png"), full_page=True
|
||||
)
|
||||
if skin == "light":
|
||||
ref.screenshot(
|
||||
path=str(OUT / f"reference-{width}.png"), full_page=True
|
||||
)
|
||||
page.evaluate("document.body.dataset.skin='light'")
|
||||
page.set_viewport_size({"width": 1440, "height": 1050})
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("original_geometry_fonts_padding_palette_and_responsive")
|
||||
|
||||
# Local filters/tabs send no requests, retain keyboard focus.
|
||||
before = len(posts)
|
||||
page.locator("#entry-query").fill("nothing-matches")
|
||||
expect(page.locator("[data-content-list-empty]")).to_be_visible()
|
||||
assert page.locator("#entry-query").evaluate("e=>e===document.activeElement")
|
||||
page.locator("#entry-query").fill("")
|
||||
page.locator("[data-content-filter=draft]").click()
|
||||
expect(page.locator("[data-entry=automation]")).to_be_visible()
|
||||
expect(page.locator("[data-entry=bots]")).to_be_hidden()
|
||||
page.locator("[data-content-filter=all]").click()
|
||||
for tab in ("relations", "usage", "schema", "fields"):
|
||||
page.locator("[data-content-tab=" + tab + "]").click()
|
||||
expect(page.locator("[data-content-panel=" + tab + "]")).to_be_visible()
|
||||
assert len(posts) == before
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("local_filter_tabs_and_real_metadata")
|
||||
|
||||
field = page.locator('[name="p.title"]')
|
||||
field.evaluate("e=>e.__qaInput=true")
|
||||
page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame=true")
|
||||
before = len(posts)
|
||||
field.fill("One background content update")
|
||||
idle(page)
|
||||
expect(page.frame_locator("#preview-result iframe").locator("strong")).to_have_text(
|
||||
"One background content update"
|
||||
)
|
||||
assert posts[before:] == [admin + "/admin/editor/content/services/bots/update"], (
|
||||
posts[before:]
|
||||
)
|
||||
assert field.evaluate("e=>e.__qaInput===true&&document.activeElement===e")
|
||||
assert page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame===true")
|
||||
assert (site / "content/services/bots.md").read_bytes() == original_file
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("one_post_keeps_field_frame_and_no_autosave")
|
||||
|
||||
gate["delay"] = 1
|
||||
field.fill("Delayed candidate")
|
||||
page.wait_for_function(
|
||||
"()=>document.getElementById('document-editor').dataset.updating==='true'"
|
||||
)
|
||||
field.fill("Latest candidate during pending POST")
|
||||
page.locator("[data-content-tab=relations]").click()
|
||||
expect(page.locator("[data-content-panel=relations]")).to_be_visible()
|
||||
idle(page)
|
||||
page.locator("[data-content-tab=fields]").click()
|
||||
expect(field).to_have_value("Latest candidate during pending POST")
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("typing_and_tabs_do_not_wait_for_delayed_post")
|
||||
|
||||
# Asset/ref dialogs have real options and restore focus with Escape.
|
||||
picker = page.locator('[data-content-picker="p.hero_asset"]')
|
||||
picker.click()
|
||||
expect(page.locator("dialog[open] .asset-option").first).to_be_visible()
|
||||
page.keyboard.press("Escape")
|
||||
assert picker.evaluate("e=>e===document.activeElement")
|
||||
page.locator('[data-content-picker="p.related_scenarios"]').click()
|
||||
expect(page.locator("dialog[open] .ref-choice")).to_have_count(3)
|
||||
page.locator("dialog[open] input[type=checkbox]").first.uncheck()
|
||||
page.locator("dialog[open]").get_by_role(
|
||||
"button", name="Применить", exact=True
|
||||
).click()
|
||||
idle(page)
|
||||
page.locator('[data-content-bool="p.featured"]').uncheck()
|
||||
idle(page)
|
||||
assert page.evaluate("window.siteDocument.state.model.meta.featured") is False
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("real_asset_ref_picker_and_boolean")
|
||||
|
||||
# Explicit add and remove list rows preserve names and field focus.
|
||||
page.locator('[data-content-add="p.benefits"]').click()
|
||||
row = page.locator('[data-list-row="p.benefits.2"] textarea')
|
||||
row.fill("New list item")
|
||||
idle(page)
|
||||
expect(page.locator('[data-list-row="p.benefits.3"]')).to_be_hidden()
|
||||
page.locator('[data-content-remove="p.benefits.0"]').click()
|
||||
idle(page)
|
||||
assert page.evaluate("window.siteDocument.state.model.meta.benefits.length") == 2
|
||||
expect(page.locator('[name="p.benefits.1"]')).to_have_value("New list item")
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("explicit_list_add_delete_reindexes_controls")
|
||||
|
||||
page.locator("[data-content-preview=page]").click()
|
||||
idle(page)
|
||||
expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text(
|
||||
"Latest candidate during pending POST"
|
||||
)
|
||||
page.locator("[data-content-version=live]").click()
|
||||
idle(page)
|
||||
expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text(
|
||||
"Telegram-боты"
|
||||
)
|
||||
page.locator("[data-content-preview=card]").click()
|
||||
idle(page)
|
||||
expect(page.locator("#preview-result .preview-empty")).to_contain_text("карточка")
|
||||
page.locator("[data-content-version=workspace]").click()
|
||||
idle(page)
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("real_workspace_card_page_and_immutable_live_page")
|
||||
|
||||
page.locator("[data-content-validate]").first.click()
|
||||
expect(page.locator("dialog[open] .review-summary")).to_be_visible()
|
||||
page.screenshot(path=str(OUT / f"review-{interactive}.png"))
|
||||
page.keyboard.press("Escape")
|
||||
page.locator("[data-editor-mode=expert]").click()
|
||||
expect(page.locator("#expert-pane")).to_be_visible()
|
||||
page.locator("[data-content-diff]").click()
|
||||
expect(page.locator("dialog[open] .diff-row.changed").first).to_be_visible()
|
||||
page.keyboard.press("Escape")
|
||||
source = page.locator("#document-source").input_value()
|
||||
page.locator("#document-source").fill("---\ntitle: [\n---\nKeep this source")
|
||||
page.wait_for_timeout(450)
|
||||
page.wait_for_function("()=>!window.siteDocument.state.busy")
|
||||
expect(page.locator("#document-source")).to_have_value(
|
||||
"---\ntitle: [\n---\nKeep this source"
|
||||
)
|
||||
expect(page.locator("[data-content-source-errors]")).not_to_be_empty()
|
||||
page.locator("#document-source").fill(source)
|
||||
idle(page)
|
||||
page.locator("[data-content-find]").click()
|
||||
page.locator("[data-source-query]").fill("Latest candidate")
|
||||
page.locator("dialog[open]").get_by_role("button", name="Найти", exact=True).click()
|
||||
assert page.locator("#document-source").evaluate(
|
||||
"e=>e.selectionEnd>e.selectionStart"
|
||||
)
|
||||
page.locator("[data-editor-mode=constructor]").click()
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("review_expert_diff_find_invalid_yaml_recovery")
|
||||
|
||||
# Navigation confirmation uses the original dialog, Escape retains edits.
|
||||
page.locator("[data-entry=ai]").click()
|
||||
expect(page.locator("dialog[open]")).to_contain_text("несохранённые")
|
||||
page.keyboard.press("Escape")
|
||||
assert page.url.endswith("/services/bots")
|
||||
page.locator("[data-save-document]").click()
|
||||
page.wait_for_function(
|
||||
"()=>!window.siteDocument.state.dirty&&!window.siteDocument.state.busy"
|
||||
)
|
||||
assert b"Latest candidate" in (site / "content/services/bots.md").read_bytes()
|
||||
assert (work / "dist/current").exists()
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("leave_confirmation_explicit_save_no_publish")
|
||||
|
||||
# Real CAS conflict; local unsaved text survives.
|
||||
field.fill("My conflict candidate")
|
||||
idle(page)
|
||||
server_source = (
|
||||
(site / "content/services/bots.md")
|
||||
.read_text()
|
||||
.replace("Latest candidate during pending POST", "Server concurrent title")
|
||||
)
|
||||
(site / "content/services/bots.md").write_text(server_source)
|
||||
page.locator("[data-save-document]").click()
|
||||
expect(page.locator("dialog[open] .conflict-grid")).to_be_visible()
|
||||
expect(field).to_have_value("My conflict candidate")
|
||||
page.screenshot(path=str(OUT / f"conflict-{interactive}.png"))
|
||||
page.keyboard.press("Escape")
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("real_409_preserves_unsaved_source")
|
||||
|
||||
# Reload is intentional and has no system dialog.
|
||||
page.reload()
|
||||
idle(page)
|
||||
field = page.locator('[name="p.title"]')
|
||||
field.fill("Copied current editor")
|
||||
idle(page)
|
||||
page.locator("[data-content-duplicate]").click()
|
||||
page.wait_for_url("**/bots-copy")
|
||||
idle(page)
|
||||
expect(page.locator('[name="p.title"]')).to_have_value(
|
||||
"Copied current editor (копия)"
|
||||
)
|
||||
assert "status: draft" in (site / "content/services/bots-copy.md").read_text()
|
||||
page.locator("[data-content-delete]").click()
|
||||
expect(page.locator("dialog[open]")).to_contain_text("Удалить запись?")
|
||||
page.keyboard.press("Escape")
|
||||
assert (site / "content/services/bots-copy.md").exists()
|
||||
page.locator("[data-content-delete]").click()
|
||||
page.locator("dialog[open]").get_by_role(
|
||||
"button", name="Удалить из workspace", exact=True
|
||||
).click()
|
||||
page.wait_for_url("**/services/ai")
|
||||
assert not (site / "content/services/bots-copy.md").exists()
|
||||
idle(page)
|
||||
page.locator("[data-content-delete]").click()
|
||||
expect(page.locator("#request-error")).to_contain_text("архивируйте")
|
||||
page.locator("[data-close-request-error]").click()
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append(
|
||||
"duplicate_current_candidate_delete_confirmation_and_published_guard"
|
||||
)
|
||||
|
||||
# Empty/off collections and a real new draft in an enabled collection.
|
||||
page.goto(admin + "/admin/content/posts")
|
||||
expect(page.locator("[data-content-list-empty]")).to_contain_text(
|
||||
"Записей пока нет"
|
||||
)
|
||||
expect(
|
||||
page.get_by_role("button", name="Создать запись", exact=True)
|
||||
).to_be_disabled()
|
||||
page.goto(admin + "/admin/content/services")
|
||||
idle(page)
|
||||
page.get_by_role("button", name="Создать запись", exact=True).click()
|
||||
page.wait_for_url("**/services/entry-*")
|
||||
idle(page)
|
||||
assert page.locator("#entry-slug").input_value().startswith("entry-")
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("empty_disabled_collection_and_create_real_draft")
|
||||
|
||||
# HTTP and network errors keep the active fields and show a message.
|
||||
field = page.locator('[name="p.title"]')
|
||||
page.route(
|
||||
"**/admin/editor/**/update",
|
||||
lambda route: route.fulfill(
|
||||
status=500,
|
||||
content_type="application/json",
|
||||
body=json.dumps(
|
||||
{
|
||||
"error": {
|
||||
"code": "qa_failure",
|
||||
"message": "Проверка HTTP 500",
|
||||
"request_id": "content-qa",
|
||||
}
|
||||
}
|
||||
),
|
||||
),
|
||||
)
|
||||
field.fill("Keep text after error")
|
||||
expect(page.locator("#request-error")).to_contain_text("Проверка HTTP 500")
|
||||
expect(field).to_have_value("Keep text after error")
|
||||
page.unroute("**/admin/editor/**/update")
|
||||
field.fill("Recovery after 500")
|
||||
idle(page)
|
||||
page.route("**/admin/editor/**/update", lambda route: route.abort())
|
||||
field.fill("Keep text offline")
|
||||
expect(page.locator("#request-error")).to_contain_text("Нет связи")
|
||||
expect(field).to_have_value("Keep text offline")
|
||||
page.unroute("**/admin/editor/**/update")
|
||||
field.fill("Recovered connection")
|
||||
idle(page)
|
||||
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
|
||||
run["checks"].append("500_and_network_errors_visible_and_recoverable")
|
||||
ref.close()
|
||||
assert not report["page_errors"], report["page_errors"]
|
||||
assert not report["native_dialogs"], report["native_dialogs"]
|
||||
assert not report["console_errors"], report["console_errors"]
|
||||
browser.close()
|
||||
(OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"comparisons": len(report["comparisons"]),
|
||||
"runs": report["runs"],
|
||||
"errors": report["page_errors"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -317,6 +317,8 @@ def main():
|
||||
|
||||
page.goto(admin + '/admin/content/services/bots')
|
||||
idle(page)
|
||||
page.locator('[data-content-preview=page]').click()
|
||||
idle(page)
|
||||
entry = page.locator('[data-inspector] [name="p.title"]')
|
||||
entry.fill('Entry background update')
|
||||
idle(page)
|
||||
|
||||
+15
-11
@@ -36,7 +36,7 @@ def main():
|
||||
work = Path(temp)
|
||||
site, dist = work / "site", work / "dist"
|
||||
shutil.copytree(
|
||||
ROOT / "examples/ai-studio", site, ignore=shutil.ignore_patterns(".engine")
|
||||
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
|
||||
)
|
||||
build_site(site, dist)
|
||||
live = (dist / "current").resolve()
|
||||
@@ -61,6 +61,7 @@ def main():
|
||||
options = {"headless": True}
|
||||
if kind.name == "chromium":
|
||||
options["args"] = ["--no-sandbox", "--no-proxy-server"]
|
||||
options["channel"] = "chromium"
|
||||
if kind.name == "firefox":
|
||||
options["firefox_user_prefs"] = {"network.proxy.type": 0}
|
||||
if os.environ.get("QA_BROWSER_EXECUTABLE"):
|
||||
@@ -84,16 +85,13 @@ def main():
|
||||
page.wait_for_url(origin + "/admin/")
|
||||
page.goto(origin + "/admin/publish")
|
||||
with patch(
|
||||
"site_engine.web.api.routes.publish",
|
||||
"site_engine.services.publication.build_site",
|
||||
side_effect=PermissionError("QA publish denied"),
|
||||
):
|
||||
page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
|
||||
with page.expect_response(
|
||||
lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
|
||||
lambda r: r.url.endswith("/admin/publication/build") and r.request.method == "POST"
|
||||
) as failed:
|
||||
page.locator("#confirm-dialog").get_by_role(
|
||||
"button", name="Продолжить"
|
||||
).click()
|
||||
page.locator('[data-pub-action=candidate]').first.click()
|
||||
response = failed.value
|
||||
assert response.status == 500
|
||||
correlation = response.headers["x-request-id"]
|
||||
@@ -146,16 +144,22 @@ def main():
|
||||
page.unroute("**/admin/editor/pages/index/save")
|
||||
checks.append("network_failure_is_visible_and_preserves_unsaved_source")
|
||||
page.get_by_role("button", name="Сохранить документ", exact=True).click()
|
||||
expect(page.locator("#editor-result")).to_have_attribute("data-saved", "1")
|
||||
page.wait_for_function(
|
||||
"expected => window.siteDocument?.state?.saved === expected && !window.siteDocument.state.dirty",
|
||||
arg=edited,
|
||||
)
|
||||
assert (site / "pages/index.md").read_text() == edited
|
||||
assert (dist / "current").resolve() == live
|
||||
checks.append("save_recovers_after_failure_without_publishing")
|
||||
page.goto(origin + "/admin/publish")
|
||||
page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
|
||||
page.locator('[data-pub-action=candidate]').first.click()
|
||||
page.locator('[data-publication-root][aria-busy=false]').wait_for()
|
||||
page.locator('[data-pub-action=publish]').click()
|
||||
page.locator('#release-comment').fill('Error recovery QA release')
|
||||
with page.expect_response(
|
||||
lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
|
||||
lambda r: r.url.endswith("/admin/publication/activate") and r.request.method == "POST"
|
||||
) as published:
|
||||
page.locator("#confirm-dialog").get_by_role("button", name="Продолжить").click()
|
||||
page.locator('[data-pub-action=confirm-publish]').click()
|
||||
assert published.value.status == 200
|
||||
assert (dist / "current").resolve() != live
|
||||
expect(page.locator("#request-error")).to_be_hidden()
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Real publication workflow and original design in Chromium; isolated temporary sites."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from contextlib import ExitStack
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
from qa_001 import PASSWORD, ROOT, serve
|
||||
from qa_editor_updates import reserve
|
||||
from starlette.applications import Starlette
|
||||
from starlette.routing import Mount
|
||||
from starlette.staticfiles import StaticFiles
|
||||
|
||||
from site_engine.build.pipeline import hash_tree
|
||||
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
|
||||
|
||||
OUT = Path(os.environ.get("QA_PUBLICATION_OUT", "/tmp/site-engine-publication-001"))
|
||||
|
||||
|
||||
def metrics(page, selectors):
|
||||
return page.evaluate(
|
||||
"""selectors=>Object.fromEntries(selectors.map(s=>{
|
||||
const e=document.querySelector(s),r=e.getBoundingClientRect(),c=getComputedStyle(e);
|
||||
return [s,{width:r.width,font:c.fontSize,padding:c.padding,background:c.backgroundColor,columns:c.gridTemplateColumns}];
|
||||
}))""",
|
||||
selectors,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
report = {
|
||||
"comparisons": [],
|
||||
"runs": [],
|
||||
"page_errors": [],
|
||||
"console_errors": [],
|
||||
"expected_errors": [],
|
||||
"native_dialogs": [],
|
||||
}
|
||||
with sync_playwright() as pw:
|
||||
browser = pw.chromium.launch(
|
||||
channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
|
||||
)
|
||||
for interactive in (False, True):
|
||||
with tempfile.TemporaryDirectory(prefix="publication-qa-") as tmp, ExitStack() as stack:
|
||||
work = Path(tmp)
|
||||
site = work / "site"
|
||||
dist = work / "dist"
|
||||
shutil.copytree(
|
||||
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
|
||||
)
|
||||
admin_socket, preview_socket = reserve(), reserve()
|
||||
admin = f"http://127.0.0.1:{admin_socket.getsockname()[1]}"
|
||||
preview = f"http://127.0.0.1:{preview_socket.getsockname()[1]}"
|
||||
stack.enter_context(
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"SITE_ROOT": str(site),
|
||||
"SITE_DIST": str(dist),
|
||||
"SITE_STATE_DIR": str(work / "state"),
|
||||
"SITE_ADMIN_LOGIN": "admin",
|
||||
"SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
|
||||
"SITE_SECRET_KEY": "publication-browser-secret-" * 3,
|
||||
"SITE_COOKIE_SECURE": "0",
|
||||
"SITE_ADMIN_ORIGIN": admin if interactive else "",
|
||||
"SITE_PREVIEW_ORIGIN": preview if interactive else "",
|
||||
},
|
||||
)
|
||||
)
|
||||
app = create_app()
|
||||
gate = {"delay": 0}
|
||||
|
||||
@app.middleware("http")
|
||||
async def delay(request, call_next, gate=gate):
|
||||
if request.url.path == "/admin/publication/build" and gate["delay"]:
|
||||
value, gate["delay"] = gate["delay"], 0
|
||||
await asyncio.sleep(value)
|
||||
return await call_next(request)
|
||||
|
||||
stack.enter_context(serve(app, admin_socket))
|
||||
if interactive:
|
||||
stack.enter_context(serve(create_preview_app(), preview_socket))
|
||||
else:
|
||||
preview_socket.close()
|
||||
reference = stack.enter_context(
|
||||
serve(
|
||||
Starlette(
|
||||
routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))]
|
||||
)
|
||||
)
|
||||
)
|
||||
context = browser.new_context(
|
||||
viewport={"width": 1440, "height": 1050}, reduced_motion="reduce"
|
||||
)
|
||||
stack.callback(context.close)
|
||||
page, ref = context.new_page(), context.new_page()
|
||||
page.set_default_timeout(12000)
|
||||
page.on("pageerror", lambda e: report["page_errors"].append(str(e)))
|
||||
|
||||
def console(message):
|
||||
if message.type != "error":
|
||||
return
|
||||
expected = (
|
||||
any(str(code) in message.text for code in (401, 403, 409, 422, 500))
|
||||
or "net::ERR_FAILED" in message.text
|
||||
)
|
||||
report["expected_errors" if expected else "console_errors"].append(
|
||||
{"message": message.text, "url": message.location.get("url")}
|
||||
)
|
||||
|
||||
page.on("console", console)
|
||||
page.on(
|
||||
"dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss())
|
||||
)
|
||||
posts = []
|
||||
page.on(
|
||||
"request",
|
||||
lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None,
|
||||
)
|
||||
checks = []
|
||||
report["runs"].append({"interactive": interactive, "checks": checks})
|
||||
|
||||
def done(name, checks=checks, interactive=interactive):
|
||||
checks.append(name)
|
||||
print("PASS", interactive, len(checks), name, flush=True)
|
||||
|
||||
def ready(page=page):
|
||||
expect(page.locator("[data-publication-root]")).to_have_attribute(
|
||||
"aria-busy", "false"
|
||||
)
|
||||
|
||||
def tab(name, page=page):
|
||||
page.locator(f'[data-pub-tab="{name}"]').click()
|
||||
|
||||
def action(name, page=page):
|
||||
page.locator(f'[data-pub-action="{name}"]').first.click()
|
||||
|
||||
def build(page=page, action=action, ready=ready):
|
||||
action("candidate")
|
||||
ready()
|
||||
expect(page.locator("[data-pub-action=publish]")).to_be_visible()
|
||||
|
||||
def publish(comment, page=page, action=action, ready=ready):
|
||||
action("publish")
|
||||
page.locator("#release-comment").fill(comment)
|
||||
action("confirm-publish")
|
||||
ready()
|
||||
expect(page.locator("dialog[open]")).to_have_count(0)
|
||||
|
||||
page.goto(admin + "/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(admin + "/admin/")
|
||||
with page.expect_response(lambda r, admin=admin: r.url == admin + "/admin/publish") as opened:
|
||||
page.locator('#sidebar a[href="/admin/publish"]').click()
|
||||
assert opened.value.request.headers.get("hx-boosted") == "true"
|
||||
ready()
|
||||
expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет")
|
||||
assert not (dist / "current").exists()
|
||||
done("real_empty_first_release")
|
||||
ref.goto(reference + "/publication-antirion.html")
|
||||
if not interactive:
|
||||
selectors = [
|
||||
".heading h1",
|
||||
".livebar",
|
||||
".pipe",
|
||||
".panel-header",
|
||||
".table th",
|
||||
".table td",
|
||||
".button.primary",
|
||||
".tabs",
|
||||
]
|
||||
for skin in ("light", "dark"):
|
||||
page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin)
|
||||
for width in (1440, 1280, 1024, 768, 390, 360):
|
||||
page.set_viewport_size({"width": width, "height": 1050})
|
||||
ref.set_viewport_size({"width": width, "height": 1050})
|
||||
a, b = metrics(page, selectors), metrics(ref, selectors)
|
||||
assert not page.evaluate(
|
||||
"document.documentElement.scrollWidth>innerWidth+1"
|
||||
), (skin, width)
|
||||
for s in selectors:
|
||||
assert a[s]["font"] == b[s]["font"], (s, width, a[s], b[s])
|
||||
assert a[s]["padding"] == b[s]["padding"], (s, width, a[s], b[s])
|
||||
if skin == "light":
|
||||
assert a[s]["background"] == b[s]["background"], (
|
||||
s,
|
||||
width,
|
||||
a[s],
|
||||
b[s],
|
||||
)
|
||||
report["comparisons"].append(
|
||||
{"skin": skin, "width": width, "runtime": a, "reference": b}
|
||||
)
|
||||
page.screenshot(
|
||||
path=str(OUT / f"publication-{skin}-{width}.png"), full_page=True
|
||||
)
|
||||
if skin == "light":
|
||||
ref.screenshot(
|
||||
path=str(OUT / f"reference-{width}.png"), full_page=True
|
||||
)
|
||||
page.set_viewport_size({"width": 1440, "height": 1050})
|
||||
page.evaluate("document.body.dataset.skin='light'")
|
||||
done("original_geometry_fonts_padding_palette_responsive_12_sets")
|
||||
before = len(posts)
|
||||
page.locator("#pub-search").fill("no-such-document")
|
||||
expect(page.locator(".table tbody")).to_contain_text("Ничего не найдено")
|
||||
expect(page.locator("#pub-search")).to_be_focused()
|
||||
page.locator("#pub-search").fill("pages/index.md")
|
||||
page.locator('[data-pub-select="pages/index.md"]').click()
|
||||
expect(page.locator(".split>.stack").last).to_contain_text("pages/index.md")
|
||||
tab("checks")
|
||||
tab("history")
|
||||
tab("changes")
|
||||
assert len(posts) == before
|
||||
done("local_filters_selection_tabs_no_post")
|
||||
action("compare-doc")
|
||||
expect(page.locator("dialog[open]")).to_contain_text("Workspace")
|
||||
page.keyboard.press("Escape")
|
||||
expect(page.locator("dialog[open]")).to_have_count(0)
|
||||
action("doc-history")
|
||||
expect(page.locator("dialog[open]")).to_contain_text("предыдущих версий пока нет")
|
||||
action("close-modal")
|
||||
done("real_compare_and_empty_document_history_designer_dialog")
|
||||
action("validate")
|
||||
ready()
|
||||
expect(page.locator(".summary")).to_contain_text("Проверено")
|
||||
assert not (dist / "current").exists()
|
||||
done("real_validate_does_not_publish")
|
||||
gate["delay"] = 1.5
|
||||
action("candidate")
|
||||
tab("activity")
|
||||
expect(page.locator("[data-pub-tab=activity]")).to_have_attribute(
|
||||
"aria-selected", "true"
|
||||
)
|
||||
ready()
|
||||
tab("candidate")
|
||||
expect(page.locator("[data-pub-action=publish]")).to_be_enabled()
|
||||
candidate = json.loads((work / "state/publication/candidate.json").read_text())
|
||||
assert not (dist / "current").exists()
|
||||
original_output = hash_tree(dist / candidate["id"])
|
||||
done("background_candidate_does_not_freeze_tabs_or_activate")
|
||||
action("candidate-diff")
|
||||
expect(page.locator("dialog[open]")).to_contain_text("pages/index.md")
|
||||
action("close-modal")
|
||||
action("preview")
|
||||
ready()
|
||||
frame = page.frame_locator(".release-preview")
|
||||
expect(frame.locator("body")).to_contain_text("Автоматизируем")
|
||||
assert not page.frames[-1].locator("script").count()
|
||||
page.screenshot(
|
||||
path=str(OUT / f"candidate-preview-{interactive}.png"), full_page=True
|
||||
)
|
||||
action("close-modal")
|
||||
done("immutable_candidate_diff_and_real_passive_preview")
|
||||
action("publish")
|
||||
page.locator("#release-comment").fill("Не публиковать")
|
||||
action("close-modal")
|
||||
assert not (dist / "current").exists()
|
||||
publish("Первый проверенный релиз")
|
||||
first = (dist / "current").resolve().name
|
||||
assert first == candidate["id"] and hash_tree(dist / first) == original_output
|
||||
expect(page.locator(".livebar")).to_contain_text(first)
|
||||
done("cancel_and_explicit_publish_exact_candidate")
|
||||
path = site / "pages/index.md"
|
||||
source = path.read_text()
|
||||
path.write_text(source + "\nИзменение для второго релиза.\n")
|
||||
tab("changes")
|
||||
action("refresh-workspace")
|
||||
ready()
|
||||
build()
|
||||
candidate = json.loads((work / "state/publication/candidate.json").read_text())
|
||||
action("publish")
|
||||
page.locator("#release-comment").fill("Устаревший кандидат")
|
||||
path.write_text(path.read_text() + "\nНовая правка после просмотра.\n")
|
||||
action("confirm-publish")
|
||||
ready()
|
||||
expect(page.locator("#request-error")).to_contain_text("Кандидат устарел")
|
||||
assert (dist / "current").resolve().name == first
|
||||
action("close-modal")
|
||||
page.locator("[data-close-request-error]").click()
|
||||
tab("candidate")
|
||||
expect(page.locator("[data-pub-action=publish]")).to_be_disabled()
|
||||
done("real_stale_candidate_409_visible_and_live_unchanged")
|
||||
build()
|
||||
publish("Второй релиз")
|
||||
second = (dist / "current").resolve().name
|
||||
assert second != first
|
||||
source_hash = hash_tree(site)
|
||||
page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click()
|
||||
page.screenshot(path=str(OUT / f"rollback-{interactive}.png"), full_page=True)
|
||||
action("close-modal")
|
||||
assert (dist / "current").resolve().name == second
|
||||
page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click()
|
||||
action("rollback-confirm")
|
||||
ready()
|
||||
assert (dist / "current").resolve().name == first and hash_tree(site) == source_hash
|
||||
done("rollback_cancel_confirm_preserves_workspace")
|
||||
page.goto(admin + "/admin/publish")
|
||||
ready()
|
||||
expect(page.locator(".livebar")).to_contain_text(first)
|
||||
tab("activity")
|
||||
expect(page.locator(".timeline")).to_contain_text("release_rollback")
|
||||
tab("history")
|
||||
page.locator(f'[data-pub-action=release-details][data-release="{second}"]').click()
|
||||
expect(page.locator("dialog[open]")).to_contain_text("Второй релиз")
|
||||
action("close-modal")
|
||||
done("reload_real_history_comments_and_audit")
|
||||
with patch(
|
||||
"site_engine.core.render.Renderer.render",
|
||||
side_effect=RuntimeError("QA render failure"),
|
||||
):
|
||||
action("candidate")
|
||||
ready()
|
||||
expect(page.locator("#request-error")).to_contain_text("Внутренняя ошибка сервера")
|
||||
expect(page.locator("#publication-panel")).to_contain_text("Ошибка сборки")
|
||||
action("build-log")
|
||||
expect(page.locator("dialog[open]")).to_contain_text("ID запроса")
|
||||
action("close-modal")
|
||||
assert (dist / "current").resolve().name == first
|
||||
page.locator("[data-close-request-error]").click()
|
||||
page.route("**/admin/publication/build", lambda route: route.abort())
|
||||
action("candidate")
|
||||
ready()
|
||||
expect(page.locator("#request-error")).to_contain_text("Нет связи с сервером")
|
||||
page.unroute("**/admin/publication/build")
|
||||
page.locator("[data-close-request-error]").click()
|
||||
build()
|
||||
done("500_network_visible_logged_and_recoverable")
|
||||
page.goto(admin + "/admin/pages/index")
|
||||
expect(page.locator(".builder")).to_be_visible()
|
||||
page.goto(admin + "/admin/content/services/bots")
|
||||
expect(page.locator(".entry-workspace")).to_be_visible()
|
||||
page.goto(admin + "/admin/theme")
|
||||
expect(page.locator(".theme-content")).to_be_visible()
|
||||
page.goto(admin + "/admin/publish")
|
||||
ready()
|
||||
tab("checks")
|
||||
page.locator("[data-pub-tab=checks]").focus()
|
||||
page.keyboard.press("ArrowRight")
|
||||
expect(page.locator("[data-pub-tab=candidate]")).to_be_focused()
|
||||
page.locator("[data-action=profile]").click()
|
||||
page.locator("#profile-dialog button[type=submit]").click()
|
||||
expect(page.locator("input[name=login]")).to_be_visible()
|
||||
done("accepted_screens_keyboard_and_logout")
|
||||
browser.close()
|
||||
(OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
assert not report["page_errors"], report["page_errors"]
|
||||
assert not report["console_errors"], report["console_errors"]
|
||||
assert not report["native_dialogs"], report["native_dialogs"]
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"comparisons": len(report["comparisons"]),
|
||||
"runs": report["runs"],
|
||||
"errors": report["page_errors"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Publication boot through real htmx links, history and repeated navigation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
from qa_001 import PASSWORD, ROOT, serve
|
||||
|
||||
from site_engine.services.auth import hash_password
|
||||
from site_engine.web.app import create_app
|
||||
|
||||
|
||||
def main():
|
||||
out = Path(
|
||||
os.environ.get("QA_PUBLICATION_NAV_OUT", "/tmp/site-engine-publication-navigation-001")
|
||||
)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
report = {"checks": [], "page_errors": [], "console_errors": [], "native_dialogs": []}
|
||||
with tempfile.TemporaryDirectory(prefix="publication-navigation-") as tmp:
|
||||
work = Path(tmp)
|
||||
shutil.copytree(
|
||||
ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine")
|
||||
)
|
||||
env = {
|
||||
"SITE_ROOT": str(work / "site"),
|
||||
"SITE_DIST": str(work / "dist"),
|
||||
"SITE_STATE_DIR": str(work / "state"),
|
||||
"SITE_ADMIN_LOGIN": "admin",
|
||||
"SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
|
||||
"SITE_SECRET_KEY": "publication-navigation-test-" * 3,
|
||||
"SITE_COOKIE_SECURE": "0",
|
||||
"SITE_ADMIN_ORIGIN": "",
|
||||
"SITE_PREVIEW_ORIGIN": "",
|
||||
}
|
||||
with patch.dict(os.environ, env), serve(create_app()) as 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": 960})
|
||||
page = context.new_page()
|
||||
page.set_default_timeout(6000)
|
||||
page.on(
|
||||
"pageerror",
|
||||
lambda exc: report["page_errors"].append({"message": str(exc), "stack": exc.stack}),
|
||||
)
|
||||
page.on(
|
||||
"console",
|
||||
lambda msg: (
|
||||
report["console_errors"].append(msg.text) if msg.type == "error" else None
|
||||
),
|
||||
)
|
||||
page.on(
|
||||
"dialog",
|
||||
lambda dialog: (report["native_dialogs"].append(dialog.message), dialog.dismiss()),
|
||||
)
|
||||
|
||||
def ready():
|
||||
expect(page.locator("[data-publication-root]")).to_have_attribute(
|
||||
"aria-busy", "false"
|
||||
)
|
||||
expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет")
|
||||
assert page.evaluate(
|
||||
"htmx.config.allowScriptTags === false && htmx.config.allowEval === false"
|
||||
)
|
||||
|
||||
def nav(path):
|
||||
if page.viewport_size["width"] < 760:
|
||||
page.get_by_role("button", name="Открыть меню", exact=True).click()
|
||||
with page.expect_response(
|
||||
lambda r: r.request.method == "GET" and r.url == origin + path
|
||||
) as response:
|
||||
page.locator(f'#sidebar a[href="{path}"]').click()
|
||||
assert response.value.request.headers.get("hx-boosted") == "true"
|
||||
page.wait_for_url(origin + path)
|
||||
assert page.evaluate("window.__publicationNavigationDocument") == "preserved"
|
||||
|
||||
try:
|
||||
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/")
|
||||
for width in (1440, 390):
|
||||
page.set_viewport_size({"width": width, "height": 960})
|
||||
for source in (
|
||||
"/admin/pages",
|
||||
"/admin/content/services/bots",
|
||||
"/admin/pages/index",
|
||||
):
|
||||
page.goto(origin + source)
|
||||
page.evaluate("window.__publicationNavigationDocument='preserved'")
|
||||
nav("/admin/publish")
|
||||
ready()
|
||||
report["checks"].append(f"htmx_from_{source}_{width}")
|
||||
nav("/admin/pages")
|
||||
nav("/admin/publish")
|
||||
ready()
|
||||
page.go_back()
|
||||
page.wait_for_url(origin + "/admin/pages")
|
||||
page.go_forward()
|
||||
page.wait_for_url(origin + "/admin/publish")
|
||||
ready()
|
||||
assert (
|
||||
page.evaluate("window.__publicationNavigationDocument") == "preserved"
|
||||
)
|
||||
report["checks"].append(f"repeat_and_back_forward_{source}_{width}")
|
||||
page.reload()
|
||||
ready()
|
||||
report["checks"].append(f"direct_reload_{width}")
|
||||
page.screenshot(path=str(out / f"publication-navigation-{width}.png"))
|
||||
assert not report["page_errors"], report["page_errors"]
|
||||
assert not report["console_errors"], report["console_errors"]
|
||||
assert not report["native_dialogs"], report["native_dialogs"]
|
||||
assert not (work / "dist/current").exists()
|
||||
finally:
|
||||
report["last_url"] = page.url
|
||||
report["boot_nodes"] = page.locator("[data-publication-boot]").count()
|
||||
(out / "report.json").write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(json.dumps(report, ensure_ascii=False), flush=True)
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -37,7 +37,7 @@ def main():
|
||||
report = {"geometry": [], "flows": [], "errors": []}
|
||||
with tempfile.TemporaryDirectory(prefix="cms-shell-") as temp:
|
||||
work = Path(temp)
|
||||
shutil.copytree(ROOT / "examples/studio-site", work / "site", ignore=shutil.ignore_patterns(".engine"))
|
||||
shutil.copytree(ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine"))
|
||||
env = {
|
||||
"SITE_ROOT": str(work / "site"), "SITE_DIST": str(work / "dist"),
|
||||
"SITE_STATE_DIR": str(work / "state"), "SITE_ADMIN_LOGIN": "admin",
|
||||
@@ -46,7 +46,7 @@ def main():
|
||||
"SITE_ADMIN_ORIGIN": "", "SITE_PREVIEW_ORIGIN": "", "SITE_PUBLIC_HOST": "",
|
||||
}
|
||||
with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
|
||||
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 960}, reduced_motion="reduce")
|
||||
page.on("pageerror", lambda error: report["errors"].append(str(error)))
|
||||
page.on("console", lambda message: report["errors"].append(message.text) if message.type == "error" else None)
|
||||
@@ -121,7 +121,7 @@ def main():
|
||||
assert page.locator("[data-command-empty]").is_visible()
|
||||
page.locator("#cmd-input").fill("Контент")
|
||||
page.locator("[data-command-result]:visible").click()
|
||||
page.wait_for_url(origin + "/admin/content")
|
||||
page.wait_for_url(origin + "/admin/content/**")
|
||||
assert page.locator(".nav-item.active").inner_text() == "Контент"
|
||||
report["flows"].append("Ctrl+K, real pages/sections, empty search, htmx navigation")
|
||||
page.locator('[data-action="profile"]').click()
|
||||
@@ -146,8 +146,11 @@ def main():
|
||||
assert page.locator(".sidebar.open").count() == 0
|
||||
page.set_viewport_size({"width": 1440, "height": 960})
|
||||
page.goto(origin + "/admin/publish")
|
||||
page.get_by_role("button", name="Опубликовать текущий черновик сайта", exact=True).click()
|
||||
page.locator("#confirm-dialog button[value=confirm]").click()
|
||||
page.locator('[data-pub-action=candidate]').first.click()
|
||||
page.locator('[data-publication-root][aria-busy=false]').wait_for()
|
||||
page.locator('[data-pub-action=publish]').click()
|
||||
page.locator('#release-comment').fill('Shell QA release')
|
||||
page.locator('[data-pub-action=confirm-publish]').click()
|
||||
page.locator(".live-pip:not(.no-release) .mono").wait_for()
|
||||
page.goto(origin + "/admin/pages")
|
||||
assert page.locator(".live-pip .mono").inner_text().strip()
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Transfer original Content CSS and SVGs; only isolate selectors from the shell."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from css_scope import scope_css
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
def emit(path, content):
|
||||
if "--check" in sys.argv:
|
||||
if not path.exists() or path.read_text() != content:
|
||||
raise SystemExit(f"Content design out of date: {path}")
|
||||
else:
|
||||
path.write_text(content)
|
||||
|
||||
target = ROOT / "src/site_engine/web/admin"
|
||||
css = (
|
||||
(ROOT / "design/assets/builder.css").read_text()
|
||||
+ "\n"
|
||||
+ (ROOT / "design/assets/content-editor.css").read_text()
|
||||
)
|
||||
css = re.sub(r"(?<![-\w])(?:html|body)(?![-\w])", ":scope", css).replace(":root", ":scope")
|
||||
css = css.replace(':scope[data-theme="antirion"]', ":scope").replace(
|
||||
':scope[data-theme="rose"]', ":scope[data-unused-rose]"
|
||||
)
|
||||
emit(
|
||||
target / "static/content-editor.css",
|
||||
"/* Generated by scripts/sync_content_design.py; original declarations unchanged. */\n"
|
||||
+ scope_css(css, ".entry-content-editor", ":where(.entry-content-editor)"),
|
||||
)
|
||||
js = (ROOT / "design/assets/content-editor.js").read_text()
|
||||
data = js.split("function icon(name){const p={", 1)[1].split("}[name]||", 1)[0]
|
||||
icons = dict(re.findall(r"(\w+):'([^']*)'", data))
|
||||
emit(
|
||||
target / "templates/_content_icons.html.j2",
|
||||
"{% macro ci(name) -%}{% set paths = "
|
||||
+ json.dumps(icons)
|
||||
+ ' %}<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ paths.get(name, paths.file) }}"/></svg>{%- endmacro %}\n',
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Reproduce the original publication CSS/SVG, scoped to the accepted runtime shell."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from css_scope import scope_css
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
target = ROOT / "src/site_engine/web/admin"
|
||||
css = (ROOT / "design/assets/publication.css").read_text()
|
||||
css = re.sub(r"(?<![-\w])(?:html|body)(?![-\w])", ":scope", css).replace(":root", ":scope")
|
||||
css = css.replace(':scope[data-theme="antirion"]', ":scope").replace(
|
||||
':scope[data-theme="rose"]', ":scope[data-unused-rose]"
|
||||
)
|
||||
js = (ROOT / "design/assets/publication.js").read_text()
|
||||
data = js.split("const ico={", 1)[1].split("};", 1)[0]
|
||||
icons = dict(re.findall(r"(\w+):'([^']*)'", data))
|
||||
output = {
|
||||
target
|
||||
/ "static/publication.css": "/* Generated by scripts/sync_publication_design.py; original declarations unchanged. */\n"
|
||||
+ scope_css(css, ".publication-content", ":where(.publication-content)"),
|
||||
target / "templates/_publication_icons.html.j2": "{% macro pi(name) -%}{% set paths = "
|
||||
+ json.dumps(icons)
|
||||
+ ' %}<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ paths.get(name, paths.file) }}"/></svg>{%- endmacro %}\n',
|
||||
target / "static/publication-icons.json": json.dumps(icons, ensure_ascii=False) + "\n",
|
||||
}
|
||||
for path, content in output.items():
|
||||
if "--check" in sys.argv:
|
||||
if not path.exists() or path.read_text() != content:
|
||||
raise SystemExit(f"Publication design out of date: {path}")
|
||||
else:
|
||||
path.write_text(content)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -97,7 +97,7 @@ with TestClient(app) as client:
|
||||
assert response.status_code==200
|
||||
response=client.get('/admin/pages/index')
|
||||
assert response.status_code==200 and 'document-editor' in response.text
|
||||
for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js'):
|
||||
for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js','content-editor.css','content-adapter.css','content-editor.js','favicon.svg','publication.css','publication-adapter.css','publication.js','publication-icons.json'):
|
||||
assert client.get('/admin/static/'+name).status_code==200,name
|
||||
assert 'pages-screen' in client.get('/admin/pages').text
|
||||
cookie=client.cookies.get('se_session')
|
||||
@@ -139,8 +139,31 @@ with TestClient(app) as client:
|
||||
result=preview.get(result.json()['url'])
|
||||
assert result.status_code==200 and 'sample-site' in result.text,result.text
|
||||
assert '--color-primary: #a48bfa' in result.text
|
||||
response=client.get('/admin/content/services/bots')
|
||||
assert response.status_code==200 and 'entry-workspace' in response.text,response.text
|
||||
from site_engine.services.entries import EntryService
|
||||
entry=EntryService(Path(os.environ['SITE_ROOT']),collection='services').get('bots')
|
||||
result=client.post('/admin/editor/content/services/bots/update',data={'csrf':csrf,'payload':json.dumps({'source':entry.source,'etag':entry.etag,'revision':30,'preview_view':'card'})},headers={'Origin':'http://testserver','HX-Request':'true','Accept':'application/json'})
|
||||
assert result.status_code==200 and 'f-entry_card' in result.json()['preview']['html'],result.text
|
||||
assert 'data-content-tab' in result.json()['projection']
|
||||
assert 'data-publication-root' in client.get('/admin/publish').text
|
||||
def publication(op, payload=None):
|
||||
return client.post('/admin/publication/'+op,data={'csrf':csrf,'payload':json.dumps(payload or {})},headers={'Origin':'http://testserver','Accept':'application/json'})
|
||||
live=(Path(os.environ['SITE_DIST'])/'current').resolve().name
|
||||
candidate=publication('build')
|
||||
assert candidate.status_code==200,candidate.text
|
||||
identity=candidate.json()['id']
|
||||
assert (Path(os.environ['SITE_DIST'])/'current').resolve().name==live
|
||||
passive=publication('preview',{'id':identity,'route':'/'})
|
||||
assert passive.status_code==200,passive.text
|
||||
with TestClient(create_preview_app()) as preview:
|
||||
result=preview.get(passive.json()['url'])
|
||||
assert result.status_code==200 and '<script' not in result.text,result.text
|
||||
result=publication('activate',{'id':identity,'expected_live':live,'comment':'Installed wheel release'})
|
||||
assert result.status_code==200,result.text
|
||||
assert (Path(os.environ['SITE_DIST'])/'current').resolve().name==identity
|
||||
assert app.state.api_calls>0
|
||||
print('installed wheel: all theme presets, build, widths, static, templates, Theme Manager, API, background update, bridge, separate preview OK; design/ absent')
|
||||
print('installed wheel: all theme presets, build, widths, static, templates, Theme Manager, Content Editor, Publication candidates/preview/activation, API, background update, bridge, separate preview OK; design/ absent')
|
||||
"""
|
||||
subprocess.run([sys.executable, "-c", program], cwd=work, env=env, check=True)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user