""" 项目管理 API 单元测试 ====================== 【功能说明】 覆盖项目 CRUD 全链路 + Git 分支读取接口,验证: 1. 创建/查询/更新/删除的正确性; 2. D 盘路径硬校验(硬约束 6); 3. 不存在项目的 404 语义; 4. Git 分支读取的降级行为(非 git 仓库路径不崩,返回明确提示)。 【技术选型理由】 用 pytest + FastAPI TestClient(httpx):不启动真实服务即可全链路验证, 存储层用临时 SQLite 文件隔离,互不干扰、可重复执行。 【实现思路】 - fixture 提供临时 DB 与 TestClient; - Git 分支测试用临时目录 + 真实 git init 做集成验证(机器已装 git); - 断言统一校验 ApiResponse 结构(code/message/data),对齐前端契约。 【潜在风险与应对】 风险1:测试污染真实数据目录。 应对:DB 路径指向 tmp_path,跑完即销毁,绝不碰 D:\\Agent\\agent\\data。 风险2:git 未安装导致测试失败。 应对:git 相关用例用 pytest.mark.skipif 优雅跳过,不误报。 """ from __future__ import annotations import shutil import subprocess from pathlib import Path from typing import Generator from uuid import uuid4 import pytest from fastapi.testclient import TestClient from app.api.project_api import get_store from app.main import create_app from app.store.project_store import SqliteProjectStore # ---------- Fixtures ---------- @pytest.fixture() def tmp_db_path(d_tmp_path: Path) -> Path: """提供一个临时 SQLite 文件路径(测试隔离,跑完自动清理)。""" return d_tmp_path / "test_agent.db" @pytest.fixture() def d_tmp_path() -> Generator[Path, None, None]: """ 测试专用临时目录,强制落在 D 盘。 【理由】业务层对 code_root_path 有「必须 D 盘」硬校验(硬约束 6), 若用 pytest 默认的 tmp_path(在 C 盘用户临时目录),建项目会被正确拒绝, 导致集成用例误失败。故统一把测试工作区放到 D:\\Agent\\agent\\data\\pytest_tmp。 """ base = Path(r"D:\Agent\pytest_tmp") base.mkdir(parents=True, exist_ok=True) work = base / uuid4().hex[:12] work.mkdir(parents=True, exist_ok=True) yield work shutil.rmtree(work, ignore_errors=True) @pytest.fixture() def store(tmp_db_path: Path) -> SqliteProjectStore: """构造基于临时库的存储实现。""" return SqliteProjectStore(tmp_db_path) @pytest.fixture() def client(store: SqliteProjectStore) -> TestClient: """ 构造 FastAPI 测试客户端,并把依赖替换为临时存储。 【关键】用 app.dependency_overrides 注入临时 store, 避免测试误写真实 D:\\Agent\\agent\\data\\agent.db。 """ app = create_app() app.dependency_overrides[get_store] = lambda: store with TestClient(app) as c: yield c app.dependency_overrides.clear() def _sample_payload(name: str = "测试项目") -> dict: """构造一份合法的项目创建载荷(路径在 D 盘,满足硬约束 6)。""" return { "name": name, "code_root_path": r"D:\Agent\code\测试项目", "backend_path": "backend", "frontend_path": "frontend", "backend_branch": "master", "frontend_branch": "master", "description": "自动化测试用项目", } # ---------- 项目 CRUD ---------- def test_create_project_success(client: TestClient) -> None: """创建项目成功:返回 code=0 且带系统字段 id/时间戳。""" resp = client.post("/api/projects", json=_sample_payload()) assert resp.status_code == 200 body = resp.json() assert body["code"] == 0, f"创建失败:{body['message']}" data = body["data"] assert data["name"] == "测试项目" assert data["id"].startswith("proj_") assert data["created_at"] and data["updated_at"] def test_create_project_rejects_non_d_drive(client: TestClient) -> None: """硬约束 6:非 D 盘路径必须被拒绝,且给出中文错误提示。""" payload = _sample_payload() payload["code_root_path"] = r"C:\Users\EDY\code\测试项目" resp = client.post("/api/projects", json=payload) assert resp.status_code == 422 # Pydantic 校验失败 assert "D 盘" in resp.text def test_list_projects(client: TestClient) -> None: """列表查询:创建两个项目后能查到两条。""" client.post("/api/projects", json=_sample_payload("项目A")) client.post("/api/projects", json=_sample_payload("项目B")) resp = client.get("/api/projects") body = resp.json() assert body["code"] == 0 assert len(body["data"]) == 2 def test_get_project_not_found(client: TestClient) -> None: """查询不存在的项目:返回 404 业务码,而非 HTTP 500。""" resp = client.get("/api/projects/proj_notexist") body = resp.json() assert body["code"] == 404 assert "不存在" in body["message"] def test_update_project(client: TestClient) -> None: """更新项目:只传入的字段被覆盖,未传字段保持原值。""" created = client.post("/api/projects", json=_sample_payload()).json()["data"] resp = client.put( f"/api/projects/{created['id']}", json={"name": "改名后", "description": "新描述"} ) body = resp.json() assert body["code"] == 0 assert body["data"]["name"] == "改名后" assert body["data"]["description"] == "新描述" # 未传字段应保持原值 assert body["data"]["backend_branch"] == "master" def test_update_project_not_found(client: TestClient) -> None: """更新不存在的项目:返回 404。""" resp = client.put("/api/projects/proj_notexist", json={"name": "x"}) assert resp.json()["code"] == 404 def test_delete_project(client: TestClient) -> None: """删除项目:首次删除成功,二次删除返回 404。""" created = client.post("/api/projects", json=_sample_payload()).json()["data"] first = client.delete(f"/api/projects/{created['id']}").json() assert first["code"] == 0 and first["data"] is True second = client.delete(f"/api/projects/{created['id']}").json() assert second["code"] == 404 # ---------- Git 分支读取(集成)---------- GIT_AVAILABLE = shutil.which("git") is not None def _init_git_repo(path: Path, branches: list[str]) -> None: """ 在临时目录初始化 git 仓库并建出指定分支(用于集成测试)。 【要点】git init -b master 已创建 master 分支, 重复执行 `git branch master` 会报错(exit 128),故跳过 HEAD 已有分支。 """ path.mkdir(parents=True, exist_ok=True) subprocess.run(["git", "init", "-b", "master"], cwd=path, check=True, capture_output=True) subprocess.run( ["git", "config", "user.email", "test@example.com"], cwd=path, check=True, capture_output=True ) subprocess.run( ["git", "config", "user.name", "test"], cwd=path, check=True, capture_output=True ) (path / "README.md").write_text("# test", encoding="utf-8") subprocess.run(["git", "add", "."], cwd=path, check=True, capture_output=True) subprocess.run( ["git", "commit", "-m", "init"], cwd=path, check=True, capture_output=True ) # master 已由 git init -b master 创建,只补建其余分支 for b in branches: if b == "master": continue subprocess.run( ["git", "branch", b], cwd=path, check=True, capture_output=True ) @pytest.mark.skipif(not GIT_AVAILABLE, reason="机器未安装 git,跳过分支读取用例") def test_list_branches_success(client: TestClient, d_tmp_path: Path) -> None: """分支读取:对真实 git 仓库能读出全部分支名。""" code_root = d_tmp_path / "demo" _init_git_repo(code_root / "backend", ["master", "develop"]) _init_git_repo(code_root / "frontend", ["master"]) payload = _sample_payload() payload["code_root_path"] = str(code_root) created = client.post("/api/projects", json=payload).json()["data"] resp = client.get(f"/api/projects/{created['id']}/branches") body = resp.json() assert body["code"] == 0, f"分支读取失败:{body['message']}" assert set(body["data"]["backend"]) == {"master", "develop"} assert set(body["data"]["frontend"]) == {"master"} @pytest.mark.skipif(not GIT_AVAILABLE, reason="机器未安装 git,跳过分支读取用例") def test_list_branches_degrades_on_non_git_path(client: TestClient, d_tmp_path: Path) -> None: """降级验证:路径不是 git 仓库时不崩溃,返回 code=1 + 明确中文提示。""" code_root = d_tmp_path / "nogit" (code_root / "backend").mkdir(parents=True, exist_ok=True) (code_root / "frontend").mkdir(parents=True, exist_ok=True) payload = _sample_payload() payload["code_root_path"] = str(code_root) created = client.post("/api/projects", json=payload).json()["data"] resp = client.get(f"/api/projects/{created['id']}/branches") body = resp.json() # 不应 500,应是降级响应 assert resp.status_code == 200 assert body["code"] == 1 assert "Git" in body["message"] or "git" in body["message"] assert body["data"] == {"backend": [], "frontend": []}