- 每次备份只要有"改名 / 跳过 / 复制失败"的条目,就在目标目录生成 .udbak-report-<时间>.csv - 列:类型、源相对路径、目标相对路径、处理、原因、大小(字节)、源修改时间;UTF-8 BOM,Excel 直接打开不乱码 - 只保留最近 10 份;清理阶段不会把这些文件当多余文件删掉 - GUI:新增"问题清单"按钮打开最近一份;完成弹窗给出 CSV 路径与整理好的条数 - 新增 4 项 CSV 相关测试(共 48 项)
275 lines
11 KiB
Python
275 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""不合规文件名 / 单条失败 不再中断整次备份 —— 回归测试。
|
|
|
|
运行: python -m unittest discover -s tests -p "test_*.py" -v
|
|
"""
|
|
import csv
|
|
import io
|
|
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('a<b>c: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))
|
|
|
|
|
|
class TestProblemCsv(Base):
|
|
def _csv_rows(self, path):
|
|
with io.open(path, encoding="utf-8-sig", newline="") as f:
|
|
return list(csv.reader(f))
|
|
|
|
def test_no_problem_no_csv(self):
|
|
write(os.path.join(self.src, "ok.txt"), b"ok")
|
|
ok, stats = self.run_engine()
|
|
self.assertTrue(ok)
|
|
self.assertIsNone(stats["report_csv"])
|
|
self.assertEqual([n for n in os.listdir(self.dst) if n.startswith(ub.REPORT_PREFIX)], [])
|
|
|
|
def test_skipped_name_goes_to_csv(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', 7, 1700000000 * 10 ** 9))
|
|
return files, dirs
|
|
|
|
eng._scan = scan_with_illegal
|
|
ok, stats = eng.run()
|
|
self.assertTrue(ok)
|
|
self.assertTrue(stats["report_csv"])
|
|
self.assertTrue(os.path.isfile(stats["report_csv"]))
|
|
rows = self._csv_rows(stats["report_csv"])
|
|
self.assertEqual(rows[0][:5], ["类型", "源相对路径", "目标相对路径", "处理", "原因"])
|
|
self.assertEqual(rows[0][5:], ["大小(字节)", "源修改时间"])
|
|
body = [r for r in rows[1:] if "bad" in r[1]]
|
|
self.assertEqual(len(body), 1)
|
|
self.assertEqual(body[0][0], "文件")
|
|
self.assertEqual(body[0][3], "已跳过")
|
|
self.assertIn("非法字符", body[0][4])
|
|
self.assertEqual(body[0][5], "7")
|
|
self.assertTrue(body[0][6].startswith("2023-11-15"))
|
|
|
|
def test_renamed_goes_to_csv(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"):
|
|
ok, stats = self.run_engine()
|
|
self.assertTrue(ok)
|
|
rows = self._csv_rows(stats["report_csv"])
|
|
body = [r for r in rows[1:] if r[1] == "report.bin"]
|
|
self.assertEqual(len(body), 1)
|
|
self.assertEqual(body[0][3], "已改名")
|
|
self.assertEqual(body[0][2], "report_fixed.bin")
|
|
|
|
def test_csv_is_not_cleaned_up(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, "x?.txt"), "x?.txt", 1, 0))
|
|
return files, dirs
|
|
|
|
eng._scan = scan_with_illegal
|
|
ok, stats = eng.run()
|
|
csv_path = stats["report_csv"]
|
|
self.assertTrue(os.path.isfile(csv_path))
|
|
# 再跑一次全量:清理阶段不能把 .udbak-report-*.csv 当"多余文件"
|
|
ok2, _ = self.run_engine()
|
|
self.assertTrue(ok2)
|
|
self.assertTrue(os.path.isfile(csv_path))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|