reportist/tests/test_render.py

232 lines
12 KiB
Python

import importlib.util
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("reportist_render", ROOT / "tests" / "support_render.py")
renderer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(renderer)
TYPST = shutil.which("typst")
PDFINFO = shutil.which("pdfinfo")
PDFTOTEXT = shutil.which("pdftotext")
@unittest.skipUnless(TYPST, "Typst is not installed")
class RenderTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.work = Path(self.temporary.name)
def tearDown(self):
self.temporary.cleanup()
def assert_pdf(self, path):
self.assertTrue(path.read_bytes().startswith(b"%PDF-"))
self.assertGreater(path.stat().st_size, 1000)
def test_yaml_and_json_examples_render(self):
for example in ("example-report.yaml", "example-report.json"):
with self.subTest(example=example):
output = self.work / f"{example}.pdf"
renderer.render(ROOT / "examples" / example, output, TYPST)
self.assert_pdf(output)
def test_minimal_report_renders_without_optional_fields(self):
output = self.work / "minimal.pdf"
renderer.render(ROOT / "examples" / "minimal-report.json", output, TYPST)
self.assert_pdf(output)
def test_typst_plugin_produces_valid_report_ir(self):
plugin = self.work / "plugin"
plugin.mkdir()
(plugin / "plugin.json").write_text(json.dumps({
"name": "example", "interface_version": 1, "input": "example-v1",
"output": "reportist-v1", "transform": "transform.typ",
}), encoding="utf-8")
(plugin / "transform.typ").write_text(
'#let transform(data) = (schema_version: 1, title: data.title, '
'metadata: (Date: "2026-09-16", Author: sys.inputs.at("plugin-author")), '
'sections: ((title: "Plugin section", content: '
'((type: "text", text: data.message),)),))\n', encoding="utf-8")
source = self.work / "source.json"
source.write_text(json.dumps({"title": "Converted input", "message": "Mapped by Typst"}), encoding="utf-8")
output = self.work / "plugin.pdf"
ir = self.work / "plugin.ir.json"
result = subprocess.run([
"bash", str(ROOT / "render.sh"), str(source), "--plugin", str(plugin),
"--plugin-input", "author=Plugin Test", "--output", str(output),
"--emit-ir", str(ir),
], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_pdf(output)
document = json.loads(ir.read_text(encoding="utf-8"))
self.assertEqual(document["title"], "Converted input")
self.assertEqual(document["metadata"]["Author"], "Plugin Test")
self.assertEqual(document["sections"][0]["content"][0]["text"], "Mapped by Typst")
def test_authored_report_uses_diagnostic_layout_blocks(self):
output = self.work / "diagnostic-style.pdf"
renderer.render(ROOT / "examples" / "diagnostic-style.yaml", output, TYPST)
self.assert_pdf(output)
if PDFTOTEXT:
extracted = subprocess.run([PDFTOTEXT, str(output), "-"],
text=True, capture_output=True, check=True).stdout
for phrase in ("Executive overview", "Observed signal score",
"Findings requiring attention", "Technical evidence"):
self.assertIn(phrase, extracted)
def test_invalid_input_leaves_no_pdf(self):
report = self.work / "invalid.json"
report.write_text(json.dumps({"schema_version": 2}), encoding="utf-8")
output = self.work / "invalid.pdf"
with self.assertRaisesRegex(ValueError, "invalid report"):
renderer.render(report, output, TYPST)
self.assertFalse(output.exists())
def test_replaceable_branding_logo_renders(self):
(self.work / "assets").mkdir()
(self.work / "assets" / "logo.svg").write_text(
'<svg xmlns="http://www.w3.org/2000/svg" width="80" height="24">'
'<rect width="80" height="24" fill="#663399"/></svg>', encoding="utf-8")
report = {"schema_version": 1, "title": "Alternate Brand", "metadata": {
"Date": "2026-09-15", "Author": "Synthetic Author"}, "branding": {
"organization": "Unrelated Example", "logo": "assets/logo.svg",
"theme": {"accent": "#663399"}}}
input_path = self.work / "brand.json"
input_path.write_text(json.dumps(report), encoding="utf-8")
output = self.work / "brand.pdf"
renderer.render(input_path, output, TYPST)
self.assert_pdf(output)
def test_named_theme_renders_and_unknown_name_is_rejected(self):
report = {"schema_version": 1, "title": "Named theme", "metadata": {
"Date": "2026-09-15", "Author": "Synthetic Author"},
"branding": {"organization": "Example", "theme": "teal"}}
input_path = self.work / "named-theme.json"
input_path.write_text(json.dumps(report), encoding="utf-8")
output = self.work / "named-theme.pdf"
renderer.render(input_path, output, TYPST)
self.assert_pdf(output)
report["branding"]["theme"] = "unknown"
input_path.write_text(json.dumps(report), encoding="utf-8")
with self.assertRaisesRegex(ValueError, "invalid report"):
renderer.render(input_path, self.work / "unknown-theme.pdf", TYPST)
def test_card_block_renders_nested_content(self):
report = {"schema_version": 1, "title": "Card example", "metadata": {
"Date": "2026-09-15", "Author": "Synthetic Author"},
"sections": [{"title": "Overview", "content": [{"type": "card",
"title": "Evidence review", "tone": "success", "content": [
{"type": "text", "text": "The capture is preserved."},
{"type": "bullets", "items": ["Verify its hash.", "Keep the original."]}]}]}]}
input_path = self.work / "cards.json"
input_path.write_text(json.dumps(report), encoding="utf-8")
output = self.work / "cards.pdf"
renderer.render(input_path, output, TYPST)
self.assert_pdf(output)
if PDFTOTEXT:
extracted = subprocess.check_output([PDFTOTEXT, str(output), "-"], text=True)
for phrase in ("Evidence review", "The capture is preserved.", "Verify its hash."):
self.assertIn(phrase, extracted)
def test_text_block_formats_balanced_inline_code(self):
report = {"schema_version": 1, "title": "Inline code", "metadata": {
"Date": "2026-09-15", "Author": "Synthetic Author"},
"sections": [{"title": "Revisions", "content": [
{"type": "text", "text": "Pinned `5661ea1` and `5969196`."},
{"type": "text", "text": "Unmatched ` stays literal."}]}]}
input_path = self.work / "inline.json"
input_path.write_text(json.dumps(report), encoding="utf-8")
output = self.work / "inline.pdf"
renderer.render(input_path, output, TYPST)
self.assert_pdf(output)
if PDFTOTEXT:
extracted = subprocess.check_output([PDFTOTEXT, "-layout", str(output), "-"], text=True)
self.assertRegex(extracted, r"Pinned\s+5661ea1\s+and\s+5969196\s*\.")
self.assertIn("Unmatched ` stays literal.", extracted)
def test_existing_output_requires_force_and_input_is_never_output(self):
input_path = ROOT / "examples" / "minimal-report.json"
output = self.work / "report.pdf"
output.write_bytes(b"existing")
with self.assertRaisesRegex(ValueError, "output exists"):
renderer.render(input_path, output, TYPST)
self.assertEqual(output.read_bytes(), b"existing")
renderer.render(input_path, output, TYPST, force=True)
self.assert_pdf(output)
with self.assertRaisesRegex(ValueError, "must differ"):
renderer.render(input_path, input_path, TYPST, force=True)
def test_logo_symlink_is_rejected(self):
outside = self.work / "outside.svg"
outside.write_text('<svg xmlns="http://www.w3.org/2000/svg"/>', encoding="utf-8")
report_dir = self.work / "report"
report_dir.mkdir()
(report_dir / "logo.svg").symlink_to(outside)
report = {"schema_version": 1, "title": "Unsafe asset", "metadata": {
"Date": "2026-09-15", "Author": "Synthetic Author"},
"branding": {"logo": "logo.svg"}}
input_path = report_dir / "report.json"
input_path.write_text(json.dumps(report), encoding="utf-8")
with self.assertRaisesRegex(ValueError, "symlinks"):
renderer.render(input_path, self.work / "unsafe.pdf", TYPST)
def test_cli_runs_outside_repository(self):
output = self.work / "outside-cwd.pdf"
result = subprocess.run([
"bash", str(ROOT / "render.sh"),
str(ROOT / "examples" / "minimal-report.json"), "--output", str(output),
], cwd=self.work, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_pdf(output)
@unittest.skipUnless(PDFINFO and PDFTOTEXT, "Poppler PDF inspection tools are not installed")
def test_long_content_paginates_without_losing_tail_content(self):
paragraphs = [
{"type": "text", "text": f"Pagination paragraph {index}: " +
"Synthetic content exercises wrapping and page flow. " * 8}
for index in range(1, 41)
]
paragraphs.append({"type": "callout", "kind": "success",
"title": "Completion marker", "text": "END-OF-LONG-REPORT"})
report = {"schema_version": 1, "title": "Long pagination exercise",
"metadata": {"Date": "2026-09-15", "Author": "Synthetic Author"},
"sections": [{"title": "Sustained content", "content": paragraphs}]}
input_path = self.work / "long.json"
input_path.write_text(json.dumps(report), encoding="utf-8")
output = self.work / "long.pdf"
renderer.render(input_path, output, TYPST)
self.assert_pdf(output)
info = subprocess.run([PDFINFO, str(output)], text=True, capture_output=True, check=True)
pages = next(int(line.split(":", 1)[1]) for line in info.stdout.splitlines()
if line.startswith("Pages:"))
self.assertGreaterEqual(pages, 4)
text_output = self.work / "long.txt"
subprocess.run([PDFTOTEXT, str(output), str(text_output)], check=True)
extracted = text_output.read_text(encoding="utf-8")
self.assertIn("Pagination paragraph 1", extracted)
self.assertIn("Pagination paragraph 40", extracted)
self.assertIn("END-OF-LONG-REPORT", extracted)
def test_standalone_component_copy_renders_example(self):
standalone = self.work / "standalone"
shutil.copytree(ROOT, standalone, ignore=shutil.ignore_patterns(
".git", ".ci-venv", "__pycache__", "*.pyc"))
output = self.work / "standalone.pdf"
result = subprocess.run([
"bash", str(standalone / "render.sh"),
str(standalone / "examples" / "example-report.yaml"),
"--output", str(output), "--typst", TYPST,
], cwd=self.work, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_pdf(output)
if __name__ == "__main__":
unittest.main()