476 lines
17 KiB
Python
476 lines
17 KiB
Python
"""Property-based tests for LangGraph agent file system tools.
|
|
|
|
Uses hypothesis to verify universal properties across many generated inputs.
|
|
"""
|
|
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from hypothesis import given, settings, strategies as st, assume
|
|
|
|
import tools
|
|
|
|
|
|
# ── Helpers ──────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def _set_workdir(path: Path):
|
|
"""Set tools.WORKDIR to the given path for testing."""
|
|
tools.set_workdir(path.resolve())
|
|
|
|
|
|
# Strategy for safe filenames (no path separators, no null bytes, non-empty)
|
|
safe_filename = st.text(
|
|
alphabet=st.characters(
|
|
whitelist_categories=("L", "N", "Pd"),
|
|
whitelist_characters="_",
|
|
),
|
|
min_size=1,
|
|
max_size=20,
|
|
).filter(lambda s: s.strip() != "" and s not in (".", ".."))
|
|
|
|
|
|
# Strategy for nested directory segments
|
|
safe_dir_segment = st.text(
|
|
alphabet=st.characters(
|
|
whitelist_categories=("L", "N"),
|
|
whitelist_characters="_",
|
|
),
|
|
min_size=1,
|
|
max_size=10,
|
|
).filter(lambda s: s.strip() != "" and s not in (".", ".."))
|
|
|
|
|
|
# ── Property 1: Write-Read Round Trip ────────────────────────────────────────
|
|
|
|
|
|
class TestProperty1WriteReadRoundTrip:
|
|
"""Feature: langgraph-agent, Property 1: Write-Read Round Trip
|
|
|
|
**Validates: Requirements 2.1, 4.1, 4.3**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(content=st.text(alphabet=st.characters(blacklist_characters="\r", blacklist_categories=("Cs",))))
|
|
def test_write_then_read_returns_identical_content(self, content):
|
|
"""For any content, write_file then read_file returns identical content."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
_set_workdir(Path(td))
|
|
result = tools.write_file.invoke({"path": "test.txt", "content": content})
|
|
assert "Successfully wrote" in result
|
|
read_result = tools.read_file.invoke({"path": "test.txt"})
|
|
assert read_result == content
|
|
|
|
|
|
# ── Property 2: Line Range Slicing ──────────────────────────────────────────
|
|
|
|
|
|
class TestProperty2LineRangeSlicing:
|
|
"""Feature: langgraph-agent, Property 2: Line Range Slicing
|
|
|
|
**Validates: Requirements 2.2, 2.4**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(
|
|
lines=st.lists(
|
|
st.text(
|
|
alphabet=st.characters(blacklist_categories=("Cc", "Cs"), blacklist_characters="\r\n\x0b\x0c\x1c\x1d\x1e\x1f\x85"),
|
|
min_size=0,
|
|
max_size=50,
|
|
),
|
|
min_size=1,
|
|
max_size=30,
|
|
),
|
|
start_line=st.integers(min_value=-5, max_value=50),
|
|
end_line=st.integers(min_value=-5, max_value=50),
|
|
)
|
|
def test_line_range_returns_correct_slice(self, lines, start_line, end_line):
|
|
"""read_file with line range returns the correct slice of lines."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
content = "\n".join(lines)
|
|
tools.write_file.invoke({"path": "lines.txt", "content": content})
|
|
|
|
result = tools.read_file.invoke(
|
|
{"path": "lines.txt", "start_line": start_line, "end_line": end_line}
|
|
)
|
|
|
|
# Compute expected slice using the same logic as the implementation:
|
|
# splitlines(keepends=True) then slice [max(0, start-1) : min(N, end)]
|
|
all_lines = content.splitlines(keepends=True)
|
|
n = len(all_lines)
|
|
|
|
if n == 0:
|
|
assert result == content
|
|
else:
|
|
s_idx = max(0, start_line - 1)
|
|
e_idx = min(n, end_line)
|
|
expected = "".join(all_lines[s_idx:e_idx])
|
|
assert result == expected
|
|
|
|
|
|
# ── Property 3: Read Non-Existent File Returns Error ────────────────────────
|
|
|
|
|
|
class TestProperty3ReadNonExistentFile:
|
|
"""Feature: langgraph-agent, Property 3: Read Non-Existent File Returns Error
|
|
|
|
**Validates: Requirements 2.3**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(filename=safe_filename)
|
|
def test_read_nonexistent_file_returns_error_string(self, filename):
|
|
"""For any non-existent file path, read_file returns an error string."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
# Ensure the file does not exist
|
|
target = tmp_path / filename
|
|
if target.exists():
|
|
target.unlink()
|
|
|
|
result = tools.read_file.invoke({"path": filename})
|
|
# Should return error string, not raise exception
|
|
assert isinstance(result, str)
|
|
assert "Error" in result
|
|
|
|
|
|
# ── Property 4: Grep Finds All Matches with Correct Format ──────────────────
|
|
|
|
|
|
class TestProperty4GrepFindsAllMatches:
|
|
"""Feature: langgraph-agent, Property 4: Grep Finds All Matches with Correct Format
|
|
|
|
**Validates: Requirements 3.1, 3.2, 3.4**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(
|
|
pattern=st.text(
|
|
alphabet=st.characters(blacklist_categories=("Cc", "Cs"), blacklist_characters="\r\n\x0b\x0c\x1c\x1d\x1e\x1f\x85"),
|
|
min_size=1,
|
|
max_size=10,
|
|
).filter(lambda s: s.strip() != ""),
|
|
file_lines=st.lists(
|
|
st.text(
|
|
alphabet=st.characters(blacklist_categories=("Cc", "Cs"), blacklist_characters="\r\n\x0b\x0c\x1c\x1d\x1e\x1f\x85"),
|
|
min_size=0,
|
|
max_size=50,
|
|
),
|
|
min_size=1,
|
|
max_size=20,
|
|
),
|
|
)
|
|
def test_grep_finds_all_matches_with_correct_format(self, pattern, file_lines):
|
|
"""grep returns all lines containing the pattern with correct format."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
|
|
# Write test file
|
|
content = "\n".join(file_lines)
|
|
(tmp_path / "search.txt").write_text(content)
|
|
|
|
result = tools.grep.invoke({"pattern": pattern, "path": "."})
|
|
|
|
# Find expected matches
|
|
expected_matches = []
|
|
for line_num, line in enumerate(file_lines, start=1):
|
|
if pattern in line:
|
|
expected_matches.append((line_num, line))
|
|
|
|
if not expected_matches:
|
|
assert "No matches found" in result
|
|
else:
|
|
# Each match should appear in the result with correct format
|
|
for line_num, line in expected_matches:
|
|
# Format: {file_path}:{line_number}: {line_content}
|
|
assert f":{line_num}: {line}" in result
|
|
# Verify file path is included
|
|
assert "search.txt" in result
|
|
|
|
|
|
# ── Property 5: Write Creates Parent Directories ────────────────────────────
|
|
|
|
|
|
class TestProperty5WriteCreatesParentDirs:
|
|
"""Feature: langgraph-agent, Property 5: Write Creates Parent Directories
|
|
|
|
**Validates: Requirements 4.2**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(
|
|
segments=st.lists(safe_dir_segment, min_size=1, max_size=4),
|
|
filename=safe_filename,
|
|
content=st.text(alphabet=st.characters(blacklist_characters="\r", blacklist_categories=("Cs",)), max_size=100),
|
|
)
|
|
def test_write_creates_parent_directories(self, segments, filename, content):
|
|
"""write_file creates all necessary parent directories."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
nested_path = "/".join(segments) + "/" + filename
|
|
result = tools.write_file.invoke({"path": nested_path, "content": content})
|
|
assert "Successfully wrote" in result
|
|
|
|
# Verify all parent directories were created
|
|
full_path = tmp_path / Path(nested_path)
|
|
assert full_path.exists()
|
|
assert full_path.read_text() == content
|
|
|
|
|
|
# ── Property 6: Write Returns Confirmation with Path ────────────────────────
|
|
|
|
|
|
class TestProperty6WriteReturnsConfirmation:
|
|
"""Feature: langgraph-agent, Property 6: Write Returns Confirmation with Path
|
|
|
|
**Validates: Requirements 4.4**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(
|
|
filename=safe_filename,
|
|
content=st.text(alphabet=st.characters(blacklist_characters="\r", blacklist_categories=("Cs",)), max_size=100),
|
|
)
|
|
def test_write_returns_confirmation_containing_path(self, filename, content):
|
|
"""write_file return value contains the file path that was written."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
result = tools.write_file.invoke({"path": filename, "content": content})
|
|
assert isinstance(result, str)
|
|
assert filename in result
|
|
|
|
|
|
# ── Property 7: List Directory Completeness and Format ──────────────────────
|
|
|
|
|
|
class TestProperty7ListDirCompleteness:
|
|
"""Feature: langgraph-agent, Property 7: List Directory Completeness and Format
|
|
|
|
**Validates: Requirements 5.1, 5.2**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(
|
|
file_names=st.lists(safe_filename, min_size=0, max_size=5, unique=True),
|
|
dir_names=st.lists(safe_dir_segment, min_size=0, max_size=5, unique=True),
|
|
)
|
|
def test_list_dir_returns_all_entries_with_correct_format(
|
|
self, file_names, dir_names
|
|
):
|
|
"""list_dir returns all entries with [FILE] or [DIR] prefix."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
|
|
# Ensure no overlap between file and dir names
|
|
dir_names = [d for d in dir_names if d not in file_names]
|
|
|
|
# Create files
|
|
for fname in file_names:
|
|
(tmp_path / fname).write_text("content")
|
|
|
|
# Create directories
|
|
for dname in dir_names:
|
|
(tmp_path / dname).mkdir(exist_ok=True)
|
|
|
|
result = tools.list_dir.invoke({"path": "."})
|
|
|
|
# Verify all files are listed with [FILE] prefix
|
|
for fname in file_names:
|
|
assert f"[FILE] {fname}" in result
|
|
|
|
# Verify all directories are listed with [DIR] prefix
|
|
for dname in dir_names:
|
|
assert f"[DIR] {dname}" in result
|
|
|
|
|
|
# ── Property 8: List Directory Error Handling ───────────────────────────────
|
|
|
|
|
|
class TestProperty8ListDirErrorHandling:
|
|
"""Feature: langgraph-agent, Property 8: List Directory Error Handling
|
|
|
|
**Validates: Requirements 5.3, 5.4**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(filename=safe_filename)
|
|
def test_list_nonexistent_path_returns_error(self, filename):
|
|
"""list_dir on non-existent path returns error message."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
# Ensure path doesn't exist
|
|
target = tmp_path / filename
|
|
if target.exists():
|
|
if target.is_dir():
|
|
target.rmdir()
|
|
else:
|
|
target.unlink()
|
|
|
|
result = tools.list_dir.invoke({"path": filename})
|
|
assert isinstance(result, str)
|
|
assert "Error" in result
|
|
|
|
@settings(max_examples=100)
|
|
@given(filename=safe_filename)
|
|
def test_list_file_path_returns_error(self, filename):
|
|
"""list_dir on a file (not directory) returns error message."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
# Create a file
|
|
(tmp_path / filename).write_text("I am a file")
|
|
|
|
result = tools.list_dir.invoke({"path": filename})
|
|
assert isinstance(result, str)
|
|
assert "Error" in result
|
|
assert "Not a directory" in result
|
|
|
|
|
|
# ── Property 10: Workdir Path Containment ───────────────────────────────────
|
|
|
|
|
|
class TestProperty10WorkdirPathContainment:
|
|
"""Feature: langgraph-agent, Property 10: Workdir Path Containment
|
|
|
|
**Validates: Requirements 8.5, 8.6, 8.7**
|
|
"""
|
|
|
|
@settings(max_examples=100)
|
|
@given(
|
|
segments=st.lists(
|
|
st.sampled_from(["a", "b", "..", "subdir", "x"]),
|
|
min_size=1,
|
|
max_size=6,
|
|
)
|
|
)
|
|
def test_dot_dot_traversal_outside_workdir_rejected(self, segments):
|
|
"""Paths with .. traversal that resolve outside workdir are rejected."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
path = "/".join(segments) + "/file.txt"
|
|
|
|
# Determine if the resolved path would be inside or outside workdir
|
|
candidate = (tmp_path / path).resolve()
|
|
workdir_resolved = tmp_path.resolve()
|
|
|
|
try:
|
|
candidate.relative_to(workdir_resolved)
|
|
is_inside = True
|
|
except ValueError:
|
|
is_inside = False
|
|
|
|
if is_inside:
|
|
# Path is inside workdir — validate_path should succeed
|
|
result = tools.validate_path(path)
|
|
assert result == str(candidate)
|
|
else:
|
|
# Path escapes workdir — validate_path should reject
|
|
with pytest.raises(ValueError, match="Access denied"):
|
|
tools.validate_path(path)
|
|
|
|
@settings(max_examples=100)
|
|
@given(
|
|
abs_path=st.sampled_from([
|
|
"/etc/passwd",
|
|
"/tmp/evil.txt",
|
|
"/usr/bin/python",
|
|
"/var/log/syslog",
|
|
])
|
|
)
|
|
def test_absolute_paths_outside_workdir_rejected(self, abs_path):
|
|
"""Absolute paths outside workdir are rejected."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
tmp_path = Path(td)
|
|
_set_workdir(tmp_path)
|
|
with pytest.raises(ValueError, match="Access denied"):
|
|
tools.validate_path(abs_path)
|
|
|
|
def test_symlink_escaping_workdir_rejected(self, tmp_path):
|
|
"""Symlinks that resolve outside workdir are rejected."""
|
|
_set_workdir(tmp_path)
|
|
|
|
# Create a directory outside workdir
|
|
outside = tmp_path.parent / "outside_target"
|
|
outside.mkdir(exist_ok=True)
|
|
(outside / "secret.txt").write_text("secret data")
|
|
|
|
# Create symlink inside workdir pointing outside
|
|
link = tmp_path / "escape_link"
|
|
link.symlink_to(outside)
|
|
|
|
with pytest.raises(ValueError, match="Access denied"):
|
|
tools.validate_path("escape_link/secret.txt")
|
|
|
|
|
|
# ── Property 11: Workdir Validation on Startup ──────────────────────────────
|
|
|
|
|
|
class TestProperty11WorkdirValidationOnStartup:
|
|
"""Feature: langgraph-agent, Property 11: Workdir Validation on Startup
|
|
|
|
**Validates: Requirements 8.2, 8.3, 8.4**
|
|
"""
|
|
|
|
def test_missing_workdir_exits_with_error(self):
|
|
"""Missing --workdir causes exit with error."""
|
|
result = subprocess.run(
|
|
[sys.executable, "main.py"],
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
assert result.returncode != 0
|
|
assert "--workdir argument is required" in result.stderr
|
|
|
|
def test_nonexistent_workdir_exits_with_error(self, tmp_path):
|
|
"""Non-existent --workdir path causes exit with error."""
|
|
nonexistent = tmp_path / "does_not_exist"
|
|
result = subprocess.run(
|
|
[sys.executable, "main.py", "--workdir", str(nonexistent)],
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
assert result.returncode != 0
|
|
assert "Workdir does not exist" in result.stderr
|
|
|
|
def test_workdir_is_file_exits_with_error(self, tmp_path):
|
|
"""--workdir pointing to a file (not directory) causes exit with error."""
|
|
file_path = tmp_path / "not_a_dir.txt"
|
|
file_path.write_text("I am a file")
|
|
result = subprocess.run(
|
|
[sys.executable, "main.py", "--workdir", str(file_path)],
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
assert result.returncode != 0
|
|
assert "Workdir is not a directory" in result.stderr
|
|
|
|
@settings(max_examples=100, deadline=None)
|
|
@given(dirname=safe_dir_segment)
|
|
def test_invalid_workdir_paths_exit_with_error(self, dirname):
|
|
"""Any non-existent workdir path causes exit with error."""
|
|
with tempfile.TemporaryDirectory() as td:
|
|
nonexistent = Path(td) / dirname / "nested" / "deep"
|
|
# Ensure it doesn't exist
|
|
assume(not nonexistent.exists())
|
|
|
|
result = subprocess.run(
|
|
[sys.executable, "main.py", "--workdir", str(nonexistent)],
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
assert result.returncode != 0
|
|
assert "Error" in result.stderr
|