D29: объект путей AppPaths с базой данных из CF_DATA_DIR

infrastructure/cli/paths.py: AppPaths(data_dir, exports_dir) с model_path;
from_env() читает CF_DATA_DIR (дефолт ./data — поведение не меняется) на
каждую команду. CF_DATA_DIR переопределяет только данные модели: экспорты
остаются в ./exports относительно CWD. load_model/save_model, cf init и
cf import-xlsx идут через объект; дефолт cf export-xlsx прежний.
Тесты: дефолтные пути, переопределение, init/config/info/import/export.
This commit is contained in:
oqyude committed 2026-10-25 16:49:33 +03:00
1 parent f41fc19cc9
commit 6470978693
6 files changed
+153 -17

No files matched your search

+16 -2
View File
@@ -61,6 +61,19 @@ CF_LANG=ru cf info
Команды верхнего уровня: `init`, `forecast`, `scenario`, `whatif`, `compare`,
`analyze`, `info`, `import-xlsx`, `export-xlsx` и под-приложение `config`.
### Переменные окружения
| Переменная | По умолчанию | Назначение |
|---|---|---|
| `CF_DATA_DIR` | `./data` | Каталог с `model.json` (данные модели). Экспорты остаются в `./exports` относительно CWD — переменная переопределяет только данные. |
| `CF_LANG` | `ru` | Язык интерфейса. Английских переводов нет: `CF_LANG=en` откатывается на `ru`. |
```bash
# Модель хранится вне рабочего каталога
CF_DATA_DIR=/tmp/cf-data cf init
CF_DATA_DIR=/tmp/cf-data cf info
```
### Команды `cf config`
Редактирование модели — 19 подкоманд:
@@ -144,7 +157,7 @@ cashflow-forecast/
│ ├── cli/ # Typer CLI (cf ...)
│ │ ├── app.py # Entry point
│ │ ├── commands/ # 10 файлов команд + config sub-typer
│ │ ├── paths.py # DATA_DIR, MODEL_PATH, EXPORTS_DIR
│ │ ├── paths.py # AppPaths — пути (CF_DATA_DIR)
│ │ ├── services.py # Composition root + helpers
│ │ └── i18n.py # ru-переводы (словарь "en" пуст, откат на ru)
│ ├── ai/ # AI-ассистент (заглушка)
@@ -154,7 +167,7 @@ cashflow-forecast/
│ ├── json_file_repository.py
│ └── excel_repository.py
│
├── tests/ # pytest, 160 тестов
├── tests/ # pytest, 229 тестов
│ ├── conftest.py
│ ├── test_model.py
│ ├── test_forecast.py
@@ -165,6 +178,7 @@ cashflow-forecast/
│ ├── test_cli_contract.py # Инвариант публичной поверхности CLI
│ ├── test_excel_sync.py # Тесты ExcelRepository
│ ├── test_i18n.py
│ ├── test_paths.py # Пути и CF_DATA_DIR
│ └── test_repositories.py # Тесты репозиториев
│
├── data/ # JSON-модели (runtime, версионируется SCHEMA_VERSION=1)
+4 -4
View File
@@ -3,16 +3,16 @@
import typer
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import EXPORTS_DIR
from infrastructure.cli.paths import AppPaths
from infrastructure.cli.services import console, load_model
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
_repo = ExcelRepository()
# Значение по умолчанию остаётся ровно "exports/forecast.xlsx" (строка в help
# и в аргументе CLI не меняется) — собирается из EXPORTS_DIR во избежание
# дублирования литерала пути.
DEFAULT_EXPORT_PATH: str = str(EXPORTS_DIR / "forecast.xlsx")
# и в аргументе CLI не меняется) — собирается из `AppPaths.exports_dir` во
# избежание дублирования литерала пути. `CF_DATA_DIR` на экспорты не влияет.
DEFAULT_EXPORT_PATH: str = str(AppPaths.from_env().exports_dir / "forecast.xlsx")
def export_xlsx(
+3 -2
View File
@@ -2,12 +2,13 @@
from domain import FinancialModel
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import MODEL_PATH
from infrastructure.cli.paths import AppPaths
from infrastructure.cli.services import console, save_model
def init() -> None:
"""Создать пустую финансовую модель"""
model = FinancialModel()
model_path = AppPaths.from_env().model_path
save_model(model)
console.print(t("cmd.init.ok", path=str(MODEL_PATH)))
console.print(t("cmd.init.ok", path=str(model_path)))
+36 -5
View File
@@ -1,9 +1,40 @@
"""Пути к данным и экспортам."""
"""Пути к данным и экспортам.
D29: единственный объект `AppPaths` — источник путей для CLI. База данных
берётся из переменной окружения `CF_DATA_DIR` (по умолчанию `./data`, то есть
прежнее поведение). `CF_DATA_DIR` переопределяет ТОЛЬКО данные модели:
каталог экспортов остаётся относительным CWD (`./exports`), потому что
экспорт — результат команды пользователя, а не состояние приложения.
"""
import os
from dataclasses import dataclass
from pathlib import Path
DATA_DIR: Path = Path("data")
MODEL_PATH: Path = DATA_DIR / "model.json"
DATA_DIR_ENV = "CF_DATA_DIR"
DEFAULT_DATA_DIR = Path("data")
DEFAULT_EXPORTS_DIR = Path("exports")
# Каталог для экспортируемых .xlsx (по умолчанию — "./exports" относительно CWD).
EXPORTS_DIR: Path = Path("exports")
@dataclass(frozen=True)
class AppPaths:
"""Пути приложения. По умолчанию совпадают с поведением до D29."""
data_dir: Path = DEFAULT_DATA_DIR
exports_dir: Path = DEFAULT_EXPORTS_DIR
@property
def model_path(self) -> Path:
"""Файл состояния модели внутри `data_dir`."""
return self.data_dir / "model.json"
@classmethod
def from_env(cls) -> "AppPaths":
"""Собрать пути из окружения.
Вызывается на каждую команду, а не один раз при импорте: так
`CF_DATA_DIR` действует и на CLI, запущенный из теста/процесса, где
переменная выставлена после импорта модуля.
"""
data_dir = os.environ.get(DATA_DIR_ENV)
return cls(data_dir=Path(data_dir) if data_dir else DEFAULT_DATA_DIR)
+5 -4
View File
@@ -14,7 +14,7 @@ from application.scenarios import ScenarioService
from domain import CurrencyConverter, FinancialModel
from infrastructure.ai.assistant import AssistantService
from infrastructure.cli.i18n import t
from infrastructure.cli.paths import MODEL_PATH
from infrastructure.cli.paths import AppPaths
from infrastructure.repositories import JsonFileRepository
console = Console()
@@ -38,13 +38,14 @@ def fail_validation(exc: ValidationError) -> NoReturn:
def load_model() -> FinancialModel:
if MODEL_PATH.exists():
return _json_repo.load(MODEL_PATH)
model_path = AppPaths.from_env().model_path
if model_path.exists():
return _json_repo.load(model_path)
return FinancialModel()
def save_model(model: FinancialModel) -> None:
_json_repo.save(model, MODEL_PATH)
_json_repo.save(model, AppPaths.from_env().model_path)
def build_services(
+89
View File
@@ -0,0 +1,89 @@
"""D29: объект путей и переопределение базы данных через CF_DATA_DIR."""
from pathlib import Path
from typer.testing import CliRunner
from domain import FinancialModel
from infrastructure.cli.app import app
from infrastructure.cli.paths import AppPaths
from infrastructure.repositories import ExcelRepository
runner = CliRunner()
class TestAppPaths:
def test_defaults_are_unchanged(self, monkeypatch):
monkeypatch.delenv("CF_DATA_DIR", raising=False)
paths = AppPaths.from_env()
assert paths.data_dir == Path("data")
assert paths.model_path == Path("data/model.json")
assert paths.exports_dir == Path("exports")
def test_data_dir_env_overrides_only_data(self, monkeypatch, tmp_path: Path):
custom = tmp_path / "custom-data"
monkeypatch.setenv("CF_DATA_DIR", str(custom))
paths = AppPaths.from_env()
assert paths.data_dir == custom
assert paths.model_path == custom / "model.json"
# Экспорты остаются относительно CWD и от CF_DATA_DIR не зависят.
assert paths.exports_dir == Path("exports")
def test_env_is_read_per_call_not_at_import(self, monkeypatch, tmp_path: Path):
custom = tmp_path / "late-env"
monkeypatch.setenv("CF_DATA_DIR", str(custom))
# Модуль уже импортирован выше — значение всё равно подхватилось.
assert AppPaths.from_env().model_path == custom / "model.json"
class TestDataDirEnvInCli:
def test_init_writes_model_into_cf_data_dir(self, isolated_cwd: Path, monkeypatch, tmp_path: Path):
custom = tmp_path / "cf-data"
monkeypatch.setenv("CF_DATA_DIR", str(custom))
result = runner.invoke(app, ["init"])
assert result.exit_code == 0
assert (custom / "model.json").exists()
assert not (isolated_cwd / "data" / "model.json").exists()
assert "Пустая модель создана" in result.stdout
def test_config_and_info_read_and_write_cf_data_dir(self, isolated_cwd: Path, monkeypatch, tmp_path: Path):
custom = tmp_path / "cf-data"
monkeypatch.setenv("CF_DATA_DIR", str(custom))
assert runner.invoke(app, ["init"]).exit_code == 0
add = runner.invoke(app, ["config", "account-add", "--name", "Из CF_DATA_DIR", "--balance", "1000"])
assert add.exit_code == 0
info = runner.invoke(app, ["info"])
assert info.exit_code == 0
assert "Из CF_DATA_DIR" in info.stdout
assert (custom / "model.json").exists()
def test_export_xlsx_default_path_ignores_cf_data_dir(self, isolated_cwd: Path, monkeypatch, tmp_path: Path):
monkeypatch.setenv("CF_DATA_DIR", str(tmp_path / "cf-data"))
runner.invoke(app, ["init"])
result = runner.invoke(app, ["export-xlsx"])
assert result.exit_code == 0
assert (isolated_cwd / "exports" / "forecast.xlsx").exists()
def test_import_xlsx_saves_model_into_cf_data_dir(self, isolated_cwd: Path, monkeypatch, tmp_path: Path):
source = tmp_path / "source.xlsx"
ExcelRepository().save(FinancialModel(base_currency="EUR"), source)
custom = tmp_path / "cf-data"
monkeypatch.setenv("CF_DATA_DIR", str(custom))
result = runner.invoke(app, ["import-xlsx", str(source)])
assert result.exit_code == 0
assert (custom / "model.json").exists()
assert not (isolated_cwd / "data" / "model.json").exists()