The IR called them react-message and django-message, so a FastAPI channel had to declare a DjangoMessage. They are client-message and server-message now, and the direction words hold wherever a channel is declared: Params / ClientMessage / ServerMessage, with mizan-core deriving <Pascal>Params and friends so no backend names a type itself. Django's ReactChannel and FastAPI's ReactChannel are both Channel. mizan-fastapi never registered a channels extension, so build_ir() emitted no channel at all and every payload type was invisible to codegen. It registers one now. RegistryExtension is an ABC requiring all(), which is what the IR reads — an extension that cannot enumerate its registrations no longer exists. The gate that should have caught the rename could not: tests/afi registered no channel because mizan-rust had no channel registry to register one in, so a five-package rename of the wire contract passed byte-parity without a channel byte crossing it. mizan-rust grows ChannelSlotKind, a CHANNELS slice, a #[mizan::channel] macro, and KDL emission whose wire_to_pascal matches Python's split; the AFI fixture now carries a channel with every slot and one with a single slot, so all three backends prove the contract byte for byte. MizanChannel held three Option<String> beside three has_*() predicates and unwrapped them with defaults; it holds an ordered slot vector, so an absent slot is absent rather than defaulted. The channels target emitted a React hooks file that a stage1-only consumer could not compile — react emits that now. The codegen's parity tests byte-compared emitted source against baselines without ever compiling it: they compile the generated crate and run its tests, import the generated Python package and call every method, and typecheck each TypeScript target against a consumer. Also fixed at source: app_visitor printed its import diagnostic to stdout, the stream export_mizan_ir writes KDL to, so a failed import silently corrupted the IR; the apps root was hardcoded to "apps"; _default_literal crashed build_ir on any non-JSON-serializable field default; Django and mizan-core derived Pascal names two different ways, disagreeing on every dotted channel name. ir.py builds a document and renders templates/ir/document.kdl.j2 rather than appending KDL strings with hand-tracked indentation, and named types resolve to a fixed point — a model reachable only through a union branch was referenced by a ref that no type block ever defined. The rest is the write-gate's own classifiers run over the standing tree: relative imports, silent swallows, Protocol contracts that should be ABCs, emitters hand-rendering target source, catch-all arms over closed enums, and comments narrating the project rather than the code. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
158 lines
5.7 KiB
Python
158 lines
5.7 KiB
Python
"""
|
|
Tests for the SSR bridge and the MizanTemplates Django template backend.
|
|
|
|
The bridge shells out to Bun, so every test here skips unless `bun` is on PATH
|
|
and the worker script is present.
|
|
"""
|
|
|
|
import os
|
|
import shutil
|
|
import threading
|
|
|
|
from django.test import SimpleTestCase, RequestFactory
|
|
|
|
_REPO_ROOT = os.path.normpath(
|
|
os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..")
|
|
)
|
|
_SSR_WORKER = os.path.join(_REPO_ROOT, "workers", "mizan-ssr", "src", "worker.tsx")
|
|
_COMPONENT_DIR = os.path.join(os.path.dirname(__file__), "ssr_components")
|
|
_HELLO = os.path.join(_COMPONENT_DIR, "Hello.tsx")
|
|
|
|
_BUN_AVAILABLE = shutil.which("bun") is not None
|
|
_SKIP_MSG = "Bun not available"
|
|
|
|
|
|
class SSRBridgeTests(SimpleTestCase):
|
|
"""Tests for the SSR bridge subprocess manager."""
|
|
|
|
def setUp(self):
|
|
if not _BUN_AVAILABLE:
|
|
self.skipTest(_SKIP_MSG)
|
|
if not os.path.exists(_SSR_WORKER):
|
|
self.skipTest(f"SSR worker not found at {_SSR_WORKER}")
|
|
|
|
from mizan.ssr.bridge import SSRBridge
|
|
self.bridge = SSRBridge(worker_path=_SSR_WORKER, timeout=10.0)
|
|
|
|
def tearDown(self):
|
|
if hasattr(self, "bridge"):
|
|
self.bridge.shutdown()
|
|
|
|
def test_render_starts_worker_and_returns_html(self):
|
|
"""The first render boots the worker and returns rendered markup."""
|
|
result = self.bridge.render(_HELLO, {"name": "World"})
|
|
self.assertIn("Hello,", result.html)
|
|
self.assertIn("World", result.html)
|
|
|
|
def test_render_passes_props_through(self):
|
|
"""Props reach the component."""
|
|
result = self.bridge.render(_HELLO, {"name": "Alice"})
|
|
self.assertIn("Alice", result.html)
|
|
self.assertIn('data-mizan-component="Hello"', result.html)
|
|
|
|
def test_render_missing_file_raises(self):
|
|
"""Rendering a path with no module raises RuntimeError naming the failure."""
|
|
missing = os.path.join(_COMPONENT_DIR, "DoesNotExist.tsx")
|
|
with self.assertRaises(RuntimeError):
|
|
self.bridge.render(missing, {})
|
|
|
|
def test_crash_recovery(self):
|
|
"""The bridge restarts the worker if it dies."""
|
|
result = self.bridge.render(_HELLO, {"name": "Before"})
|
|
self.assertIn("Before", result.html)
|
|
|
|
self.bridge._proc.kill()
|
|
self.bridge._proc.wait()
|
|
|
|
result = self.bridge.render(_HELLO, {"name": "After"})
|
|
self.assertIn("After", result.html)
|
|
|
|
def test_concurrent_renders(self):
|
|
"""Concurrent callers each get their own response matched by message id."""
|
|
results = {}
|
|
errors = {}
|
|
|
|
def render_in_thread(name: str, idx: int):
|
|
try:
|
|
results[idx] = self.bridge.render(_HELLO, {"name": name}).html
|
|
except Exception as e:
|
|
errors[idx] = e
|
|
|
|
threads = []
|
|
for i in range(5):
|
|
t = threading.Thread(target=render_in_thread, args=(f"User{i}", i))
|
|
threads.append(t)
|
|
t.start()
|
|
|
|
for t in threads:
|
|
t.join(timeout=20)
|
|
|
|
self.assertEqual(errors, {})
|
|
self.assertEqual(len(results), 5)
|
|
for i in range(5):
|
|
self.assertIn(f"User{i}", results[i])
|
|
|
|
|
|
class SSRTemplateBackendTests(SimpleTestCase):
|
|
"""Tests for the MizanTemplates Django template backend."""
|
|
|
|
def setUp(self):
|
|
if not _BUN_AVAILABLE:
|
|
self.skipTest(_SKIP_MSG)
|
|
if not os.path.exists(_SSR_WORKER):
|
|
self.skipTest(f"SSR worker not found at {_SSR_WORKER}")
|
|
|
|
from mizan.ssr.backend import MizanTemplates
|
|
self.engine = MizanTemplates({
|
|
"NAME": "mizan-test",
|
|
"DIRS": [_COMPONENT_DIR],
|
|
"APP_DIRS": False,
|
|
"OPTIONS": {
|
|
"worker": _SSR_WORKER,
|
|
"timeout": 10,
|
|
},
|
|
})
|
|
self.factory = RequestFactory()
|
|
|
|
def tearDown(self):
|
|
if hasattr(self, "engine") and self.engine._bridge is not None:
|
|
self.engine._bridge.shutdown()
|
|
|
|
def test_get_template_resolves_name_to_file(self):
|
|
"""get_template resolves the name against DIRS to an absolute file path."""
|
|
from mizan.ssr.backend import MizanTemplate
|
|
template = self.engine.get_template("Hello.tsx")
|
|
self.assertIsInstance(template, MizanTemplate)
|
|
self.assertEqual(template.file_path, os.path.abspath(_HELLO))
|
|
|
|
def test_missing_template_raises(self):
|
|
"""A name that resolves to no file under DIRS raises TemplateDoesNotExist."""
|
|
from django.template import TemplateDoesNotExist
|
|
with self.assertRaises(TemplateDoesNotExist):
|
|
self.engine.get_template("NoSuchComponent.tsx")
|
|
|
|
def test_template_render_emits_html_and_hydration_data(self):
|
|
"""render() wraps the markup and serializes the props for hydration."""
|
|
template = self.engine.get_template("Hello.tsx")
|
|
html = template.render({"name": "Django"})
|
|
self.assertIn("Hello,", html)
|
|
self.assertIn("Django", html)
|
|
self.assertIn('id="mizan-root"', html)
|
|
self.assertIn('window.__MIZAN_SSR_DATA__={"name": "Django"}', html)
|
|
|
|
def test_template_render_strips_django_internals(self):
|
|
"""request and csrf_token are dropped from props and from hydration data."""
|
|
template = self.engine.get_template("Hello.tsx")
|
|
request = self.factory.get("/")
|
|
html = template.render(
|
|
{"name": "Test", "request": request, "csrf_token": "abc"}, request
|
|
)
|
|
self.assertIn("Test", html)
|
|
self.assertNotIn("csrf_token", html)
|
|
self.assertNotIn("abc", html)
|
|
|
|
def test_from_string_is_unsupported(self):
|
|
"""This engine renders modules by path, so it has no source-string form."""
|
|
with self.assertRaises(NotImplementedError):
|
|
self.engine.from_string("<div>Not supported</div>")
|