fix(контракт): пустой DB_PATH, каталог вместо файла и точный разбор [DONE] (R-05, R-06)

Проверка среды отвергает пустой DB_PATH и DATA_DIR-файл; в проверке шлюза конец потока
определяется телом data, а не подстрокой в тексте.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
anor
2026-11-18 19:31:15 +10:00
co-authored by Claude Code
parent b5f585c7ce
commit 424f9ee66f
3 changed files with 34 additions and 5 deletions
+6
View File
@@ -41,7 +41,11 @@ def _inside_prod(path: Path) -> bool:
def check_db_path(db_path: str) -> None:
"""База тестовой среды: окончание `_test.db` и не ссылка на боевую базу."""
if not (db_path or "").strip():
raise RuntimeError("DB_PATH пуст: тестовая среда требует путь к базе")
path = Path(db_path)
if path.is_dir():
raise RuntimeError(f"DB_PATH указывает на каталог ({db_path!r}), а нужен файл базы")
if not path.name.endswith("_test.db"):
raise RuntimeError(
f"Тестовая среда требует базу с окончанием _test.db, а указана {path.name!r}")
@@ -84,6 +88,8 @@ def enforce() -> None:
data_dir = Path(raw)
if not data_dir.is_absolute():
raise RuntimeError(f"DATA_DIR тестовой среды должен быть абсолютным, а указан {raw!r}")
if data_dir.is_file():
raise RuntimeError(f"DATA_DIR указывает на файл ({data_dir}), а нужен каталог")
if _inside_prod(data_dir):
raise RuntimeError(
f"DATA_DIR указывает на боевой каталог ({data_dir}): задайте отдельный каталог")
+27 -4
View File
@@ -126,7 +126,7 @@ def test_check_runs_before_database_connect(monkeypatch, tmp_path):
_load(monkeypatch, CONTRACT_ENV="test", DB_PATH=str(tmp_path / "prod.db"),
DATA_DIR=str(tmp_path / "data"))
import sys as _sys
_sys.modules.pop("db", None) # чистый импорт: проверка стоит в самом модуле
_sys.modules.pop("db", None) # enforcement вызывается явно в db.py, кэш модуля не влияет
with pytest.raises(RuntimeError) as err:
import db # noqa: F401 — импорт обязан упасть до соединения
assert "_test.db" in str(err.value)
@@ -137,7 +137,7 @@ def test_migration_script_refuses_prod_database(monkeypatch, tmp_path):
prod = tmp_path / "prod.db"
prod.write_bytes(b"")
import subprocess
env = dict(os.environ, CONTRACT_ENV="test", DB_PATH="/tmp/whatever_test.db")
env = dict(os.environ, CONTRACT_ENV="test", DB_PATH=str(tmp_path / "env_test.db"))
r = subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "migrate_admin_v2.py"),
"--db", str(prod), "--dry-run"],
capture_output=True, text=True, env=env)
@@ -148,9 +148,14 @@ def test_migration_script_refuses_prod_database(monkeypatch, tmp_path):
def test_migration_script_allows_test_database(monkeypatch, tmp_path):
db = tmp_path / "copy_test.db"
import sqlite3
sqlite3.connect(db).execute("CREATE TABLE t(x)").connection.commit()
con = sqlite3.connect(db)
try:
con.execute("CREATE TABLE t(x)")
con.commit()
finally:
con.close()
import subprocess
env = dict(os.environ, CONTRACT_ENV="test", DB_PATH="/tmp/whatever_test.db")
env = dict(os.environ, CONTRACT_ENV="test", DB_PATH=str(tmp_path / "env_test.db"))
r = subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "migrate_admin_v2.py"),
"--db", str(db), "--dry-run"],
capture_output=True, text=True, env=env)
@@ -169,3 +174,21 @@ def test_hard_link_to_prod_database_refused(monkeypatch, tmp_path):
with pytest.raises(RuntimeError) as err:
module.enforce()
assert "жёсткая ссылка" in str(err.value)
def test_empty_db_path_refused(monkeypatch, tmp_path):
module = _load(monkeypatch, CONTRACT_ENV="test", DB_PATH="",
DATA_DIR=str(tmp_path / "arm-test-data"))
with pytest.raises(RuntimeError) as err:
module.enforce()
assert "пуст" in str(err.value)
def test_data_dir_pointing_to_file_refused(monkeypatch, tmp_path):
file_path = tmp_path / "файл"
file_path.write_text("x")
module = _load(monkeypatch, CONTRACT_ENV="test",
DB_PATH=str(tmp_path / "smeta-web_test.db"), DATA_DIR=str(file_path))
with pytest.raises(RuntimeError) as err:
module.enforce()
assert "каталог" in str(err.value)
+1 -1
View File
@@ -128,7 +128,7 @@ def test_client_stream_carries_tool_calls(env, monkeypatch):
assert "[DONE]" in body
import json as _json
chunks = [_json.loads(l[5:]) for l in body.splitlines()
if l.startswith("data:") and "[DONE]" not in l]
if l.startswith("data:") and l[5:].strip() != "[DONE]"]
calls = [c["choices"][0]["delta"]["tool_calls"] for c in chunks
if (c["choices"][0].get("delta") or {}).get("tool_calls")]
first, fragments = calls[0][0], [call[0] for call in calls[1:]]