# -*- coding: utf-8 -*- """不合规文件名 / 单条失败 不再中断整次备份 —— 回归测试。 运行: python -m unittest discover -s tests -p "test_*.py" -v """ 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 L(p): return p if p.startswith("\\\\?\\") else "\\\\?\\" + os.path.abspath(p) def write(path, data=b"x"): os.makedirs(L(os.path.dirname(path)), exist_ok=True) with open(L(path), "wb") as f: f.write(data) def read(path): with open(L(path), "rb") as f: return f.read() class Base(unittest.TestCase): def setUp(self): self.base = tempfile.mkdtemp(prefix="resil-") 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 TestDirFileConflict(Base): def test_conflict_does_not_abort(self): write(os.path.join(self.src, "node", "sub", "a.txt"), b"alpha") write(os.path.join(self.dst, "node"), b"old-file") # 目标同名位置是文件 ok, stats = self.run_engine() self.assertTrue(ok, stats) self.assertEqual(stats["failed"], 0) self.assertEqual(read(os.path.join(self.dst, "node", "sub", "a.txt")), b"alpha") # 旧文件没被销毁,进了隔离区 self.assertTrue(os.path.isdir(os.path.join(self.dst, ub.QUARANTINE_DIR))) class TestBadNameHandling(Base): def test_hard_bad_name_is_skipped_not_fatal(self): write(os.path.join(self.src, "good.txt"), b"good") eng = ub.BackupEngine(self.src, self.dst, log_callback=lambda m: None) real_scan = eng._scan def scan_with_illegal(): files, dirs = real_scan() files.append((os.path.join(self.src, 'bad"name.txt'), 'bad"name.txt', 3, 0)) return files, dirs eng._scan = scan_with_illegal ok, stats = eng.run() self.assertTrue(ok, stats) self.assertEqual(stats["skipped_bad"], 1) self.assertEqual(stats["copied"], 1) self.assertEqual(read(os.path.join(self.dst, "good.txt")), b"good") self.assertTrue(any("bad" in rel for rel, _why in stats["skipped_names"])) def test_copy_exception_is_recorded_not_fatal(self): write(os.path.join(self.src, "ok.txt"), b"ok") write(os.path.join(self.src, "boom.txt"), b"boom") real_copy = ub.BackupEngine._copy_one def flaky(self_, src, dst, size, mtime_ns): if src.endswith("boom.txt"): raise RuntimeError("模拟一个意料之外的异常") return real_copy(self_, src, dst, size, mtime_ns) with mock.patch.object(ub.BackupEngine, "_copy_one", flaky): ok, stats = self.run_engine() self.assertFalse(ok) # 有失败项 self.assertEqual(stats["failed"], 1) self.assertEqual(read(os.path.join(self.dst, "ok.txt")), b"ok") class TestRenameFallback(Base): """名字合法但目标上建不出来(如 FAT32 拒绝以点结尾的名字)时,改名继续。""" def test_file_rename_when_create_fails(self): write(os.path.join(self.src, "report.bin"), b"data") real_copy = ub.BackupEngine._copy_one def failing(self_, src, dst, size, mtime_ns): if os.path.basename(dst) == "report.bin": raise OSError(22, "The filename, directory name, or volume label syntax is incorrect.") return real_copy(self_, src, dst, size, mtime_ns) with mock.patch.object(ub.BackupEngine, "_copy_one", failing), \ mock.patch.object(ub, "sanitize_component", lambda n: "report_fixed.bin"): ok, stats = self.run_engine() self.assertTrue(ok, stats) self.assertEqual(stats["renamed"], 1) self.assertEqual(stats["skipped_bad"], 0) self.assertEqual(read(os.path.join(self.dst, "report_fixed.bin")), b"data") self.assertEqual(stats["name_map"].get("report.bin"), "report_fixed.bin") self.assertTrue(os.path.isfile(os.path.join(self.dst, ub.NAME_MAP_FILE))) def test_rename_is_deterministic_across_runs(self): write(os.path.join(self.src, "report.bin"), b"data") real_copy = ub.BackupEngine._copy_one def failing(self_, src, dst, size, mtime_ns): if os.path.basename(dst) == "report.bin": raise OSError(22, "invalid name") return real_copy(self_, src, dst, size, mtime_ns) with mock.patch.object(ub.BackupEngine, "_copy_one", failing), \ mock.patch.object(ub, "sanitize_component", lambda n: "report_fixed.bin"): ok1, stats1 = self.run_engine() ok2, stats2 = self.run_engine() self.assertTrue(ok1 and ok2) self.assertEqual(stats1["renamed"], 1) # 第二次靠 .udbak-name-map.json 直接命中已改名的文件,不再重复改名/复制 self.assertEqual(stats2["renamed"], 0) self.assertEqual(stats2["copied"], 0) self.assertEqual(read(os.path.join(self.dst, "report_fixed.bin")), b"data") def test_dead_dir_does_not_abort(self): write(os.path.join(self.src, "locked", "a.txt"), b"a") write(os.path.join(self.src, "open", "b.txt"), b"b") real = ub._ensure_dir def fake(path): if path.rstrip("\\").endswith("locked"): raise OSError(13, "拒绝访问(模拟)") return real(path) with mock.patch.object(ub, "_ensure_dir", fake): ok, stats = self.run_engine() self.assertFalse(ok) # 记了失败,但没有中断 self.assertEqual(stats["failed"], 1) self.assertEqual(read(os.path.join(self.dst, "open", "b.txt")), b"b") self.assertFalse(os.path.exists(os.path.join(self.dst, "locked"))) def test_rename_dir_machinery(self): """直接验证目录改名:非法字符被替换、写入映射、建出目录、子路径跟着走。""" eng = ub.BackupEngine(self.src, self.dst, log_callback=lambda m: None) eng._src_names[os.path.normcase("")] = {"a:b"} ok = eng._rename_dir("a:b", OSError(22, "invalid name")) self.assertTrue(ok) self.assertEqual(eng.dir_map[os.path.normcase("a:b")], "a_b") self.assertEqual(eng.name_map["a:b"], "a_b") self.assertTrue(os.path.isdir(os.path.join(self.dst, "a_b"))) self.assertEqual(eng._mapped_rel(os.path.join("a:b", "x.txt")), os.path.join("a_b", "x.txt")) class TestSanitize(unittest.TestCase): def test_illegal_chars(self): s = ub.sanitize_component('ac:d"e|f?g*h.txt') self.assertFalse(any(ch in s for ch in '<>:"|?*')) def test_trailing_dot_and_space(self): self.assertEqual(ub.sanitize_component("name. "), "name") def test_reserved(self): self.assertTrue(ub.sanitize_component("CON").startswith("_")) def test_too_long(self): s = ub.sanitize_component("长" * 400) self.assertLessEqual(len(s), 120) def test_name_problem_classification(self): self.assertTrue(ub.name_problem('a"b')[0]) # hard hard, why = ub.name_problem("name.") self.assertFalse(hard) self.assertIn("结尾", why) self.assertEqual(ub.name_problem("ok.txt"), (False, None)) if __name__ == "__main__": unittest.main(verbosity=2)