import pytest from pathlib import Path from src.tools.file_ops import FileOperations def test_file_operations_read_scope(tmp_path): ops = FileOperations(repo_root=str(tmp_path)) test_file = tmp_path / "sample.py" test_file.write_text("line one\nline two\nline three\n", encoding="utf-8") res = ops.read_scope("sample.py", 1, 2) assert res["status"] == "success" assert res["total_lines"] == 3 assert "line one" in res["content"] assert "line two" in res["content"] def test_file_operations_read_scope_not_found(tmp_path): ops = FileOperations(repo_root=str(tmp_path)) res = ops.read_scope("nonexistent.py", 1, 5) assert res["status"] == "error" assert "not found" in res["message"] def test_file_operations_read_scope_generic_exception(tmp_path, monkeypatch): ops = FileOperations(repo_root=str(tmp_path)) test_file = tmp_path / "error.py" test_file.write_text("content", encoding="utf-8") def mock_read_text(*args, **kwargs): raise RuntimeError("Simulated read failure") monkeypatch.setattr("pathlib.Path.read_text", mock_read_text) res = ops.read_scope("error.py", 1, 2) assert res["status"] == "error" assert "Simulated read failure" in res["message"] def test_file_operations_patch_file(tmp_path): ops = FileOperations(repo_root=str(tmp_path)) test_file = tmp_path / "target.py" test_file.write_text("def hello():\n return 'old'\n", encoding="utf-8") res = ops.patch_file("target.py", "return 'old'", "return 'new'") assert res["status"] == "success" updated_content = test_file.read_text(encoding="utf-8") assert "return 'new'" in updated_content def test_file_operations_patch_file_missing_target(tmp_path): ops = FileOperations(repo_root=str(tmp_path)) test_file = tmp_path / "target.py" test_file.write_text("def hello():\n return 'old'\n", encoding="utf-8") res = ops.patch_file("target.py", "nonexistent_code", "replacement") assert res["status"] == "error" assert "Target code block not found" in res["message"] def test_file_operations_patch_file_exception(tmp_path): ops = FileOperations(repo_root=str(tmp_path)) sub_dir = tmp_path / "subdir" sub_dir.mkdir() res = ops.patch_file("subdir", "target", "replacement") assert res["status"] == "error" def test_file_operations_path_traversal_security(tmp_path): ops = FileOperations(repo_root=str(tmp_path)) res = ops.read_scope("../outside_file.py", 1, 5) assert res["status"] == "error" assert "Access denied" in res["message"] def test_patch_file_not_found(tmp_path): from src.tools.file_ops import FileOperations ops = FileOperations(repo_root=str(tmp_path)) res = ops.patch_file("nonexistent.py", "target", "replacement") assert res["status"] == "error" assert "not found" in res["message"]