50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
import stat
|
|
import tempfile
|
|
import unittest
|
|
|
|
from herdr_hub.aliases import (
|
|
AliasRegistry,
|
|
AliasRegistryError,
|
|
MAX_ALIAS_LENGTH,
|
|
normalize_alias,
|
|
)
|
|
|
|
|
|
class AliasRegistryTests(unittest.TestCase):
|
|
def test_set_reset_round_trip_and_permissions(self) -> None:
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "config" / "aliases.json"
|
|
registry = AliasRegistry(path)
|
|
|
|
self.assertEqual(registry.load(), {})
|
|
self.assertTrue(registry.set("remote:orangepi:default", " 客厅主机 "))
|
|
self.assertFalse(registry.set("remote:orangepi:default", "客厅主机"))
|
|
self.assertEqual(
|
|
registry.load(),
|
|
{"remote:orangepi:default": "客厅主机"},
|
|
)
|
|
self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
|
|
self.assertTrue(registry.set("remote:orangepi:default", ""))
|
|
self.assertEqual(registry.load(), {})
|
|
|
|
def test_invalid_aliases_and_corrupt_registry_are_rejected(self) -> None:
|
|
with self.assertRaises(ValueError):
|
|
normalize_alias("x" * (MAX_ALIAS_LENGTH + 1))
|
|
with self.assertRaises(ValueError):
|
|
normalize_alias("bad\nname")
|
|
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "aliases.json"
|
|
path.write_text("not json", encoding="utf-8")
|
|
registry = AliasRegistry(path)
|
|
with self.assertRaises(AliasRegistryError):
|
|
registry.set("local:default", "工作")
|
|
self.assertEqual(path.read_text(encoding="utf-8"), "not json")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|