Files
AgentScript/agent/backend/tests/test_m4_tools.py
T

214 lines
7.2 KiB
Python
Raw Normal View History

"""
M4 自研工具链测试
=================
【功能说明】
覆盖路径守卫、文件读写编辑、搜索定位、白名单执行器、Git 工具全链路。
重点验证安全边界(越权拒绝、白名单拦截、备份还原)。
【技术选型理由】
1. 安全类用例优先:工具链是 Agent 的"手",手不能乱伸;
2. 真实文件操作在 D 盘临时目录进行,与生产隔离;
3. 执行器用白名单内真实命令(git version)验证,避免 mock 掩盖问题。
【实现思路】
- 每个工具类配 success + denial/异常 两组用例;
- 备份还原做完整闭环验证(改 → 备份 → 还原 → 内容一致)。
【潜在风险与应对】
风险1:测试残留文件污染 D:\\Agent\\code。
应对:测试文件放 pytest_tmp,跑完清理。
风险2:Windows 路径大小写导致断言失败。
统一用 str(path).lower() 比对或用 Path 对象比较。
"""
from __future__ import annotations
import shutil
from pathlib import Path
from typing import Generator
from uuid import uuid4
import pytest
from app.tools.executor import ExecutorError, run_command
from app.tools.file_tools import (
FileToolError,
edit_file,
read_file,
restore_backup,
write_file,
)
from app.tools.path_guard import PathSecurityError, get_default_guard
from app.tools.search_tools import find_files, grep_files
# ---------- Fixtures ----------
@pytest.fixture()
def d_tmp_path() -> Generator[Path, None, None]:
"""D 盘测试临时目录(在守卫允许的 agent/data 下)。"""
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)
# ---------- 路径守卫 ----------
def test_path_guard_allows_code_root() -> None:
"""D:\\Agent\\code 下的路径应被允许。"""
guard = get_default_guard()
assert guard.is_allowed(Path(r"D:\Agent\code\demo\src")) is True
def test_path_guard_rejects_c_drive() -> None:
"""C 盘路径必须被拒绝(硬约束 6)。"""
guard = get_default_guard()
assert guard.is_allowed(Path(r"C:\Windows\System32")) is False
def test_path_guard_rejects_traversal() -> None:
"""路径穿越攻击(..\\..\\)应被拒绝。"""
guard = get_default_guard()
assert guard.is_allowed(Path(r"D:\Agent\code\..\..\Windows")) is False
def test_path_guard_ensure_raises() -> None:
"""越权访问抛 PathSecurityError。"""
guard = get_default_guard()
with pytest.raises(PathSecurityError):
guard.ensure_allowed(Path(r"C:\Users\EDY"), action="读取")
# ---------- 文件工具 ----------
def test_write_and_read_file(d_tmp_path: Path) -> None:
"""写入后能读取,内容一致。"""
target = d_tmp_path / "demo.txt"
write_file(target, "你好世界\n第二行")
result = read_file(target)
assert "你好世界" in result["content"]
assert result["total_lines"] == 2
def test_write_creates_backup_on_existing_file(d_tmp_path: Path) -> None:
"""覆盖已有文件时生成快照备份。"""
target = d_tmp_path / "demo.txt"
write_file(target, "原始内容")
result = write_file(target, "新内容", task_id="t1")
assert result["backup_path"] is not None
# 备份内容应是原始内容
backup_content = Path(result["backup_path"]).read_text(encoding="utf-8")
assert backup_content == "原始内容"
def test_edit_file_unique_match(d_tmp_path: Path) -> None:
"""精确编辑:唯一匹配成功替换。"""
target = d_tmp_path / "code.java"
write_file(target, "public class A {\n int x = 1;\n}")
result = edit_file(target, "int x = 1;", "int x = 2;")
assert result["replacements"] == 1
content = read_file(target)["content"]
assert "int x = 2;" in content
def test_edit_file_rejects_ambiguous_match(d_tmp_path: Path) -> None:
"""多次匹配时报错,不误替换。"""
target = d_tmp_path / "dup.java"
write_file(target, "int x = 1;\nint x = 1;\n")
with pytest.raises(FileToolError) as exc:
edit_file(target, "int x = 1;", "int x = 2;")
assert "出现 2 次" in str(exc.value)
def test_edit_file_rejects_not_found(d_tmp_path: Path) -> None:
"""未匹配到文本时报错。"""
target = d_tmp_path / "code.java"
write_file(target, "hello")
with pytest.raises(FileToolError):
edit_file(target, "不存在的字符串", "x")
def test_restore_backup_roundtrip(d_tmp_path: Path) -> None:
"""备份还原闭环:改 → 还原 → 内容回到原始。"""
target = d_tmp_path / "data.txt"
write_file(target, "原始版本")
result = write_file(target, "被改坏的版本", task_id="t2")
backup = result["backup_path"]
assert backup
restore_backup(backup, target)
assert read_file(target)["content"] == "原始版本"
# ---------- 搜索工具 ----------
def test_grep_files_finds_matches(d_tmp_path: Path) -> None:
"""grep 能按正则搜到内容。"""
(d_tmp_path / "A.java").write_text(
"public class A {\n void doSomething() {}\n}", encoding="utf-8"
)
(d_tmp_path / "B.java").write_text(
"public class B {\n void doOther() {}\n}", encoding="utf-8"
)
result = grep_files("doSomething", d_tmp_path, glob_filter="*.java")
assert result["total_matches"] == 1
assert "A.java" in result["results"][0]["file"]
def test_find_files_by_name(d_tmp_path: Path) -> None:
"""文件名模糊查找。"""
(d_tmp_path / "OrderController.java").write_text("x", encoding="utf-8")
(d_tmp_path / "User.java").write_text("y", encoding="utf-8")
result = find_files("Controller", d_tmp_path)
assert result["total"] == 1
assert "OrderController" in result["files"][0]
# ---------- 白名单执行器 ----------
def test_executor_rejects_non_whitelist_command(d_tmp_path: Path) -> None:
"""非白名单命令必须被拒绝。"""
with pytest.raises(ExecutorError) as exc:
run_command(["rm", "-rf", "/"], cwd=d_tmp_path)
assert "白名单" in str(exc.value)
def test_executor_rejects_forbidden_args(d_tmp_path: Path) -> None:
"""白名单命令带危险子参数也被拒绝。"""
with pytest.raises(ExecutorError) as exc:
run_command(["git", "push", "--force"], cwd=d_tmp_path)
assert "禁止" in str(exc.value)
def test_executor_rejects_shell_injection(d_tmp_path: Path) -> None:
"""shell 注入(; & |)因 list 传参天然失效,但含 rm 的参数仍被拦。"""
with pytest.raises(ExecutorError):
run_command(["git", "status", ";", "rm", "-rf", "/"], cwd=d_tmp_path)
def test_executor_runs_allowed_command(d_tmp_path: Path) -> None:
"""白名单命令可正常执行。"""
result = run_command(["git", "version"], cwd=d_tmp_path)
assert result["returncode"] == 0
assert "git version" in result["stdout"]
def test_executor_timeout(d_tmp_path: Path) -> None:
"""超时命令抛 Timeout 异常(用 python sleep 验证真实超时)。"""
with pytest.raises(ExecutorError) as exc:
run_command(
["python", "-c", "import time; time.sleep(30)"],
cwd=d_tmp_path,
timeout=1,
)
assert "超时" in str(exc.value)