|
| 1 | +import os |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from openhands.tools.apply_patch.definition import ApplyPatchAction, ApplyPatchExecutor |
| 7 | + |
| 8 | + |
| 9 | +@pytest.fixture() |
| 10 | +def tmp_ws(tmp_path: Path) -> Path: |
| 11 | + # create a temp workspace root |
| 12 | + return tmp_path |
| 13 | + |
| 14 | + |
| 15 | +def run_exec(ws: Path, patch: str): |
| 16 | + ex = ApplyPatchExecutor(workspace_root=str(ws)) |
| 17 | + return ex(ApplyPatchAction(patch_text=patch)) |
| 18 | + |
| 19 | + |
| 20 | +def test_create_modify_delete(tmp_ws: Path): |
| 21 | + # 1) create FACTS.txt |
| 22 | + patch1 = ( |
| 23 | + "*** Begin Patch\n" |
| 24 | + "*** Add File: FACTS.txt\n" |
| 25 | + "+OpenHands SDK integrates tools.\n" |
| 26 | + "*** End Patch" |
| 27 | + ) |
| 28 | + obs1 = run_exec(tmp_ws, patch1) |
| 29 | + assert not obs1.is_error |
| 30 | + fp = tmp_ws / "FACTS.txt" |
| 31 | + assert fp.exists() |
| 32 | + assert fp.read_text().rstrip("\n") == "OpenHands SDK integrates tools." |
| 33 | + |
| 34 | + # 2) append a second line |
| 35 | + patch2 = ( |
| 36 | + "*** Begin Patch\n" |
| 37 | + "*** Update File: FACTS.txt\n" |
| 38 | + "@@\n" |
| 39 | + " OpenHands SDK integrates tools.\n" |
| 40 | + "+ApplyPatch works.\n" |
| 41 | + "*** End Patch" |
| 42 | + ) |
| 43 | + obs2 = run_exec(tmp_ws, patch2) |
| 44 | + assert not obs2.is_error |
| 45 | + assert fp.read_text() == ("OpenHands SDK integrates tools.\nApplyPatch works.") |
| 46 | + |
| 47 | + # 3) delete |
| 48 | + patch3 = "*** Begin Patch\n*** Delete File: FACTS.txt\n*** End Patch" |
| 49 | + obs3 = run_exec(tmp_ws, patch3) |
| 50 | + assert not obs3.is_error |
| 51 | + assert not fp.exists() |
| 52 | + |
| 53 | + |
| 54 | +def test_reject_absolute_path(tmp_ws: Path): |
| 55 | + # refuse escape/absolute paths |
| 56 | + patch = ( |
| 57 | + "*** Begin Patch\n" |
| 58 | + f"*** Add File: {os.path.abspath('/etc/passwd')}\n" |
| 59 | + "+x\n" |
| 60 | + "*** End Patch" |
| 61 | + ) |
| 62 | + obs = run_exec(tmp_ws, patch) |
| 63 | + assert obs.is_error |
| 64 | + assert "Absolute or escaping paths" in obs.text |
0 commit comments