zcbot/tests/test_disk_quota.py

86 lines
2.9 KiB
Python

"""disk_quota.py 单元测试。
不连真 DB ── parse_bytes / scan_user_dir / skip dotfile 行为 / 不存在路径,
都纯 Python 文件系统操作可单测。upsert / check_disk_quota 需要 DB,跳过(集成测覆盖)。
"""
from __future__ import annotations
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.storage.disk_quota import parse_bytes, scan_user_dir
class TestParseBytes(unittest.TestCase):
def test_int_passthrough(self):
self.assertEqual(parse_bytes(1024), 1024)
self.assertEqual(parse_bytes(0), 0)
def test_gb(self):
self.assertEqual(parse_bytes("5gb"), 5 * 1024 ** 3)
self.assertEqual(parse_bytes("5g"), 5 * 1024 ** 3)
self.assertEqual(parse_bytes("5GB"), 5 * 1024 ** 3)
def test_mb(self):
self.assertEqual(parse_bytes("500mb"), 500 * 1024 ** 2)
self.assertEqual(parse_bytes("500m"), 500 * 1024 ** 2)
def test_kb(self):
self.assertEqual(parse_bytes("1kb"), 1024)
def test_bytes(self):
self.assertEqual(parse_bytes("1024b"), 1024)
self.assertEqual(parse_bytes("1024"), 1024)
def test_float_suffix(self):
self.assertEqual(parse_bytes("1.5gb"), int(1.5 * 1024 ** 3))
def test_invalid(self):
self.assertIsNone(parse_bytes(""))
self.assertIsNone(parse_bytes("xxx"))
self.assertIsNone(parse_bytes("1.2.3"))
self.assertIsNone(parse_bytes(None))
class TestScanUserDir(unittest.TestCase):
def test_empty_dir(self):
with tempfile.TemporaryDirectory() as d:
b, c = scan_user_dir(Path(d))
self.assertEqual((b, c), (0, 0))
def test_nonexistent(self):
b, c = scan_user_dir(Path("/nonexistent/path/xxx"))
self.assertEqual((b, c), (0, 0))
def test_count_and_size(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
(root / "a.txt").write_bytes(b"hello") # 5
(root / "sub").mkdir()
(root / "sub" / "b.txt").write_bytes(b"world!") # 6
(root / "sub" / "c.txt").write_bytes(b"x" * 1000) # 1000
b, c = scan_user_dir(root)
self.assertEqual(b, 1011)
self.assertEqual(c, 3)
def test_skip_dotfile_toplevel(self):
"""顶层 .zcbot_tmp / .memory 被跳过(开发期临时 + 用户记忆,不算配额)。"""
with tempfile.TemporaryDirectory() as d:
root = Path(d)
(root / "a.txt").write_bytes(b"counted") # 7
(root / ".zcbot_tmp").mkdir()
(root / ".zcbot_tmp" / "skipped.py").write_bytes(b"x" * 99999)
(root / ".memory").mkdir()
(root / ".memory" / "core.md").write_bytes(b"x" * 99999)
b, c = scan_user_dir(root)
self.assertEqual(b, 7)
self.assertEqual(c, 1)
if __name__ == "__main__":
unittest.main()