Support categorized fragments, theme presets, block widths, and server-backed theme editing with onboarding and preview. Include Site Studio, design sources, specification and verification reports; remove the legacy studio-site example.
233 lines
13 KiB
Python
233 lines
13 KiB
Python
"""Width contract through parsing, document operations and real HTTP boundaries."""
|
|
|
|
import os
|
|
import tempfile
|
|
import unittest
|
|
from dataclasses import asdict
|
|
from html.parser import HTMLParser
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
from fastapi.testclient import TestClient
|
|
from test_fragment_catalog_ui import environment
|
|
from theme_fixture import seed, write
|
|
|
|
from site_engine.build.pipeline import build_site, make_views
|
|
from site_engine.core.block_layout import BlockLayout, default_layout
|
|
from site_engine.core.layout_marks import apply_layout
|
|
from site_engine.core.models import parse_block
|
|
from site_engine.core.page_ops import find_block
|
|
from site_engine.core.registry import load_site
|
|
from site_engine.core.render import Renderer
|
|
from site_engine.core.routes import build_route_table
|
|
from site_engine.core.validate import validate_workspace
|
|
from site_engine.errors import Report
|
|
from site_engine.parsing.yamlio import dump_yaml
|
|
from site_engine.services.auth import hash_password
|
|
from site_engine.services.documents import DocumentService, EditorContext
|
|
|
|
|
|
class Elements(HTMLParser):
|
|
def __init__(self, html):
|
|
super().__init__()
|
|
self.items = []
|
|
self.feed(html)
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
self.items.append((tag, dict(attrs)))
|
|
|
|
|
|
class BlockLayoutTest(unittest.TestCase):
|
|
def test_strict_shapes_modes_and_unknown_keys(self):
|
|
for raw in (None, False, [], "full", {"width": "boxed"}, {"section_width": []},
|
|
{"section_width": "wide"}, {"content_width": 1080}, {"content_width": None}):
|
|
with self.subTest(layout=raw):
|
|
report = Report()
|
|
block = parse_block({"id": "test_block", "fragment": "hero", "layout": raw}, "test", report)
|
|
self.assertIsNone(block)
|
|
self.assertIn("E_BLOCK_LAYOUT", report.codes())
|
|
self.assertTrue(all(".layout" in i.path for i in report.errors))
|
|
|
|
def test_all_modes_defaults_and_explicit_inheritance(self):
|
|
for fragment in ("hero", "cta_banner", "site_header", "site_footer", "richtext", "columns"):
|
|
block = parse_block({"id": "test_block", "fragment": fragment}, "test", Report())
|
|
self.assertIsNone(block.layout)
|
|
expected = "full" if fragment in ("hero", "cta_banner", "site_header", "site_footer") else "inherit"
|
|
self.assertEqual(default_layout(fragment).section_width, expected)
|
|
for section in ("inherit", "boxed", "fluid", "full"):
|
|
for content in ("inherit", "boxed", "fluid", "full"):
|
|
report = Report()
|
|
block = parse_block({"id": "test_block", "fragment": "hero", "layout": {"section_width": section, "content_width": content}}, "test", report)
|
|
self.assertTrue(report.ok)
|
|
effective = block.layout.resolve("fluid")
|
|
self.assertEqual(effective.section_width, "fluid" if section == "inherit" else section)
|
|
self.assertEqual(effective.content_width, "fluid" if content == "inherit" else content)
|
|
|
|
def test_layout_marks_do_not_change_roots_or_overwrite_nested_block_containers(self):
|
|
child = apply_layout('<section class="child"><div class="container"><img src="x"></div></section>', BlockLayout("boxed", "fluid"))
|
|
source = '<header class="sticky"><div class="f-container">' + child + '</div></header><aside>Second root</aside>'
|
|
html = apply_layout(source, BlockLayout("full", "boxed"))
|
|
self.assertEqual(html.count("<header"), 1)
|
|
self.assertEqual(html.count("<section"), 1)
|
|
self.assertEqual(html.count("<div"), 2)
|
|
elements = Elements(html).items
|
|
self.assertEqual(elements[0][1]["data-section-width"], "full")
|
|
self.assertEqual(elements[1][1]["data-engine-container"], "boxed")
|
|
self.assertEqual(elements[2][1]["data-section-width"], "boxed")
|
|
self.assertEqual(elements[3][1]["data-engine-container"], "fluid")
|
|
self.assertEqual(elements[-1][1]["data-section-width"], "full")
|
|
|
|
|
|
class LayoutIntegrationTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.password = "temporary layout password"
|
|
cls.password_hash = hash_password(cls.password, n=2**10)
|
|
|
|
def setUp(self):
|
|
temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(temp.cleanup)
|
|
self.work = Path(temp.name)
|
|
self.site, self.out = self.work / "site", self.work / "dist"
|
|
seed(self.site)
|
|
env = patch.dict(os.environ, environment(self.site, self.work, self.password_hash))
|
|
env.start()
|
|
self.addCleanup(env.stop)
|
|
from site_engine.web.app import create_app
|
|
self.app = create_app()
|
|
self.client = TestClient(self.app)
|
|
self.addCleanup(self.client.close)
|
|
self.cookie = self.app.state.auth.login("admin", self.password, "testclient")
|
|
self.client.cookies.set("se_session", self.cookie)
|
|
self.principal = self.app.state.auth.authenticate(self.cookie)
|
|
self.csrf = self.app.state.auth.csrf_token(self.principal)
|
|
self.app.state.api_credentials["test-layout"] = (self.cookie, "testclient")
|
|
self.headers = {"Authorization": "Bearer test-layout"}
|
|
self.service = DocumentService(self.site)
|
|
|
|
def api(self, method, path, data=None):
|
|
return self.client.request(method, "/admin/api/v1" + path, json=data, headers=self.headers)
|
|
|
|
def test_page_display_fixed_entry_and_slots_share_renderer_contract(self):
|
|
reg = load_site(self.site)
|
|
self.assertTrue(validate_workspace(reg).ok)
|
|
table = build_route_table(reg, Report())
|
|
renderer = Renderer(reg, table, Report(), preview_mode=True)
|
|
views = make_views(reg, table, Report())
|
|
attrs = []
|
|
for view in views:
|
|
html, _ = renderer.render(view)
|
|
attrs.extend(a for _, a in Elements(html).items if a.get("data-preview-id"))
|
|
by_id = {a["data-preview-id"]: a for a in attrs}
|
|
for identity, section, content, scope in (
|
|
("hero_home", "full", "boxed", "page"), ("section_outer", "fluid", "full", "page"),
|
|
("richtext_child", "boxed", "fluid", "page"), ("header_fixed", "full", "boxed", "layout"),
|
|
("display_text", "full", "boxed", "display"), ("entry_text", "fluid", "full", "entry"),
|
|
):
|
|
self.assertEqual(by_id[identity]["data-section-width"], section)
|
|
self.assertEqual(by_id[identity]["data-content-width"], content)
|
|
self.assertEqual(by_id[identity]["data-preview-scope"], scope)
|
|
|
|
def test_snapshot_has_typed_layout_for_fixed_display_and_raw_page(self):
|
|
snap = self.service.get("index")
|
|
self.assertEqual(snap.schema["container"]["gutter"]["mobile"], 16)
|
|
self.assertEqual(snap.model["meta"]["regions"]["main"][0]["layout"]["content_width"], "boxed")
|
|
# Fixed layout omitted in YAML is still absent/default, not explicit inherit.
|
|
self.assertIsNone(snap.schema["regions"]["header"]["fixed"][0]["layout"])
|
|
entry = DocumentService(self.site, collection="articles")
|
|
entry.kind = "entry"
|
|
self.assertEqual(entry.get("first").schema["display"]["main"][0]["layout"], {"section_width": "full", "content_width": "boxed"})
|
|
|
|
def test_transform_props_duplicate_move_save_and_reopen_preserve_layout(self):
|
|
snap = self.service.get("index")
|
|
original = (self.site / "pages/index.md").read_bytes()
|
|
layout = {"section_width": "boxed", "content_width": "full"}
|
|
for action in (
|
|
{"type": "block", "block_id": "hero_home", "values": {"layout": layout}},
|
|
{"type": "block", "block_id": "hero_home", "values": {"props": {"title": "Новое название"}}},
|
|
{"type": "duplicate", "block_id": "hero_home"},
|
|
{"type": "move", "block_id": "hero_home", "after": "section_outer"},
|
|
{"type": "toggle", "block_id": "hero_home"},
|
|
{"type": "add", "fragment": "richtext", "region": "main"},
|
|
):
|
|
snap = self.service.transform_buffer("index", snap.source, snap.etag, action)
|
|
self.assertTrue(snap.report.ok, snap.report.issues)
|
|
self.assertEqual(find_block(snap.model["meta"], "hero_home")[2]["layout"], layout)
|
|
self.assertEqual((self.site / "pages/index.md").read_bytes(), original)
|
|
copies = [b for b in snap.model["meta"]["regions"]["main"] if b["fragment"] == "hero"]
|
|
self.assertEqual(len(copies), 2)
|
|
self.assertTrue(all(b["layout"] == layout for b in copies))
|
|
self.service.save_source("index", snap.source, snap.etag, EditorContext(self.principal))
|
|
self.assertEqual(find_block(self.service.get("index").model["meta"], "hero_home")[2]["layout"], layout)
|
|
|
|
def test_api_transform_rejects_bad_width_and_keeps_explicit_null_fields(self):
|
|
snap = self.api("GET", "/pages/index/source").json()
|
|
data = {k: snap[k] for k in ("source", "etag", "revision")}
|
|
data["action"] = {"type": "block", "block_id": "hero_home", "values": {"layout": {"section_width": "full", "content_width": "fluid"}, "anchor": "hero-anchor"}}
|
|
response = self.api("POST", "/pages/index/transform", data)
|
|
self.assertEqual(response.status_code, 200, response.text)
|
|
data["source"] = response.json()["source"]
|
|
data["action"]["values"] = {"anchor": None}
|
|
response = self.api("POST", "/pages/index/transform", data)
|
|
self.assertEqual(response.status_code, 200, response.text)
|
|
block = response.json()["model"]["meta"]["regions"]["main"][0]
|
|
self.assertIsNone(block["anchor"])
|
|
self.assertEqual(block["layout"]["content_width"], "fluid")
|
|
for layout in (None, [], {"section_width": "bad"}, {"content_width": False}, {"width": "full"}):
|
|
data["action"]["values"] = {"layout": layout}
|
|
response = self.api("POST", "/pages/index/transform", data)
|
|
self.assertEqual(response.status_code, 422, response.text)
|
|
self.assertTrue(response.json()["error"]["request_id"])
|
|
|
|
def test_expert_and_core_refuse_invalid_layout_without_mutating_source(self):
|
|
snap = self.service.get("index")
|
|
changed = self.service.transform_buffer("index", snap.source, snap.etag, {"type": "block", "block_id": "richtext_child", "values": {"layout": {"content_width": "bad"}}})
|
|
self.assertIn("E_BLOCK_LAYOUT", changed.report.codes())
|
|
self.assertEqual(changed.source, snap.source)
|
|
invalid = snap.source.replace("section_width: full", "section_width: wide", 1)
|
|
checked = self.service.validate_source("index", invalid, snap.etag)
|
|
self.assertIsNone(checked.model)
|
|
self.assertIn("E_BLOCK_LAYOUT", checked.report.codes())
|
|
|
|
def test_html_inspector_posts_through_api_without_saving(self):
|
|
snap = self.service.get("index")
|
|
response = self.client.get("/admin/pages/index")
|
|
self.assertEqual(response.status_code, 200, response.text)
|
|
self.assertIn("Макет блока · ширина", response.text)
|
|
self.assertIn("data-block-width='section_width'", response.text)
|
|
data = {"csrf": self.csrf, "etag": snap.etag, "revision": 1, "source": snap.source,
|
|
"selection": "hero_home", "block_id": "hero_home", "mode": "constructor",
|
|
"operation": "block", "p.title": "Новое название",
|
|
"block_layout.section_width": "fluid", "block_layout.content_width": "full"}
|
|
response = self.client.post("/admin/editor/pages/index/transform", data=data,
|
|
headers={"Origin": "http://testserver", "HX-Request": "true"})
|
|
self.assertEqual(response.status_code, 200, response.text)
|
|
self.assertIn("section_width: fluid", response.text)
|
|
self.assertEqual((self.site / "pages/index.md").read_text(), snap.source)
|
|
data["block_layout.section_width"] = "bad"
|
|
response = self.client.post("/admin/editor/pages/index/transform", data=data,
|
|
headers={"Origin": "http://testserver", "HX-Request": "true"})
|
|
self.assertEqual(response.status_code, 422, response.text)
|
|
self.assertEqual((self.site / "pages/index.md").read_text(), snap.source)
|
|
|
|
def test_theme_error_reaches_api_html_preview_and_publish_without_switching_live(self):
|
|
live = build_site(self.site, self.out)
|
|
snap = self.service.get("index")
|
|
write(self.site, "theme.yaml", dump_yaml({"schema": 1, "preset": "unknown", "preset_version": 1, "overrides": {}}))
|
|
response = self.api("POST", "/pages/index/preview", {k: asdict(snap)[k] for k in ("source", "etag", "revision")})
|
|
self.assertEqual(response.status_code, 422, response.text)
|
|
self.assertIn("E_THEME_VALUE", response.text)
|
|
response = self.api("POST", "/publish")
|
|
self.assertEqual(response.status_code, 422)
|
|
self.assertIn("E_THEME_VALUE", response.text)
|
|
response = self.client.post("/admin/publish", data={"csrf": self.csrf},
|
|
headers={"Origin": "http://testserver", "HX-Request": "true"})
|
|
self.assertEqual(response.status_code, 422, response.text)
|
|
self.assertIn("E_THEME_VALUE", response.text)
|
|
self.assertEqual(os.readlink(self.out / "current"), live.build_id)
|
|
|
|
def test_openapi_exposes_layout_enum(self):
|
|
schema = self.app.openapi()["components"]["schemas"]["BlockLayoutDTO"]
|
|
self.assertEqual(schema["properties"]["section_width"]["enum"], ["inherit", "boxed", "fluid", "full"])
|
|
self.assertFalse(schema["additionalProperties"])
|