from __future__ import annotations
import shutil
import tempfile
import unittest
from pathlib import Path
from tools.api_contracts.mod_tree import ensure_mod_chain
class EnsureModChainTest(unittest.TestCase):
def setUp(self) -> None:
self.root = Path(tempfile.mkdtemp())
def tearDown(self) -> None:
shutil.rmtree(self.root, ignore_errors=True)
def _read(self, rel: str) -> str:
return (self.root / rel).read_text(encoding="utf-8")
def test_creates_missing_chain(self):
actions = ensure_mod_chain(self.root, "im/im/v1/message/create.rs")
created = [a for a in actions if a.startswith("[CREATE]")]
self.assertEqual(len(created), 4)
self.assertIn("pub mod im;", self._read("im/mod.rs"))
self.assertIn("pub mod v1;", self._read("im/im/mod.rs"))
self.assertIn("pub mod message;", self._read("im/im/v1/mod.rs"))
self.assertIn("pub mod create;", self._read("im/im/v1/message/mod.rs"))
def test_skips_existing_pub_mod(self):
msg_mod = self.root / "im" / "im" / "v1" / "message" / "mod.rs"
msg_mod.parent.mkdir(parents=True, exist_ok=True)
msg_mod.write_text("//! message\n\npub mod create;\npub mod get;\n", encoding="utf-8")
actions = ensure_mod_chain(self.root, "im/im/v1/message/create.rs")
self.assertNotIn("[MOD]", "".join(a for a in actions if "message/mod.rs" in a))
content = msg_mod.read_text(encoding="utf-8")
self.assertEqual(content.count("pub mod create;"), 1)
self.assertIn("pub mod get;", content)
def test_appends_without_destroying_existing(self):
msg_mod = self.root / "im" / "im" / "v1" / "message" / "mod.rs"
msg_mod.parent.mkdir(parents=True, exist_ok=True)
original = "//! 消息模块\npub mod get;\npub use get::GetMessageRequest;\n"
msg_mod.write_text(original, encoding="utf-8")
ensure_mod_chain(self.root, "im/im/v1/message/create.rs")
content = msg_mod.read_text(encoding="utf-8")
self.assertIn("//! 消息模块", content)
self.assertIn("pub mod get;", content)
self.assertIn("pub use get::GetMessageRequest;", content)
self.assertIn("pub mod create;", content)
def test_dry_run_no_write(self):
actions = ensure_mod_chain(self.root, "a/b/c.rs", dry_run=True)
self.assertTrue(any("[CREATE]" in a for a in actions))
self.assertFalse((self.root / "a" / "mod.rs").exists())
def test_single_segment_no_mod_needed(self):
actions = ensure_mod_chain(self.root, "lonely.rs")
self.assertEqual(actions, [])
if __name__ == "__main__":
unittest.main()