# -*- coding: utf-8 -*- """损坏目录项(FAT32 半坏)时的行为:不崩溃、只跳过、不误删备份。""" 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)) class Base(unittest.TestCase): def setUp(self): self.base = tempfile.mkdtemp(prefix="corrupt-") 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() class TestTimestampFormat(unittest.TestCase): def test_garbage_timestamps_do_not_raise(self): for ns in (None, 0, -1, -2 ** 63, 2 ** 63 - 1, 10 ** 30): out = ub.BackupEngine._fmt_ns(ns) self.assertIsInstance(out, str) def test_normal_timestamp(self): self.assertEqual(ub.BackupEngine._fmt_ns(1600000000 * 10 ** 9), "2020-09-13 20:26:40") class TestCorruptFileEntry(Base): def test_unreadable_entry_reported_not_fatal(self): write(os.path.join(self.src, "good.txt"), b"good") write(os.path.join(self.src, "ghost.bin"), b"ghost") real_copy = ub.BackupEngine._copy_one def ghost(self_, src, dst, size, mtime_ns): if os.path.basename(src) == "ghost.bin": raise FileNotFoundError(2, "系统找不到指定的文件", src) return real_copy(self_, src, dst, size, mtime_ns) with mock.patch.object(ub.BackupEngine, "_copy_one", ghost): ok, stats = self.run_engine() self.assertFalse(ok) # 备份不完整,必须报出来 self.assertEqual(stats["corrupt"], 1) actions = [p["action"] for p in stats["problems"]] self.assertIn("源目录项损坏", actions) with open(os.path.join(self.dst, "good.txt"), "rb") as f: self.assertEqual(f.read(), b"good") class TestCorruptDirEntry(Base): def test_corrupt_dir_skipped_and_cleanup_disabled(self): # 源里有一棵"名字非法"的目录(真实场景是目录项被写坏) write(os.path.join(self.src, "keep.txt"), b"keep") eng = ub.BackupEngine(self.src, self.dst, log_callback=lambda m: None) real_scan = eng._scan def scan_with_corrupt_dir(): files, dirs = real_scan() dirs.append('bad?dir') return files, dirs eng._scan = scan_with_corrupt_dir ok, stats = eng.run() # 不能抛异常 self.assertEqual(stats["corrupt"], 1) self.assertTrue(any(p["action"] == "已跳过" and "目录项" in p["reason"] for p in stats["problems"])) # 损坏目录不会在备份里造出空目录 self.assertFalse(any(n.startswith("bad") for n in os.listdir(self.dst))) # 关键:源盘有坏条目时,不能在备份里做删除(保护已有备份) self.assertEqual(stats["quarantined"], 0) self.assertEqual(stats["deleted"], 0) def test_existing_backup_copies_are_kept(self): write(os.path.join(self.src, "keep.txt"), b"keep") write(os.path.join(self.dst, "old.txt"), b"old") # 之前备份里已有、这次源里没有 eng = ub.BackupEngine(self.src, self.dst, log_callback=lambda m: None) real_scan = eng._scan def scan_with_corrupt_dir(): files, dirs = real_scan() dirs.append('bad?dir') return files, dirs eng._scan = scan_with_corrupt_dir eng.run() self.assertTrue(os.path.isfile(os.path.join(self.dst, "old.txt"))) if __name__ == "__main__": unittest.main(verbosity=2)