Files
flexly-cms/tests/test_editor_updates.py

220 lines
12 KiB
Python

"""Stateless editor updates: batching, API isolation, one registry and explicit saves."""
import json
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from fastapi.testclient import TestClient
from theme_fixture import seed
from site_engine.core.registry import load_site
from site_engine.services.auth import hash_password
from site_engine.services.documents import DocumentService
from site_engine.services.pages import PageService
from site_engine.services.preview import PreviewStore
from site_engine.web.app import create_app
class EditorUpdateTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.password = "editor background test password"
cls.password_hash = hash_password(cls.password, n=2**10)
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.work = Path(tmp.name)
self.site = self.work / "site"
seed(self.site)
env = patch.dict(os.environ, {
"SITE_ROOT": str(self.site), "SITE_DIST": str(self.work / "dist"),
"SITE_STATE_DIR": str(self.work / "state"), "SITE_ADMIN_LOGIN": "admin",
"SITE_ADMIN_PASSWORD_HASH": self.password_hash,
"SITE_SECRET_KEY": "editor-update-test-secret-" * 3, "SITE_COOKIE_SECURE": "0",
"SITE_ADMIN_ORIGIN": "", "SITE_PREVIEW_ORIGIN": "",
})
env.start()
self.addCleanup(env.stop)
self.app = create_app()
self.client = TestClient(self.app)
self.addCleanup(self.client.close)
auth = self.app.state.auth
cookie = auth.login("admin", self.password, "testclient")
self.client.cookies.set("se_session", cookie)
self.app.state.api_credentials["test"] = (cookie, "testclient")
self.csrf = auth.csrf_token(auth.authenticate(cookie))
self.svc = PageService(self.site)
self.snap = self.svc.get("index")
self.payload = {"source": self.snap.source, "etag": self.snap.etag, "revision": 3,
"operations": []}
def api(self, payload=None, identity="pages/index", operation="update"):
return self.client.post("/admin/api/v1/" + identity + "/" + operation,
json=self.payload if payload is None else payload,
headers={"Authorization": "Bearer test"})
def ui(self, payload=None, csrf=None, operation="update"):
return self.client.post("/admin/editor/pages/index/" + operation,
data={"csrf": self.csrf if csrf is None else csrf,
"payload": json.dumps(self.payload if payload is None else payload),
"selection": "hero_home", "mode": "constructor"},
headers={"Origin": "http://testserver", "HX-Request": "true",
"Accept": "application/json"})
@staticmethod
def block(identity, **values):
return {"type": "block", "block_id": identity, "values": values}
def test_html_adapter_one_api_call_and_one_registry_for_update_and_preview(self):
self.payload["operations"] = [self.block("hero_home", note="First"),
self.block("richtext_child", note="Second")]
before = (self.site / "pages/index.md").read_bytes()
calls = self.app.state.api_calls
with patch("site_engine.services.documents.load_site", wraps=load_site) as load:
response = self.ui()
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(load.call_count, 1)
self.assertEqual(self.app.state.api_calls - calls, 1)
result = response.json()
self.assertIn("First", result["snapshot"]["source"])
self.assertIn("Second", result["snapshot"]["source"])
self.assertEqual(result["preview"]["revision"], 3)
self.assertIn("data-preview-id=", result["preview"]["html"])
self.assertIn("data-section-inspector", result["projection"])
self.assertNotIn("<textarea name='source'", result["projection"])
self.assertNotIn("data-raw-source", result["projection"])
self.assertNotIn("data-next-source", result["projection"])
self.assertEqual(before, (self.site / "pages/index.md").read_bytes())
self.assertFalse((self.site / ".engine/history").exists())
self.assertFalse((self.work / "dist/current").exists())
def test_no_operations_preserves_expert_source_bytes(self):
self.payload["source"] = self.snap.source.replace("---\n", "---\n# Keep comment\n", 1)
response = self.api()
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(response.json()["snapshot"]["source"], self.payload["source"])
def test_shared_inspector_parser_handles_nested_bindings_and_widths(self):
self.payload["operations"] = [{"type": "inspector", "fields": {
"operation": ["block"], "block_id": ["hero_home"],
"p.title._bind": ["page.title"], "p.subtitle": ["Updated subtitle"],
"p.actions.0.url.kind": ["url"], "p.actions.0.url.target": ["https://example.org"],
"p.actions.0.label": ["Background button"],
"block_layout.section_width": ["fluid"], "block_layout.content_width": ["boxed"],
}}]
response = self.api()
self.assertEqual(response.status_code, 200, response.text)
block = response.json()["snapshot"]["model"]["meta"]["regions"]["main"][0]
self.assertEqual(block["props"]["title"], {"bind": "page.title"})
self.assertEqual(block["layout"], {"section_width": "fluid", "content_width": "boxed"})
self.assertIn("Updated subtitle", response.json()["preview"]["html"])
def test_batch_is_all_or_nothing_for_invalid_later_action(self):
self.payload["operations"] = [self.block("hero_home", note="Must not leak"),
self.block("missing_block", note="Invalid")]
response = self.api()
self.assertEqual(response.status_code, 422)
error = response.json()["error"]
self.assertEqual(error["buffer"]["source"], self.snap.source)
self.assertNotIn("Must not leak", error["buffer"]["source"])
self.assertTrue(error["request_id"])
def test_invalid_form_and_malformed_source_preserve_input(self):
self.payload["operations"] = [{"type": "inspector", "fields": {
"operation": ["block"], "block_id": ["hero_home"],
"block_layout.section_width": ["wrong"],
}}]
response = self.ui()
self.assertEqual(response.status_code, 422, response.text)
self.assertEqual(response.json()["error"]["buffer"]["source"], self.snap.source)
self.assertIn("projection", response.json())
self.payload.update(source="---\ntitle: [broken\n---\n", operations=[])
response = self.ui()
self.assertEqual(response.status_code, 422, response.text)
self.assertEqual(response.json()["error"]["buffer"]["source"], self.payload["source"])
def test_preview_failure_returns_accepted_edit_and_traceable_error(self):
self.payload["operations"] = [self.block("hero_home", note="Accepted without preview")]
with patch.object(PreviewStore, "render_document", side_effect=OSError("disk full")), \
self.assertLogs("uvicorn.error", level="ERROR") as logs:
response = self.api()
self.assertEqual(response.status_code, 200, response.text)
result = response.json()
self.assertIn("Accepted without preview", result["snapshot"]["source"])
self.assertIsNone(result["preview"])
self.assertEqual(result["preview_error"]["code"], "preview_failed")
self.assertTrue(result["preview_error"]["request_id"])
self.assertIn("disk full", "\n".join(logs.output))
self.assertNotIn("Accepted without preview", "\n".join(logs.output))
def test_update_exception_uses_existing_error_boundary(self):
with patch.object(DocumentService, "update_buffer", side_effect=OSError("read failure")), \
self.assertLogs("uvicorn.error", level="ERROR"):
response = self.ui()
self.assertEqual(response.status_code, 500)
self.assertTrue(response.json()["error"]["request_id"])
def test_projection_programming_error_is_logged_as_500_not_invalid_input(self):
from site_engine.web.admin.application import AdminApplication
with patch.object(AdminApplication, "editor_projection", side_effect=TypeError("projection failure")), \
self.assertLogs("uvicorn.error", level="ERROR") as logs:
response = self.ui()
self.assertEqual(response.status_code, 500, response.text)
self.assertTrue(response.json()["error"]["request_id"])
self.assertIn("projection failure", "\n".join(logs.output))
def test_save_is_explicit_and_keeps_cas_conflict(self):
self.payload["operations"] = [self.block("hero_home", note="Explicit save")]
updated = self.ui().json()["snapshot"]
self.assertEqual((self.site / "pages/index.md").read_text(), self.snap.source)
save = {key: updated[key] for key in ("source", "etag", "revision")}
response = self.ui(save, operation="save")
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual((self.site / "pages/index.md").read_text(), updated["source"])
conflict = self.ui(save, operation="save")
self.assertEqual(conflict.status_code, 409, conflict.text)
self.assertEqual(conflict.json()["error"]["current"]["source"], updated["source"])
def test_csrf_auth_and_invalid_payload_errors_are_json(self):
response = self.ui(csrf="wrong")
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()["error"]["code"], "forbidden")
response = self.ui({**self.payload, "unknown": True})
self.assertEqual(response.status_code, 422)
self.assertTrue(response.json()["error"]["request_id"])
self.client.cookies.clear()
response = self.ui()
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()["error"]["code"], "session_expired")
def test_entry_update_uses_own_overlay_and_never_writes(self):
from site_engine.services.entries import EntryService
snap = EntryService(self.site, collection="articles").get("first")
payload = {"source": snap.source, "etag": snap.etag, "revision": 7, "operations": [
{"type": "entry_fields", "values": {"title": "New article title"}, "body": "Updated body"}
]}
response = self.api(payload, identity="collections/articles/entries/first")
self.assertEqual(response.status_code, 200, response.text)
self.assertIn("Updated body", response.json()["preview"]["html"])
self.assertEqual((self.site / "content/articles/first.md").read_text(), snap.source)
response = self.client.post('/admin/editor/entries/articles/first/update',
data={"csrf": self.csrf, "payload": json.dumps(payload)},
headers={"Origin": "http://testserver", "Accept": "application/json"})
self.assertEqual(response.status_code, 200, response.text)
self.assertNotIn("<textarea name='source'", response.json()["projection"])
self.assertNotIn("data-raw-source", response.json()["projection"])
def test_form_move_rejects_ambiguous_target(self):
self.payload["operations"] = [{"type": "inspector", "fields": {
"operation": ["move"], "block_id": ["hero_home"], "direction": ["down"],
"before": ["section_outer"],
}}]
response = self.api()
self.assertEqual(response.status_code, 422, response.text)
self.assertEqual(response.json()["error"]["buffer"]["source"], self.snap.source)