"""定时备份功能测试:备份内容一致性、保留策略、调度时间计算。 Run with: python -m unittest discover -s tests -p "test_backup.py" -v """ import shutil import sqlite3 import tempfile import time import unittest from contextlib import closing from datetime import datetime from pathlib import Path from uuid import uuid4 from server.backup import _backup_once_sync, parse_time, seconds_until def make_db(path: Path) -> None: with closing(sqlite3.connect(str(path))) as conn: conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)") conn.executemany("INSERT INTO t (name) VALUES (?)", [(f"row{i}",) for i in range(50)]) conn.commit() class BackupTests(unittest.TestCase): def setUp(self): self.directory = Path(tempfile.gettempdir()) / f"worklog-backup-{uuid4().hex}" self.directory.mkdir() self.db = self.directory / "worklog.db" make_db(self.db) def tearDown(self): shutil.rmtree(self.directory) def test_backup_creates_consistent_copy(self): dest = _backup_once_sync(self.db, self.directory / "backups", keep=14) self.assertTrue(dest.exists()) self.assertEqual(dest.parent.name, "backups") with closing(sqlite3.connect(str(self.db))) as src: src_count = src.execute("SELECT COUNT(*) FROM t").fetchone()[0] with closing(sqlite3.connect(str(dest))) as copy: copy_count = copy.execute("SELECT COUNT(*) FROM t").fetchone()[0] self.assertEqual(copy_count, 50) self.assertEqual(src_count, copy_count) def test_backup_runs_while_db_in_wal_mode_with_uncommitted_wal(self): # 模拟服务运行中:开一个 WAL 连接写入但不 checkpoint with closing(sqlite3.connect(str(self.db))) as conn: conn.execute("PRAGMA journal_mode=WAL") conn.execute("INSERT INTO t (name) VALUES ('wal-only-row')") conn.commit() try: dest = _backup_once_sync(self.db, self.directory / "backups", keep=14) finally: pass with closing(sqlite3.connect(str(dest))) as copy: copy_count = copy.execute( "SELECT COUNT(*) FROM t WHERE name='wal-only-row'" ).fetchone()[0] self.assertEqual(copy_count, 1, "备份应包含 WAL 里未合并的数据") def test_retention_keeps_only_latest(self): bdir = self.directory / "backups" for _ in range(5): _backup_once_sync(self.db, bdir, keep=3) time.sleep(0.05) # 同秒会加 -2/-3 序号,不会被覆盖 files = sorted(bdir.glob("worklog-*.db")) self.assertEqual(len(files), 3, f"应只保留 3 份,实际 {len(files)}") def test_prune_does_not_touch_foreign_files(self): bdir = self.directory / "backups" bdir.mkdir() stranger = bdir / "other-20260101-000000.db" stranger.write_bytes(b"x") _backup_once_sync(self.db, bdir, keep=1) self.assertTrue(stranger.exists(), "不匹配命名规则的文件不应被清理") def test_seconds_until(self): base = datetime(2026, 10, 27, 22, 0, 0) self.assertEqual(seconds_until(23, 0, base), 3600.0) # 已过目标点:算明天 late = datetime(2026, 10, 27, 23, 30, 0) self.assertEqual(seconds_until(23, 0, late), 23.5 * 3600) # 恰好等于目标点:算明天(避免 0 延迟重复触发) exact = datetime(2026, 10, 27, 23, 0, 0) self.assertEqual(seconds_until(23, 0, exact), 24 * 3600) def test_parse_time(self): self.assertEqual(parse_time("23:00"), (23, 0)) self.assertEqual(parse_time("0:05"), (0, 5)) self.assertEqual(parse_time("25:00"), (23, 0), "非法时间回退 23:00") self.assertEqual(parse_time("abc"), (23, 0)) self.assertEqual(parse_time(""), (23, 0)) if __name__ == "__main__": unittest.main()