fix(загрузка): распаковка архивов не глотает ошибки — перебор распаковщиков и честное сообщение
Живой случай 13.11.2026: RAR5 181 МБ распаковался частично (13 файлов из 120 нулевые/обрезанные), ошибка ушла только в audit_log — человек видел обычный ответ. - unrar первым для .rar: официальный распаковщик берёт архив, на котором unar сдаётся - успех только после сверки размеров КАЖДОГО файла с каталогом архива; код 1 unrar (предупреждение) при полной распаковке — успех, код 2 и выше — нет - при неполном/полном провале, бомбе, таймауте и отсутствии распаковщика — сообщение в чат: сколько и каких файлов не извлеклось и что делать, без внутрянки - общий замок на папку результата: повторная загрузка не стирает её у первой распаковки - многотомники: сверка по первому тому отключена; WinRAR .partN.rar распознаётся - версия 2026-11-13b Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -50,7 +50,8 @@ class _FakeGrowingProc:
|
||||
def test_bomb_extraction_killed_and_cleaned(monkeypatch, tmp_path):
|
||||
out = tmp_path / "out"
|
||||
monkeypatch.setattr(archive_host, "MAX_EXTRACT_BYTES", 4 * 1024 * 1024) # 4 МБ кап
|
||||
monkeypatch.setattr(archive_host, "_backend", lambda: "unar")
|
||||
monkeypatch.setattr(archive_host, "_tools_for", lambda entry: ["unar"])
|
||||
monkeypatch.setattr(archive_host, "_archive_members", lambda entry: None)
|
||||
monkeypatch.setattr(archive_host.subprocess, "Popen", lambda *a, **k: _FakeGrowingProc(out))
|
||||
|
||||
res = archive_host._run_unar(tmp_path / "bomb.rar", out)
|
||||
@@ -66,8 +67,9 @@ class _FakeSymlinkProc:
|
||||
(out / "real.gge").write_bytes(b"<x/>")
|
||||
try:
|
||||
(out / "evil.gge").symlink_to(target) # симлинк на секрет вне out
|
||||
except OSError:
|
||||
pass
|
||||
except OSError as e:
|
||||
# Без симлинка проверка ниже зелена вхолостую — это не прогон, а тишина.
|
||||
raise RuntimeError("симлинк не создан — проверка невозможна") from e
|
||||
self.returncode = 0
|
||||
|
||||
def poll(self):
|
||||
@@ -84,7 +86,8 @@ def test_extraction_strips_symlinks(monkeypatch, tmp_path):
|
||||
secret = tmp_path / "secret_outside.txt"
|
||||
secret.write_text("HOST-SECRET")
|
||||
out = tmp_path / "out"
|
||||
monkeypatch.setattr(archive_host, "_backend", lambda: "unar")
|
||||
monkeypatch.setattr(archive_host, "_tools_for", lambda entry: ["unar"])
|
||||
monkeypatch.setattr(archive_host, "_archive_members", lambda entry: None)
|
||||
monkeypatch.setattr(archive_host.subprocess, "Popen",
|
||||
lambda *a, **k: _FakeSymlinkProc(out, secret))
|
||||
res = archive_host._run_unar(tmp_path / "evil.rar", out)
|
||||
|
||||
+444
-17
@@ -7,30 +7,293 @@ import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import archive_host as ah
|
||||
|
||||
|
||||
def test_rar_retries_after_partial_backend_and_replaces_truncated_file(monkeypatch, tmp_path):
|
||||
archive = tmp_path / "сметы.rar"
|
||||
archive.write_bytes(b"rar")
|
||||
commands = []
|
||||
monkeypatch.setattr(ah.shutil, "which", lambda tool: f"/bin/{tool}" if tool in {"unrar", "unar"} else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: {"смета.gge": 100})
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
commands.append(cmd[0])
|
||||
out = tmp_path / "сметы_extracted"
|
||||
if cmd[0] == "unar":
|
||||
# Остаток прошлой попытки обязан быть снесён до второй распаковки:
|
||||
# иначе в папке смешались бы файлы двух движков.
|
||||
assert not (out / "смета.gge").exists(), "папка не очищена перед сменой бэкенда"
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / "смета.gge").write_bytes(b"x" * (20 if cmd[0] == "unrar" else 100))
|
||||
self.returncode = 1 if cmd[0] == "unrar" else 0
|
||||
|
||||
def poll(self):
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return self.returncode
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah.extract_rarlike(archive, tmp_path)
|
||||
assert commands == ["unrar", "unar"]
|
||||
assert result["ok"] is True
|
||||
assert (tmp_path / "сметы_extracted" / "смета.gge").stat().st_size == 100
|
||||
|
||||
|
||||
def _run_async(monkeypatch, ah, tmp_path, result):
|
||||
"""Вызвать extract_rarlike_async синхронно и вернуть (messages, audits)."""
|
||||
import db
|
||||
|
||||
messages, audits = [], []
|
||||
monkeypatch.setattr(ah, "extract_rarlike", lambda archive, work: result)
|
||||
monkeypatch.setattr(db, "save_message", lambda *args: messages.append(args))
|
||||
monkeypatch.setattr(db, "log_action", lambda *args: audits.append(args))
|
||||
|
||||
class InlineThread:
|
||||
def __init__(self, target, **kwargs):
|
||||
self.target = target
|
||||
|
||||
def start(self):
|
||||
self.target()
|
||||
|
||||
monkeypatch.setattr(ah.threading, "Thread", InlineThread)
|
||||
ah.extract_rarlike_async(tmp_path / "сметы.rar", tmp_path, "user", "tab")
|
||||
return messages, audits
|
||||
|
||||
|
||||
def test_partial_failure_text_names_count_and_files(monkeypatch, tmp_path):
|
||||
"""Частичный провал: человек видит СКОЛЬКО файлов и КАКИЕ, и что делать."""
|
||||
messages, audits = _run_async(monkeypatch, ah, tmp_path, {
|
||||
"ok": False, "error": "exit-1", "extracted": 107,
|
||||
"failed_files": ["A.gge", "B.pdf"],
|
||||
})
|
||||
assert messages == [("user", "tab", "system",
|
||||
"Не удалось полностью распаковать архив сметы.rar: "
|
||||
"не извлеклось 2 файла (A.gge, B.pdf). "
|
||||
"Результат распаковки не готов к работе. Повторите загрузку архива; "
|
||||
"если файлы снова не извлекутся, пришлите их по отдельности.")]
|
||||
assert len(audits) == 1 and audits[0][1] == "rar_extract_fail"
|
||||
|
||||
|
||||
def test_partial_failure_long_list_is_cut(monkeypatch, tmp_path):
|
||||
"""Список из 20 имён не вываливается в чат целиком: 8 имён и «и ещё 12»."""
|
||||
names = [f"смета{i}.gge" for i in range(20)]
|
||||
messages, _ = _run_async(monkeypatch, ah, tmp_path, {
|
||||
"ok": False, "error": "exit-1", "extracted": 3, "failed_files": names,
|
||||
})
|
||||
text = messages[0][3]
|
||||
assert "не извлеклось 20 файлов" in text
|
||||
for i in range(8): # все первые восемь названы, не только восьмое
|
||||
assert f"смета{i}.gge" in text
|
||||
assert "смета7.gge и ещё 12" in text and "смета19.gge" not in text
|
||||
|
||||
|
||||
def test_total_failure_does_not_pretend_partial(monkeypatch, tmp_path):
|
||||
"""Ни один файл не извлечён — «не распакован», а не «не полностью»."""
|
||||
messages, _ = _run_async(monkeypatch, ah, tmp_path, {
|
||||
"ok": False, "error": "exit-1", "extracted": 0, "failed_files": ["A.gge"],
|
||||
})
|
||||
text = messages[0][3]
|
||||
assert text.startswith("Архив сметы.rar не распакован.")
|
||||
assert "не извлеклось" not in text and "A.gge" not in text
|
||||
|
||||
|
||||
def test_bomb_and_timeout_explained_without_internals(monkeypatch, tmp_path):
|
||||
for error, phrase in (("extract-too-large", "превышает допустимый объём"),
|
||||
("extract-timeout", "не завершилась за отведённое время")):
|
||||
messages, _ = _run_async(monkeypatch, ah, tmp_path, {
|
||||
"ok": False, "error": error, "extracted": 0, "failed_files": []})
|
||||
text = messages[0][3]
|
||||
assert phrase in text, text
|
||||
assert "exit-" not in text and "unar" not in text and "unrar" not in text and "7z" not in text
|
||||
|
||||
|
||||
def test_no_backend_explained_in_chat(monkeypatch, tmp_path):
|
||||
messages, audits = _run_async(monkeypatch, ah, tmp_path, {
|
||||
"ok": False, "error": "no-backend"})
|
||||
assert messages[0][3] == ("Архив сметы.rar не распакован: распаковщик недоступен. "
|
||||
"Повторите загрузку позже; если не получится, "
|
||||
"пришлите файлы по отдельности.")
|
||||
assert len(audits) == 1
|
||||
|
||||
|
||||
def test_timeout_stops_fallback(monkeypatch, tmp_path):
|
||||
"""Таймаут — не повод звать второй распаковщик: он упрётся в тот же потолок."""
|
||||
archive = tmp_path / "a.rar"
|
||||
archive.write_bytes(b"rar")
|
||||
commands = []
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool in {"unrar", "unar"} else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: {"a.gge": 10})
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
commands.append(cmd[0])
|
||||
self.returncode = None
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
def wait(self, timeout=None):
|
||||
if timeout is None: # ожидание после kill — процесс уже мёртв
|
||||
self.returncode = -9
|
||||
return -9
|
||||
raise ah.subprocess.TimeoutExpired(cmd="x", timeout=timeout)
|
||||
|
||||
def kill(self):
|
||||
self.returncode = -9
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah.extract_rarlike(archive, tmp_path)
|
||||
assert commands == ["unrar"]
|
||||
assert result["ok"] is False and result["error"] == "extract-timeout"
|
||||
|
||||
|
||||
def test_rc1_with_complete_listing_is_success(monkeypatch, tmp_path):
|
||||
"""unrar пишет «OK» и всё же отдаёт код 1 на предупреждении — полная распаковка успех."""
|
||||
archive = tmp_path / "a.rar"
|
||||
archive.write_bytes(b"rar")
|
||||
commands = []
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool in {"unrar", "unar"} else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: {"a.gge": 10})
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
commands.append(cmd[0])
|
||||
(tmp_path / "a_extracted").mkdir(exist_ok=True)
|
||||
(tmp_path / "a_extracted" / "a.gge").write_bytes(b"x" * 10)
|
||||
self.returncode = 1
|
||||
|
||||
def poll(self):
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return self.returncode
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah.extract_rarlike(archive, tmp_path)
|
||||
assert commands == ["unrar"]
|
||||
assert result["ok"] is True and result["files"] == 1
|
||||
|
||||
|
||||
def test_best_attempt_is_reported(monkeypatch, tmp_path):
|
||||
"""Обе попытки неполные: сообщение берёт ЛУЧШУЮ (1 потеря), не последнюю (2)."""
|
||||
archive = tmp_path / "a.rar"
|
||||
archive.write_bytes(b"rar")
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool in {"unrar", "unar"} else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: {"a.gge": 10, "b.gge": 10})
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
out = tmp_path / "a_extracted"
|
||||
out.mkdir(exist_ok=True)
|
||||
if cmd[0] == "unrar": # извлёк один из двух
|
||||
(out / "a.gge").write_bytes(b"x" * 10)
|
||||
self.returncode = 0
|
||||
|
||||
def poll(self):
|
||||
return 0
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah.extract_rarlike(archive, tmp_path)
|
||||
assert result["ok"] is False
|
||||
assert result["failed_files"] == ["b.gge"]
|
||||
assert result["extracted"] == 1
|
||||
|
||||
|
||||
def test_missing_files_accepts_empty_member(monkeypatch, tmp_path):
|
||||
"""Файл нулевого размера в самом архиве — легитимный, не «не извлечён»."""
|
||||
out = tmp_path / "out"
|
||||
out.mkdir()
|
||||
(out / "empty.gge").write_bytes(b"")
|
||||
assert ah._missing_files(out, {"empty.gge": 0}) == []
|
||||
(out / "empty.gge").write_bytes(b"x")
|
||||
assert ah._missing_files(out, {"empty.gge": 0}) == ["empty.gge"]
|
||||
|
||||
|
||||
def test_zero_exit_with_truncated_file_retries(monkeypatch, tmp_path):
|
||||
archive = tmp_path / "a.7z"
|
||||
archive.write_bytes(b"7z")
|
||||
out = tmp_path / "a_extracted"
|
||||
commands = []
|
||||
monkeypatch.setattr(ah.shutil, "which", lambda tool: f"/bin/{tool}" if tool in {"7z", "unar"} else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: {"a.gge": 10})
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
commands.append(cmd[0])
|
||||
(out / "a.gge").write_bytes(b"a" * (5 if cmd[0] == "7z" else 10))
|
||||
self.returncode = 0
|
||||
|
||||
def poll(self):
|
||||
return 0
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah.extract_rarlike(archive, tmp_path)
|
||||
assert commands == ["7z", "unar"]
|
||||
assert result["ok"] is True
|
||||
assert (out / "a.gge").stat().st_size == 10
|
||||
|
||||
|
||||
def test_7z_listing_without_lsar_detects_file_size(monkeypatch, tmp_path):
|
||||
if not ah.shutil.which("7z"):
|
||||
pytest.skip("7z не установлен")
|
||||
archive = tmp_path / "a.7z"
|
||||
(tmp_path / "a.gge").write_bytes(b"abc")
|
||||
subprocess.run(["7z", "a", str(archive), str(tmp_path / "a.gge")],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
actual_which = ah.shutil.which
|
||||
monkeypatch.setattr(ah.shutil, "which", lambda tool: None if tool == "lsar" else actual_which(tool))
|
||||
assert ah._archive_members(archive) == {"a.gge": 3}
|
||||
|
||||
|
||||
def test_not_rarlike_zip_ignored():
|
||||
r = ah.extract_rarlike(Path("foo.zip"), Path(tempfile.mkdtemp()))
|
||||
assert r["ok"] is False and r["error"] == "not-rarlike"
|
||||
|
||||
|
||||
def test_no_backend():
|
||||
orig = ah._backend
|
||||
ah._backend = lambda: None
|
||||
orig = ah._tools_for
|
||||
ah._tools_for = lambda entry: []
|
||||
try:
|
||||
r = ah.extract_rarlike(Path("foo.rar"), Path(tempfile.mkdtemp()))
|
||||
assert r["ok"] is False and r["error"] == "no-backend"
|
||||
finally:
|
||||
ah._backend = orig
|
||||
ah._tools_for = orig
|
||||
|
||||
|
||||
def test_extraction_wiring():
|
||||
orig_b, orig_popen = ah._backend, subprocess.Popen
|
||||
ah._backend = lambda: "unar"
|
||||
orig_t, orig_m, orig_popen = ah._tools_for, ah._archive_members, subprocess.Popen
|
||||
ah._tools_for = lambda entry: ["unar"]
|
||||
ah._archive_members = lambda entry: None
|
||||
|
||||
def fake_popen(cmd, **kw):
|
||||
assert "09.0200.rar" in cmd, f"распаковщику передан не тот архив: {cmd}"
|
||||
out = Path(cmd[cmd.index("-o") + 1])
|
||||
(out / "sub").mkdir(parents=True, exist_ok=True)
|
||||
(out / "sub" / "смета.xlsx").write_text("x")
|
||||
@@ -57,17 +320,181 @@ def test_extraction_wiring():
|
||||
assert r["files"] == 1, r
|
||||
assert (wd / "09.0200_extracted" / "sub" / "смета.xlsx").exists()
|
||||
finally:
|
||||
ah._backend, subprocess.Popen = orig_b, orig_popen
|
||||
ah._tools_for, ah._archive_members, subprocess.Popen = orig_t, orig_m, orig_popen
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import traceback
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
try:
|
||||
fn(); print(f" ok: {fn.__name__}")
|
||||
except Exception:
|
||||
failed += 1; print(f" FAIL: {fn.__name__}"); traceback.print_exc()
|
||||
print("ALL PASS" if not failed else f"{failed} FAILED")
|
||||
sys.exit(failed)
|
||||
|
||||
def test_best_count_kept_when_listing_unavailable(monkeypatch, tmp_path):
|
||||
"""Без листинга (verify=False) число извлечённых берётся по ЛУЧШЕЙ попытке."""
|
||||
archive = tmp_path / "a.rar"
|
||||
archive.write_bytes(b"rar")
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool in {"unrar", "unar"} else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: None)
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
out = tmp_path / "a_extracted"
|
||||
out.mkdir(exist_ok=True)
|
||||
n = 3 if cmd[0] == "unrar" else 1
|
||||
for i in range(n):
|
||||
(out / f"f{i}.gge").write_bytes(b"x")
|
||||
self.returncode = 1
|
||||
|
||||
def poll(self):
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return self.returncode
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah._run_unar(archive, tmp_path / "a_extracted", verify=False)
|
||||
assert result["ok"] is False
|
||||
assert result["extracted"] == 3
|
||||
|
||||
|
||||
def test_7z_listing_skips_symlink_field(monkeypatch, tmp_path):
|
||||
"""Симлинк из 7z-листинга не должен считаться «не извлечённым»: его удаляют."""
|
||||
listing = ("7-Zip\n----------\nPath = link\nSize = 10\nSymbolic Link = /etc/passwd\n\n"
|
||||
"Path = file.gge\nSize = 5\n")
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool == "7z" else None)
|
||||
|
||||
class R:
|
||||
returncode = 0
|
||||
stdout = listing
|
||||
stderr = ""
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "run", lambda *a, **k: R())
|
||||
assert ah._archive_members(tmp_path / "a.7z") == {"file.gge": 5}
|
||||
|
||||
|
||||
def test_empty_listing_is_unknown_not_complete(monkeypatch, tmp_path):
|
||||
"""Пустой ответ листера — «не знаем», а не «всё на месте»."""
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool == "lsar" else None)
|
||||
|
||||
class R:
|
||||
returncode = 0
|
||||
stdout = '{"lsarContents": []}'
|
||||
stderr = ""
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "run", lambda *a, **k: R())
|
||||
assert ah._archive_members(tmp_path / "a.rar") is None
|
||||
|
||||
|
||||
def test_dir_size_does_not_follow_symlinks(tmp_path):
|
||||
"""Размер цели симлинка не должен надувать распакованный объём до «бомбы»."""
|
||||
out = tmp_path / "out"
|
||||
out.mkdir()
|
||||
(out / "data.bin").write_bytes(b"x" * 100)
|
||||
(out / "link.bin").symlink_to(out / "data.bin")
|
||||
assert ah._dir_size(out) == 100
|
||||
|
||||
|
||||
def test_clear_out_does_not_raise(monkeypatch, tmp_path):
|
||||
"""Уборка не роняет распаковку: все отказы возвращаются словарём."""
|
||||
out = tmp_path / "out"
|
||||
out.mkdir()
|
||||
(out / "f").write_bytes(b"x")
|
||||
monkeypatch.setattr(ah.shutil, "rmtree",
|
||||
lambda *a, **k: (_ for _ in ()).throw(OSError("busy")))
|
||||
ah._clear_out(out) # не бросает
|
||||
|
||||
|
||||
def test_split_no_backend_text_names_real_cause(monkeypatch, tmp_path):
|
||||
"""Нет распаковщика — совет «проверьте тома» уводит не туда."""
|
||||
import db
|
||||
messages = []
|
||||
monkeypatch.setattr(ah, "extract_split", lambda path, work: {
|
||||
"notify": True, "entry": "v.zip", "error": "no-backend"})
|
||||
monkeypatch.setattr(db, "save_message", lambda *args: messages.append(args))
|
||||
monkeypatch.setattr(db, "log_action", lambda *args: None)
|
||||
|
||||
class InlineThread:
|
||||
def __init__(self, target, **kwargs):
|
||||
self.target = target
|
||||
|
||||
def start(self):
|
||||
self.target()
|
||||
|
||||
monkeypatch.setattr(ah.threading, "Thread", InlineThread)
|
||||
ah.extract_split_async(tmp_path / "v.zip", tmp_path, "user", "tab")
|
||||
text = messages[0][3]
|
||||
assert "распаковщик недоступен" in text
|
||||
assert "Проверьте все тома" not in text
|
||||
|
||||
|
||||
def test_backend_error_with_matching_sizes_is_not_success(monkeypatch, tmp_path):
|
||||
"""Ошибка распаковщика (код 2) — не успех, даже если размеры совпали: CRC мог не сойтись."""
|
||||
archive = tmp_path / "a.rar"
|
||||
archive.write_bytes(b"rar")
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool == "unrar" else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: {"a.gge": 10})
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
(tmp_path / "a_extracted").mkdir(exist_ok=True)
|
||||
(tmp_path / "a_extracted" / "a.gge").write_bytes(b"x" * 10)
|
||||
self.returncode = 2
|
||||
|
||||
def poll(self):
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return self.returncode
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah.extract_rarlike(archive, tmp_path)
|
||||
assert result["ok"] is False
|
||||
|
||||
|
||||
def test_dirty_folder_blocks_success(monkeypatch, tmp_path):
|
||||
"""Не смогли снести папку прошлой загрузки — не распаковываем поверх старых файлов."""
|
||||
archive = tmp_path / "a.rar"
|
||||
archive.write_bytes(b"rar")
|
||||
(tmp_path / "a_extracted").mkdir()
|
||||
(tmp_path / "a_extracted" / "old.gge").write_bytes(b"old")
|
||||
monkeypatch.setattr(ah.shutil, "which",
|
||||
lambda tool: f"/bin/{tool}" if tool == "unrar" else None)
|
||||
monkeypatch.setattr(ah, "_archive_members", lambda entry: {"a.gge": 10})
|
||||
monkeypatch.setattr(ah.shutil, "rmtree", lambda *a, **k: None) # уборка «не удалась»
|
||||
|
||||
class Proc:
|
||||
def __init__(self, cmd, **kwargs):
|
||||
(tmp_path / "a_extracted" / "a.gge").write_bytes(b"x" * 10)
|
||||
self.returncode = 0
|
||||
|
||||
def poll(self):
|
||||
return self.returncode
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return self.returncode
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(ah.subprocess, "Popen", Proc)
|
||||
result = ah.extract_rarlike(archive, tmp_path)
|
||||
assert result["ok"] is False and result["error"] == "cleanup-failed"
|
||||
|
||||
|
||||
def test_success_message_uses_singular(monkeypatch, tmp_path):
|
||||
"""«1 файл», а не «1 файлов»: текст читает человек."""
|
||||
messages, _ = _run_async(monkeypatch, ah, tmp_path, {
|
||||
"ok": True, "files": 1, "target": str(tmp_path / "x_extracted")})
|
||||
assert messages[0][3] == "Архив сметы.rar распакован (1 файл) в папку x_extracted/"
|
||||
|
||||
|
||||
def test_rar_part_naming_recognized_as_set(tmp_path):
|
||||
"""WinRAR режет набор как name.part1.rar, name.part2.rar — это тот же набор."""
|
||||
(tmp_path / "name.part1.rar").write_bytes(b"p1")
|
||||
(tmp_path / "name.part2.rar").write_bytes(b"p2")
|
||||
assert ah._split_entry(tmp_path / "name.part2.rar") == (tmp_path / "name.part1.rar", "name")
|
||||
|
||||
+84
-13
@@ -86,7 +86,7 @@ def _realistic_unar(required):
|
||||
"""Мок _run_unar под реальное поведение unar: dir создаётся ДО запуска (как в
|
||||
_run_unar), но успех — ТОЛЬКО если все `required` тома лежат рядом с entry;
|
||||
иначе {ok:False} и пустой out (как unar rc!=0, files=0)."""
|
||||
def fake(entry: Path, out: Path):
|
||||
def fake(entry: Path, out: Path, verify=True):
|
||||
out.mkdir(parents=True, exist_ok=True) # как реальный _run_unar
|
||||
parent = entry.parent
|
||||
if not all((parent / v).exists() for v in required):
|
||||
@@ -179,7 +179,7 @@ def test_incomplete_never_false_success():
|
||||
def test_split_skips_when_entry_missing():
|
||||
# том без entry-тома → skip:incomplete, unar не зовём
|
||||
orig = ah._run_unar
|
||||
ah._run_unar = lambda e, o: (_ for _ in ()).throw(AssertionError("unar не должен вызываться"))
|
||||
ah._run_unar = lambda e, o, verify=True: (_ for _ in ()).throw(AssertionError("unar не должен вызываться"))
|
||||
try:
|
||||
wd = Path(tempfile.mkdtemp())
|
||||
(wd / "x.z02").write_bytes(b"vol") # .zip рядом нет
|
||||
@@ -188,14 +188,85 @@ def test_split_skips_when_entry_missing():
|
||||
ah._run_unar = orig
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import traceback
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
try:
|
||||
fn(); print(f" ok: {fn.__name__}")
|
||||
except Exception:
|
||||
failed += 1; print(f" FAIL: {fn.__name__}"); traceback.print_exc()
|
||||
print("ALL PASS" if not failed else f"{failed} FAILED")
|
||||
sys.exit(failed)
|
||||
def test_reuploaded_volume_invalidates_done_marker(tmp_path, monkeypatch):
|
||||
for name in ("v.z01", "v.zip"):
|
||||
(tmp_path / name).write_bytes(b"old")
|
||||
calls = []
|
||||
|
||||
def fake(entry, out, verify=True):
|
||||
calls.append(entry)
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / "a.gge").write_bytes(b"new")
|
||||
return {"ok": True, "files": 1, "target": str(out)}
|
||||
|
||||
monkeypatch.setattr(ah, "_run_unar", fake)
|
||||
assert ah.extract_split(tmp_path / "v.zip", tmp_path)["ok"]
|
||||
assert ah.extract_split(tmp_path / "v.zip", tmp_path)["skip"] == "already"
|
||||
(tmp_path / "v.z01").write_bytes(b"new")
|
||||
assert ah.extract_split(tmp_path / "v.z01", tmp_path)["ok"]
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_split_failure_reports_files_and_next_volume_can_retry(tmp_path, monkeypatch):
|
||||
import db
|
||||
|
||||
(tmp_path / "v.z01").write_bytes(b"part")
|
||||
(tmp_path / "v.zip").write_bytes(b"end")
|
||||
messages = []
|
||||
monkeypatch.setattr(db, "save_message", lambda *args: messages.append(args))
|
||||
monkeypatch.setattr(db, "log_action", lambda *args: None) # иначе пишем в рабочую базу
|
||||
monkeypatch.setattr(ah, "_run_unar", lambda entry, out, verify=True: {
|
||||
"ok": False, "error": "exit-1", "failed_files": ["A.gge"]})
|
||||
|
||||
class InlineThread:
|
||||
def __init__(self, target, **kwargs):
|
||||
self.target = target
|
||||
|
||||
def start(self):
|
||||
self.target()
|
||||
|
||||
monkeypatch.setattr(ah.threading, "Thread", InlineThread)
|
||||
ah.extract_split_async(tmp_path / "v.zip", tmp_path, "user", "tab")
|
||||
assert messages == [("user", "tab", "system",
|
||||
"Пока не удалось полностью распаковать многотомный архив "
|
||||
"v.zip: не извлеклось 1 файл (A.gge). "
|
||||
"Результат распаковки не готов к работе. "
|
||||
"Проверьте все тома; после загрузки следующего "
|
||||
"тома попытка повторится автоматически.")]
|
||||
assert not (tmp_path / ".v.extracted.done").exists()
|
||||
# Следующая загрузка тома должна ПОВТОРИТЬ попытку и добиться успеха.
|
||||
monkeypatch.setattr(ah, "_run_unar", lambda entry, out, verify=True: {
|
||||
"ok": True, "files": 1, "target": str(out)})
|
||||
ah.extract_split_async(tmp_path / "v.z01", tmp_path, "user", "tab")
|
||||
assert (tmp_path / ".v.extracted.done").exists()
|
||||
assert messages[-1][3].startswith("Многотомный архив")
|
||||
|
||||
|
||||
def test_rar_terminal_with_r00_uses_split_marker(tmp_path, monkeypatch):
|
||||
(tmp_path / "v.r00").write_bytes(b"part")
|
||||
(tmp_path / "v.rar").write_bytes(b"end")
|
||||
seen = []
|
||||
monkeypatch.setattr(ah, "_run_unar", lambda entry, out, verify=True: (
|
||||
seen.append(entry), {"ok": True, "files": 1, "target": str(out)})[1])
|
||||
result = ah.extract_split(tmp_path / "v.rar", tmp_path)
|
||||
assert result["ok"] is True
|
||||
assert seen and seen[0].name == "v.rar" # терминал .rar, не том .r00
|
||||
assert (tmp_path / ".v.extracted.done").exists()
|
||||
|
||||
|
||||
|
||||
def test_split_does_not_verify_against_volume_listing(tmp_path, monkeypatch):
|
||||
"""Листинг первого тома неполон: сверка по нему объявила бы целый набор битым."""
|
||||
(tmp_path / "v.z01").write_bytes(b"part")
|
||||
(tmp_path / "v.zip").write_bytes(b"end")
|
||||
seen = {}
|
||||
|
||||
def fake(entry, out, verify=True):
|
||||
seen["verify"] = verify
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / "a.gge").write_bytes(b"x")
|
||||
return {"ok": True, "files": 1, "target": str(out)}
|
||||
|
||||
monkeypatch.setattr(ah, "_run_unar", fake)
|
||||
assert ah.extract_split(tmp_path / "v.zip", tmp_path)["ok"]
|
||||
assert seen["verify"] is False
|
||||
|
||||
Reference in New Issue
Block a user