D19: cf export-xlsx создаёт отсутствующий каталог, ошибка — доменная
- infrastructure/repositories/excel_repository.py: ExcelRepository.save() создаёт
родительский каталог файла (parents=True, exist_ok=True) перед сохранением;
ошибки создания каталога и записи файла оборачиваются в ExcelRepositoryError
с понятным сообщением вместо сырого FileNotFoundError из openpyxl.
- tests/test_excel_sync.py: +3 теста (создание каталога, экспорт в bare
filename, доменная ошибка когда родительский путь занят файлом).
- tests/test_cli.py: +3 теста (экспорт в несуществующий каталог, дефолтный
exports/forecast.xlsx, понятная ошибка без traceback).
Было → стало:
cf export-xlsx /tmp/nifodea-check/out.xlsx FileNotFoundError (traceback)
→ «Модель экспортирована в
/tmp/nifodea-check/out.xlsx», код 0
cf export-xlsx (каталога exports/ нет) FileNotFoundError (traceback)
→ каталог создан, файл записан, код 0
каталог создать нельзя (путь занят файлом) FileNotFoundError (traceback)
→ «Ошибка экспорта: Не удалось создать
каталог …», код 1, без traceback
This commit is contained in:
1 parent
c702818d43
commit
e992dde07d
3 files changed
+81
No files matched your search
@@ -94,6 +94,8 @@ class ExcelRepository(ModelRepository):
|
||||
|
||||
def save(self, model: FinancialModel, path: str | Path) -> None:
|
||||
p = Path(path)
|
||||
self._ensure_parent_dir(p)
|
||||
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
|
||||
@@ -121,7 +123,23 @@ class ExcelRepository(ModelRepository):
|
||||
ws_info.append(["Property", "Value"])
|
||||
ws_info.append(["base_currency", model.base_currency])
|
||||
|
||||
try:
|
||||
wb.save(p)
|
||||
except OSError as e:
|
||||
raise ExcelRepositoryError(f"Не удалось сохранить файл {p}: {e}") from e
|
||||
|
||||
@staticmethod
|
||||
def _ensure_parent_dir(p: Path) -> None:
|
||||
"""Создать родительский каталог файла, если его нет (D19).
|
||||
|
||||
Раньше экспорт в несуществующий каталог падал с сырым
|
||||
`FileNotFoundError` из openpyxl — без понятного сообщения.
|
||||
"""
|
||||
parent = p.parent
|
||||
try:
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise ExcelRepositoryError(f"Не удалось создать каталог {parent}: {e}") from e
|
||||
|
||||
def _add_to_model(self, model: FinancialModel, sheet_name: str, data: dict, cls) -> None:
|
||||
try:
|
||||
|
||||
@@ -181,6 +181,30 @@ class TestCli:
|
||||
assert "Акции" in result.stdout
|
||||
|
||||
|
||||
class TestExportXlsx:
|
||||
"""D19: `cf export-xlsx` в несуществующий каталог создаёт каталог."""
|
||||
|
||||
def test_export_creates_missing_directory(self, tmp_path: Path):
|
||||
target = tmp_path / "missing" / "out.xlsx"
|
||||
result = runner.invoke(app, ["export-xlsx", str(target)])
|
||||
assert result.exit_code == 0
|
||||
assert target.exists()
|
||||
assert "Traceback" not in result.stdout
|
||||
|
||||
def test_export_default_path_creates_exports_dir(self, tmp_path: Path):
|
||||
result = runner.invoke(app, ["export-xlsx"])
|
||||
assert result.exit_code == 0
|
||||
assert (tmp_path / "exports" / "forecast.xlsx").exists()
|
||||
|
||||
def test_export_to_unwritable_location_reports_error(self, tmp_path: Path):
|
||||
blocker = tmp_path / "blocker"
|
||||
blocker.write_text("not a directory", encoding="utf-8")
|
||||
result = runner.invoke(app, ["export-xlsx", str(blocker / "out.xlsx")])
|
||||
assert result.exit_code == 1
|
||||
assert "Ошибка экспорта" in result.stdout
|
||||
assert "Traceback" not in result.stdout
|
||||
|
||||
|
||||
class TestValidationErrors:
|
||||
"""D17: ошибка валидации — понятное сообщение и код 1, без traceback."""
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from domain import FinancialModel
|
||||
@@ -56,6 +57,44 @@ class TestExcelRepository:
|
||||
assert p.exists()
|
||||
|
||||
|
||||
class TestExportCreatesParentDir:
|
||||
"""D19: экспорт в несуществующий каталог создаёт каталог и пишет файл.
|
||||
|
||||
Раньше `cf export-xlsx exports/report.xlsx` в каталоге без `exports/`
|
||||
падал с сырым `FileNotFoundError` из openpyxl.
|
||||
"""
|
||||
|
||||
def test_save_creates_missing_parent_dir(self, sample_model, tmp_path: Path):
|
||||
repo = ExcelRepository()
|
||||
target = tmp_path / "nested" / "deeper" / "out.xlsx"
|
||||
assert not target.parent.exists()
|
||||
|
||||
repo.save(sample_model, target)
|
||||
|
||||
assert target.parent.is_dir()
|
||||
assert target.exists()
|
||||
|
||||
def test_save_to_bare_filename_in_cwd(self, sample_model, tmp_path: Path, monkeypatch):
|
||||
repo = ExcelRepository()
|
||||
monkeypatch.chdir(tmp_path)
|
||||
repo.save(sample_model, "out.xlsx")
|
||||
assert (tmp_path / "out.xlsx").exists()
|
||||
|
||||
def test_save_reports_unreadable_parent_as_domain_error(self, sample_model, tmp_path: Path):
|
||||
# Родительский путь занят файлом — каталог создать нельзя.
|
||||
blocker = tmp_path / "blocker"
|
||||
blocker.write_text("not a directory", encoding="utf-8")
|
||||
|
||||
repo = ExcelRepository()
|
||||
with pytest.raises(ExcelRepositoryError) as exc_info:
|
||||
repo.save(sample_model, blocker / "out.xlsx")
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "Не удалось создать каталог" in message
|
||||
assert "blocker" in message
|
||||
assert not isinstance(exc_info.value, FileNotFoundError)
|
||||
|
||||
|
||||
class TestExcelRoundTripByValues:
|
||||
"""Round-trip .xlsx ПО ЗНАЧЕНИЯМ, а не только по количеству строк (D11).
|
||||
|
||||
|
||||
Reference in new issue
Block a user