# -*- coding: utf-8 -*- """源盘完整性:哈希快照比对 + 备份后复查源文件是否被动过。""" import os import shutil import sys import tempfile import unittest from unittest import mock HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) sys.path.insert(0, ROOT) import usb_backup as ub # noqa: E402 def write(path, data=b"x", mtime=None): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "wb") as f: f.write(data) if mtime is not None: os.utime(path, (mtime, mtime)) def read(path): with open(path, "rb") as f: return f.read() class Base(unittest.TestCase): def setUp(self): self.base = tempfile.mkdtemp(prefix="srchash-") self.src = os.path.join(self.base, "src") self.dst = os.path.join(self.base, "dst") os.makedirs(self.src) os.makedirs(self.dst) def tearDown(self): shutil.rmtree(self.base, ignore_errors=True) def run_engine(self, **kw): kw.setdefault("log_callback", lambda m: None) return ub.BackupEngine(self.src, self.dst, **kw).run() @property def index_path(self): return os.path.join(self.dst, ub.SOURCE_INDEX_FILE) def load_index(self): import json with open(self.index_path, encoding="utf-8") as f: return json.load(f)["files"] class TestSnapshot(Base): def test_index_written_with_hashes(self): write(os.path.join(self.src, "a.txt"), b"alpha") write(os.path.join(self.src, "sub", "b.bin"), b"B" * 100) ok, stats = self.run_engine() self.assertTrue(ok) self.assertTrue(os.path.isfile(self.index_path)) idx = self.load_index() self.assertEqual(len(idx), 2) for entry in idx.values(): self.assertTrue(entry.get("sha256"), entry) self.assertEqual(len(entry["sha256"]), 64) def test_second_run_clean(self): write(os.path.join(self.src, "a.txt"), b"alpha") self.run_engine() ok, stats = self.run_engine() self.assertTrue(ok) self.assertEqual(stats["source_suspect"], 0) self.assertEqual(stats["source_vanished"], 0) self.assertEqual(stats["source_modified"], 0) def test_silent_change_detected_and_backup_kept(self): p = os.path.join(self.src, "db.bin") write(p, b"V1" + b"\x00" * 1022) self.run_engine() st = os.stat(p) # 内容变了,但大小和 mtime 被还原(典型的介质比特翻转 / 静默改动) with open(p, "wb") as f: f.write(b"V2" + b"\x00" * 1022) os.utime(p, ns=(st.st_atime_ns, st.st_mtime_ns)) ok, stats = self.run_engine(source_snapshot=True) self.assertTrue(ok) self.assertEqual(stats["source_suspect"], 1) self.assertEqual(read(os.path.join(self.dst, "db.bin")), b"V1" + b"\x00" * 1022) actions = [p_["action"] for p_ in stats["problems"]] self.assertIn("源文件可疑", actions) # 基线不被覆盖:下一轮仍然告警 ok2, stats2 = self.run_engine(source_snapshot=True) self.assertEqual(stats2["source_suspect"], 1) def test_no_snapshot_no_rehash(self): """没开"源盘快照"时不做整盘重读,也就不会主动发现静默改动。""" p = os.path.join(self.src, "db.bin") write(p, b"V1" + b"\x00" * 1022) self.run_engine() st = os.stat(p) with open(p, "wb") as f: f.write(b"V2" + b"\x00" * 1022) os.utime(p, ns=(st.st_atime_ns, st.st_mtime_ns)) ok, stats = self.run_engine() # source_snapshot 默认 False self.assertTrue(ok) self.assertEqual(stats["source_suspect"], 0) def test_vanished_file_reported(self): write(os.path.join(self.src, "keep.txt"), b"keep") write(os.path.join(self.src, "sub", "gone.txt"), b"gone") self.run_engine() os.remove(os.path.join(self.src, "sub", "gone.txt")) ok, stats = self.run_engine() self.assertTrue(ok) self.assertEqual(stats["source_vanished"], 1) rows = [p_ for p_ in stats["problems"] if p_["action"] == "源文件消失"] self.assertEqual(len(rows), 1) self.assertEqual(rows[0]["src"], os.path.join("sub", "gone.txt")) def test_vanished_with_whole_dir_not_reported(self): write(os.path.join(self.src, "sub", "a.txt"), b"a") write(os.path.join(self.src, "sub", "b.txt"), b"b") self.run_engine() shutil.rmtree(os.path.join(self.src, "sub")) ok, stats = self.run_engine() self.assertTrue(ok) self.assertEqual(stats["source_vanished"], 0) def test_index_survives_cleanup(self): write(os.path.join(self.src, "a.txt"), b"alpha") self.run_engine() self.assertTrue(os.path.isfile(self.index_path)) self.run_engine() self.assertTrue(os.path.isfile(self.index_path)) class TestPostCheck(Base): def test_modification_during_backup_detected(self): write(os.path.join(self.src, "a.txt"), b"a" * 100) write(os.path.join(self.src, "b.txt"), b"b" * 100) real_copy = ub.BackupEngine._copy_one def modifying(self_, src, dst, size, mtime_ns): out = real_copy(self_, src, dst, size, mtime_ns) other = os.path.join(self.src, "b.txt") if os.path.basename(src) == "a.txt": with open(other, "ab") as f: f.write(b"tampered") return out with mock.patch.object(ub.BackupEngine, "_copy_one", modifying): ok, stats = self.run_engine() # 备份期间被改动的文件,复制阶段本身也可能失败;这里只关心"来源告警" self.assertGreaterEqual(stats["source_modified"], 1) rows = [p_ for p_ in stats["problems"] if p_["action"] == "备份期间被改动"] self.assertTrue(any(r["src"] == "b.txt" for r in rows), rows) def test_post_check_can_be_disabled(self): write(os.path.join(self.src, "a.txt"), b"a" * 100) write(os.path.join(self.src, "b.txt"), b"b" * 100) real_copy = ub.BackupEngine._copy_one def modifying(self_, src, dst, size, mtime_ns): out = real_copy(self_, src, dst, size, mtime_ns) if os.path.basename(src) == "a.txt": with open(os.path.join(self.src, "b.txt"), "ab") as f: f.write(b"x") return out with mock.patch.object(ub.BackupEngine, "_copy_one", modifying): ok, stats = self.run_engine(post_check=False) self.assertEqual(stats["source_modified"], 0) if __name__ == "__main__": unittest.main(verbosity=2)