from __future__ import annotations import json import sys from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from cc_slim.tools import ( _safe_path, bash_tool, edit_tool, glob_tool, grep_tool, read_tool, write_tool, ) def test_safe_path_allows_workspace_children(tmp_path: Path) -> None: path = _safe_path(tmp_path, "a/b.txt") assert path == (tmp_path / "a/b.txt").resolve() def test_safe_path_blocks_escape(tmp_path: Path) -> None: with pytest.raises(ValueError, match="路径越过工作区边界"): _safe_path(tmp_path, "../outside.txt") def test_write_edit_read_glob_grep_flow(tmp_path: Path) -> None: created = write_tool(tmp_path, {"path": "hello.py", "content": "print('hello')\n"}) edited = edit_tool(tmp_path, {"path": "hello.py", "content": "print('world')\n"}) read_back = read_tool(tmp_path, {"path": "hello.py"}) globbed = glob_tool(tmp_path, {"pattern": "*.py"}) grepped = grep_tool(tmp_path, {"pattern": "world", "path": "."}) assert created == "已创建文件: hello.py" assert edited == "已修改文件: hello.py" assert "1: print('world')" in read_back assert globbed == "hello.py" assert "hello.py:1: print('world')" in grepped def test_bash_tool_success(tmp_path: Path) -> None: result = bash_tool(tmp_path, {"command": "cmd /c exit 0"}) payload = json.loads(result) assert payload["returncode"] == 0 def test_edit_requires_existing_file(tmp_path: Path) -> None: result = edit_tool(tmp_path, {"path": "missing.txt", "content": "x"}) assert result == "文件不存在: missing.txt"