mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 08:58:36 +00:00
Reviewers on #340 (Oliwettoo, aslan2142) noted that the in-process gen.main tests print the tool's progress line and its 'no COM folder' error into the test output. Redirect stdout and stderr around those two calls. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
202 lines
7.7 KiB
Python
202 lines
7.7 KiB
Python
"""Tests for tools/gen_gdk_runtime_classes.py: atomic output, parsing and the CLI."""
|
|
import contextlib
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
try:
|
|
import resource # POSIX only: the failed-write tests cap the child's file size with it
|
|
except ImportError:
|
|
resource = None
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from tempfile import TemporaryDirectory
|
|
from unittest import mock
|
|
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(REPO / "tools"))
|
|
|
|
import gen_gdk_runtime_classes as gen # noqa: E402
|
|
|
|
SCRIPT = REPO / "tools" / "gen_gdk_runtime_classes.py"
|
|
|
|
|
|
def make_docs(root: Path) -> Path:
|
|
"""Create the smallest synthetic docs tree accepted by the generator."""
|
|
docs = root / "docs"
|
|
(docs / "COM").mkdir(parents=True)
|
|
return docs
|
|
|
|
|
|
def command(docs: Path, output: Path) -> list[str]:
|
|
return [sys.executable, "-I", str(SCRIPT), str(docs), "--out", str(output)]
|
|
|
|
|
|
def fail_after_bytes(limit: int):
|
|
def set_file_limit() -> None:
|
|
resource.setrlimit(resource.RLIMIT_FSIZE, (limit, limit))
|
|
signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
|
|
|
|
return set_file_limit
|
|
|
|
|
|
NEEDS_RLIMIT = unittest.skipIf(resource is None, "needs POSIX resource limits (RLIMIT_FSIZE)")
|
|
|
|
|
|
class GenGdkRuntimeClassesTests(unittest.TestCase):
|
|
@NEEDS_RLIMIT
|
|
def test_failed_write_preserves_existing_file(self) -> None:
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
docs = make_docs(root)
|
|
output = root / "table.json"
|
|
original = b"previous table must survive\n"
|
|
output.write_bytes(original)
|
|
|
|
# Validate that this input reaches the output path and exceeds the limit.
|
|
successful = subprocess.run(command(docs, output), capture_output=True, check=False)
|
|
self.assertEqual(successful.returncode, 0, successful.stderr.decode(errors="replace"))
|
|
self.assertGreater(output.stat().st_size, 64)
|
|
output.write_bytes(original)
|
|
|
|
failed = subprocess.run(command(docs, output), capture_output=True, check=False,
|
|
preexec_fn=fail_after_bytes(64))
|
|
self.assertNotEqual(failed.returncode, 0, failed.stdout.decode(errors="replace"))
|
|
self.assertEqual(output.read_bytes(), original)
|
|
|
|
@NEEDS_RLIMIT
|
|
def test_failed_write_leaves_no_temporary_file(self) -> None:
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
docs = make_docs(root)
|
|
output = root / "table.json"
|
|
output.write_bytes(b"existing table")
|
|
before = set(os.listdir(root))
|
|
|
|
failed = subprocess.run(command(docs, output), capture_output=True, check=False,
|
|
preexec_fn=fail_after_bytes(64))
|
|
|
|
self.assertNotEqual(failed.returncode, 0, failed.stdout.decode(errors="replace"))
|
|
self.assertEqual(set(os.listdir(root)), before)
|
|
|
|
def test_successful_write_produces_valid_json(self) -> None:
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
docs = make_docs(root)
|
|
output = root / "table.json"
|
|
|
|
result = subprocess.run(command(docs, output), capture_output=True, check=False)
|
|
|
|
self.assertEqual(result.returncode, 0, result.stderr.decode(errors="replace"))
|
|
with output.open(encoding="utf-8") as stream:
|
|
table = json.load(stream)
|
|
self.assertEqual(table["classes"], {})
|
|
self.assertEqual(table["interfaces"], {})
|
|
|
|
|
|
|
|
class TestParseLayout(unittest.TestCase):
|
|
def test_returns_none_without_layout_section(self) -> None:
|
|
self.assertIsNone(gen.parse_layout("# IFoo\nNo known methods.\n"))
|
|
|
|
def test_parses_methods_and_unknown_slots(self) -> None:
|
|
doc = (
|
|
"# IExample\n\n"
|
|
"Layout:\n"
|
|
"- [Query](Query.md)\n"
|
|
"- *unknown*\n"
|
|
"- PlainMethod\n"
|
|
"\nTrailing paragraph stops parsing.\n"
|
|
"- IgnoredBullet\n"
|
|
)
|
|
self.assertEqual(gen.parse_layout(doc), ["Query", None, "PlainMethod"])
|
|
|
|
|
|
class TestParseDocsAndCheck(unittest.TestCase):
|
|
def test_missing_com_folder_raises(self) -> None:
|
|
with TemporaryDirectory() as tmp:
|
|
with self.assertRaises(FileNotFoundError):
|
|
gen.parse_docs(tmp)
|
|
|
|
def test_parses_classes_and_interfaces_and_detects_missing_links(self) -> None:
|
|
with TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
cls_dir = root / "COM" / "XUserImpl"
|
|
cls_dir.mkdir(parents=True)
|
|
|
|
(cls_dir / "README.md").write_text(
|
|
"Class Id: `AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE`\n"
|
|
"Implements: [IXUser](IXUser.md), [IMissing](IMissing.md)\n",
|
|
encoding="utf-8",
|
|
)
|
|
(cls_dir / "IXUser.md").write_text(
|
|
"Interface Id: `11111111-2222-3333-4444-555555555555`\n"
|
|
"Inherits: IUnknown\n"
|
|
"Layout:\n"
|
|
"- GetId\n",
|
|
encoding="utf-8",
|
|
)
|
|
(cls_dir / "IXUser2.md").write_text(
|
|
"Interface Id: `66666666-7777-8888-9999-000000000000`\n"
|
|
"Inherits: [IXMissingBase](IXMissingBase.md)\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
classes, interfaces = gen.parse_docs(tmp)
|
|
self.assertEqual(
|
|
classes["XUserImpl"],
|
|
{"id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "implements": ["IXUser", "IMissing"]},
|
|
)
|
|
self.assertIsNone(interfaces["IXUser"]["inherits"])
|
|
self.assertEqual(interfaces["IXUser"]["methods"], ["GetId"])
|
|
self.assertEqual(interfaces["IXUser2"]["inherits"], "IXMissingBase")
|
|
self.assertIsNone(interfaces["IXUser2"]["methods"])
|
|
|
|
problems = gen.check(classes, interfaces)
|
|
self.assertIn("XUserImpl implements IMissing, which has no page", problems)
|
|
self.assertIn("IXUser2 inherits IXMissingBase, which has no page", problems)
|
|
|
|
|
|
class TestBuildAndMain(unittest.TestCase):
|
|
def test_revision_fallback_when_not_git_repo(self) -> None:
|
|
with TemporaryDirectory() as tmp:
|
|
self.assertEqual(gen.revision(tmp), "unknown revision")
|
|
|
|
def test_main_writes_json_and_handles_missing_docs(self) -> None:
|
|
with TemporaryDirectory() as tmp:
|
|
missing_dir = str(Path(tmp) / "does_not_exist")
|
|
with contextlib.redirect_stderr(io.StringIO()):
|
|
self.assertEqual(gen.main([missing_dir]), 1)
|
|
|
|
docs = Path(tmp) / "docs"
|
|
cls_dir = docs / "COM" / "Demo"
|
|
cls_dir.mkdir(parents=True)
|
|
(cls_dir / "README.md").write_text(
|
|
"Class Id: `00000000-0000-0000-0000-000000000001`\n"
|
|
"Implements: [IDemo](IDemo.md)\n",
|
|
encoding="utf-8",
|
|
)
|
|
(cls_dir / "IDemo.md").write_text(
|
|
"Interface Id: `00000000-0000-0000-0000-000000000002`\n"
|
|
"Inherits: IUnknown\n"
|
|
"Layout:\n"
|
|
"- Ping\n",
|
|
encoding="utf-8",
|
|
)
|
|
out_json = Path(tmp) / "out.json"
|
|
with mock.patch.object(gen, "revision", return_value="deadbeef"), \
|
|
contextlib.redirect_stdout(io.StringIO()):
|
|
rc = gen.main([str(docs), "--out", str(out_json)])
|
|
self.assertEqual(rc, 0)
|
|
data = json.loads(out_json.read_text(encoding="utf-8"))
|
|
self.assertTrue(data["source"].endswith("deadbeef"))
|
|
self.assertEqual(data["interfaces"]["IDemo"]["methods"], ["Ping"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|