D10: изолировать ФС в тестах — tmp_path + monkeypatch.chdir
- tests/conftest.py: автофикстура `isolated_cwd` переводит CWD во временный каталог на время каждого теста; добавлена session-фикстура `repo_root` - tests/test_cli.py: удалён `_cleanup()` (он удалял отслеживаемый git файл data/model.json) и импорт MODEL_PATH — 13 вызовов - +2 регрессионных теста: CLI пишет модель в tmp, а отслеживаемый data/model.json в дереве репозитория остаётся байт-в-байт прежним Проверено: `python -m pytest -q` больше не модифицирует data/model.json.
This commit is contained in:
1 parent
b15533f275
commit
bf764723e4
2 files changed
+42
-19
No files matched your search
@@ -1,3 +1,4 @@
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
@@ -14,6 +15,26 @@ from domain import (
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def repo_root() -> Path:
|
||||
"""Корень репозитория (для проверок, что тесты не пишут в дерево)."""
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Изоляция ФС: тесты не пишут в рабочее дерево репозитория.
|
||||
|
||||
CLI работает с относительными путями (`data/model.json`, `exports/...`),
|
||||
поэтому достаточно перевести CWD во временный каталог — любой файл,
|
||||
созданный командой, окажется в tmp_path, а не в дереве репозитория.
|
||||
До D10 тесты писали в `./data/model.json` и `_cleanup()` удалял
|
||||
отслеживаемый git файл.
|
||||
"""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_model() -> FinancialModel:
|
||||
acc_id = uuid4()
|
||||
|
||||
+21
-19
@@ -1,31 +1,24 @@
|
||||
from pathlib import Path
|
||||
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from infrastructure.cli.app import app
|
||||
from infrastructure.cli.paths import MODEL_PATH
|
||||
|
||||
runner = CliRunner()
|
||||
|
||||
|
||||
def _cleanup():
|
||||
if MODEL_PATH.exists():
|
||||
MODEL_PATH.unlink()
|
||||
|
||||
|
||||
class TestCli:
|
||||
def test_init(self):
|
||||
_cleanup()
|
||||
result = runner.invoke(app, ["init"])
|
||||
assert result.exit_code == 0
|
||||
assert "Пустая модель" in result.stdout
|
||||
|
||||
def test_forecast_after_init(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
result = runner.invoke(app, ["forecast", "--months", "3"])
|
||||
assert result.exit_code == 0
|
||||
|
||||
def test_forecast_with_currency(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
result = runner.invoke(app, ["forecast", "--months", "3", "--currency", "USD"])
|
||||
assert result.exit_code == 0
|
||||
@@ -40,14 +33,12 @@ class TestCli:
|
||||
assert result.exit_code == 0
|
||||
|
||||
def test_info_empty(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
result = runner.invoke(app, ["info"])
|
||||
assert result.exit_code == 0
|
||||
assert "Базовая валюта" in result.stdout
|
||||
|
||||
def test_config_base_currency_set(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
result = runner.invoke(app, ["config", "base-currency", "EUR"])
|
||||
assert result.exit_code == 0
|
||||
@@ -57,14 +48,12 @@ class TestCli:
|
||||
assert "EUR" in info.stdout
|
||||
|
||||
def test_config_base_currency_show(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
result = runner.invoke(app, ["config", "base-currency"])
|
||||
assert result.exit_code == 0
|
||||
assert "RUB" in result.stdout
|
||||
|
||||
def test_config_account_crud(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
args = ["config", "account-add", "--name", "Тестовый", "--balance", "1000"]
|
||||
@@ -82,7 +71,6 @@ class TestCli:
|
||||
assert "Тестовый" not in lst2.stdout
|
||||
|
||||
def test_config_transaction_crud(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
runner.invoke(app, ["config", "account-add", "--name", "Счёт", "--balance", "0"])
|
||||
|
||||
@@ -108,7 +96,6 @@ class TestCli:
|
||||
assert "Зарплата" in lst.stdout
|
||||
|
||||
def test_config_asset_crud(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
add = runner.invoke(
|
||||
@@ -131,7 +118,6 @@ class TestCli:
|
||||
assert "Квартира" in lst.stdout
|
||||
|
||||
def test_config_liability_crud(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
add = runner.invoke(
|
||||
@@ -153,7 +139,6 @@ class TestCli:
|
||||
assert "Кредит" in add.stdout
|
||||
|
||||
def test_config_recurring_crud(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
add = runner.invoke(
|
||||
@@ -175,7 +160,6 @@ class TestCli:
|
||||
assert "аренда" in lst.stdout
|
||||
|
||||
def test_config_rate_crud(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
set_r = runner.invoke(app, ["config", "rate-set", "EUR", "RUB", "90"])
|
||||
@@ -186,7 +170,6 @@ class TestCli:
|
||||
assert "90" in lst.stdout
|
||||
|
||||
def test_info_with_data(self):
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
acc_args = ["config", "account-add", "--name", "Основной", "--balance", "50000"]
|
||||
runner.invoke(app, acc_args)
|
||||
@@ -196,3 +179,22 @@ class TestCli:
|
||||
result = runner.invoke(app, ["info"])
|
||||
assert "Основной" in result.stdout
|
||||
assert "Акции" in result.stdout
|
||||
|
||||
|
||||
class TestFilesystemIsolation:
|
||||
"""Регрессии D10: CLI-тесты не пишут в дерево репозитория."""
|
||||
|
||||
def test_cli_writes_model_into_tmp_cwd(self, isolated_cwd: Path):
|
||||
result = runner.invoke(app, ["init"])
|
||||
assert result.exit_code == 0
|
||||
assert (isolated_cwd / "data" / "model.json").exists()
|
||||
|
||||
def test_cli_does_not_touch_tracked_repo_files(self, repo_root: Path, isolated_cwd: Path):
|
||||
tracked = repo_root / "data" / "model.json"
|
||||
before = tracked.read_bytes() if tracked.exists() else None
|
||||
|
||||
result = runner.invoke(app, ["init"])
|
||||
assert result.exit_code == 0
|
||||
|
||||
after = tracked.read_bytes() if tracked.exists() else None
|
||||
assert before == after, "CLI-тест изменил отслеживаемый data/model.json в дереве репозитория"
|
||||
Reference in new issue
Block a user