"""存储目录平滑升级(.projectbrain → .botbrain)的路径解析测试。
覆盖设计文档 docs/migration-storage-dir.md §5 的全部场景:
M1 自动迁移 / M2 并存偏好新目录 / M3 降级只读 / M4 常规 / M5 全新,
迁移完整性、幂等性、并发竞态、cookie 回退与字面量防遗漏守卫。
"""
import json
import pytest
from project_brain.paths import (
LEGACY_PB_DIR_NAME,
PB_DIR_NAME,
MigrationResult,
config_file,
cookie_file,
graph_dir,
migrate_legacy,
pb_dir,
)
@pytest.fixture
def project(tmp_path):
root = tmp_path / "proj"
root.mkdir()
return root
def _make_legacy_store(project, config=True):
"""按 0.8.x 语义造一个旧目录图谱(含 CURRENT + generations)。"""
legacy = project / LEGACY_PB_DIR_NAME
gen_dir = legacy / "graph" / "generations" / "gen-001"
gen_dir.mkdir(parents=True)
(gen_dir / "nodes.json").write_text(json.dumps({"n1": {"id": "n1"}}), encoding="utf-8")
(legacy / "graph" / "CURRENT").write_text("gen-001", encoding="utf-8")
if config:
(legacy / "config.yaml").write_text("project:\n name: demo\n", encoding="utf-8")
return legacy
def test_fresh_project_creates_new_dir_name(project):
path, result = None, migrate_legacy(project)
assert result == MigrationResult.FRESH
path = pb_dir(project)
assert path == project / PB_DIR_NAME
assert path.name == ".botbrain"
def test_legacy_only_is_atomically_migrated(project):
legacy = _make_legacy_store(project)
path = pb_dir(project)
assert path == project / PB_DIR_NAME
assert not legacy.exists()
new = project / PB_DIR_NAME
assert (new / "graph" / "CURRENT").read_text(encoding="utf-8") == "gen-001"
nodes = json.loads(
(new / "graph" / "generations" / "gen-001" / "nodes.json").read_text(
encoding="utf-8",
)
)
assert nodes["n1"]["id"] == "n1"
assert (new / "config.yaml").exists()
assert migrate_legacy(project) == MigrationResult.ALREADY_NEW
def test_both_present_prefers_new_and_keeps_both(project):
_make_legacy_store(project)
new = project / PB_DIR_NAME
new.mkdir()
(new / "marker.txt").write_text("new", encoding="utf-8")
path = pb_dir(project)
assert path == new
assert (project / LEGACY_PB_DIR_NAME).exists()
assert (new / "marker.txt").read_text(encoding="utf-8") == "new"
def test_rename_failure_degrades_to_legacy_readonly(project, monkeypatch):
_make_legacy_store(project)
import os as os_module
real_rename = os_module.rename
def failing_rename(src, dst):
if str(dst).endswith(PB_DIR_NAME):
raise PermissionError("simulated handle lock")
return real_rename(src, dst)
monkeypatch.setattr(os_module, "rename", failing_rename)
path = pb_dir(project)
assert path == project / LEGACY_PB_DIR_NAME
assert (path / "graph" / "CURRENT").read_text(encoding="utf-8") == "gen-001"
assert migrate_legacy(project) == MigrationResult.DEGRADED_LEGACY_READONLY
def test_rename_race_lost_resolves_to_new_dir(project, monkeypatch):
_make_legacy_store(project)
import os as os_module
real_rename = os_module.rename
def racing_rename(src, dst):
real_rename(src, dst)
raise FileNotFoundError(src)
monkeypatch.setattr(os_module, "rename", racing_rename)
path = pb_dir(project)
assert path == project / PB_DIR_NAME
assert (path / "graph" / "CURRENT").read_text(encoding="utf-8") == "gen-001"
def test_migration_is_idempotent(project):
_make_legacy_store(project)
first = migrate_legacy(project)
second = migrate_legacy(project)
third = migrate_legacy(project)
assert first == MigrationResult.MIGRATED
assert second == MigrationResult.ALREADY_NEW
assert third == MigrationResult.ALREADY_NEW
assert not (project / LEGACY_PB_DIR_NAME).exists()
def test_graph_dir_and_config_file_helpers(project):
_make_legacy_store(project)
assert graph_dir(project) == project / PB_DIR_NAME / "graph"
assert config_file(project) == project / PB_DIR_NAME / "config.yaml"
def test_watcher_ignore_dirs_contain_both_names():
from project_brain.watcher.watcher import _DEFAULT_IGNORE_DIRS
assert PB_DIR_NAME in _DEFAULT_IGNORE_DIRS
assert LEGACY_PB_DIR_NAME in _DEFAULT_IGNORE_DIRS
def test_cookie_file_falls_back_to_legacy_only(monkeypatch, tmp_path):
import project_brain.paths as paths
new_home = tmp_path / "new_home"
legacy_home = tmp_path / "legacy_home"
legacy_home.mkdir()
legacy_cookie = legacy_home / LEGACY_PB_DIR_NAME
legacy_cookie.mkdir()
(legacy_cookie / "wiki_cookies.json").write_text("{}", encoding="utf-8")
monkeypatch.setattr(paths.Path, "home", lambda: legacy_home, raising=False)
assert paths.cookie_file() == legacy_cookie / "wiki_cookies.json"
new_cookie = new_home / PB_DIR_NAME
new_cookie.mkdir(parents=True)
(new_cookie / "wiki_cookies.json").write_text("{}", encoding="utf-8")
monkeypatch.setattr(paths.Path, "home", lambda: new_home, raising=False)
assert paths.cookie_file() == new_cookie / "wiki_cookies.json"
empty_home = tmp_path / "empty_home"
empty_home.mkdir()
monkeypatch.setattr(paths.Path, "home", lambda: empty_home, raising=False)
assert paths.cookie_file() == empty_home / PB_DIR_NAME / "wiki_cookies.json"
def test_no_legacy_literal_outside_paths_module():
"""防遗漏守卫:src 下除 paths.py 外不得再硬编码旧目录名字面量。"""
import re
from pathlib import Path
src_root = Path(__file__).resolve().parents[1] / "src" / "project_brain"
offenders = []
pattern = re.compile(r"[\"']\.projectbrain[\"']")
for py_file in src_root.rglob("*.py"):
if py_file.name == "paths.py":
continue
if pattern.search(py_file.read_text(encoding="utf-8")):
offenders.append(str(py_file))
assert offenders == []
def test_config_load_reads_migrated_config(project):
"""Config.load 走 paths 解析:仅存旧目录时迁移后能读到原配置。"""
from project_brain.config import Config
_make_legacy_store(project)
config = Config.load(str(project))
assert config.project_name == "demo"
assert config_file(project).exists()
assert not (project / LEGACY_PB_DIR_NAME).exists()
def test_cmd_build_migrates_legacy_store_in_real_build_flow(project, capsys):
"""端到端:真实 build 流程遇到旧目录时自动迁移并在新目录发布。"""
from project_brain.__main__ import _cmd_build
_make_legacy_store(project)
_cmd_build(project)
new_graph = project / PB_DIR_NAME / "graph"
assert new_graph.exists()
assert (new_graph / "CURRENT").exists()
assert not (project / LEGACY_PB_DIR_NAME).exists()
assert (project / PB_DIR_NAME / "config.yaml").exists()
def test_cookie_file_ignores_empty_new_dir(monkeypatch, tmp_path):
"""评审场景回归:新目录已存在但无 cookie 文件时,必须回退旧 cookie。
判断粒度是 cookie 文件级而非目录级——空的新目录不影响回退。
"""
import project_brain.paths as paths
home = tmp_path / "home"
legacy_cookie_dir = home / LEGACY_PB_DIR_NAME
legacy_cookie_dir.mkdir(parents=True)
(legacy_cookie_dir / "wiki_cookies.json").write_text("{}", encoding="utf-8")
(home / PB_DIR_NAME).mkdir()
monkeypatch.setattr(paths.Path, "home", lambda: home, raising=False)
assert paths.cookie_file() == legacy_cookie_dir / "wiki_cookies.json"