feat: first commit
This commit is contained in:
1
tests/__init__.py
Normal file
1
tests/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# Tests package
|
||||
BIN
tests/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
tests/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
tests/__pycache__/test_agent.cpython-312-pytest-9.0.2.pyc
Normal file
BIN
tests/__pycache__/test_agent.cpython-312-pytest-9.0.2.pyc
Normal file
Binary file not shown.
BIN
tests/__pycache__/test_cli.cpython-312-pytest-9.0.2.pyc
Normal file
BIN
tests/__pycache__/test_cli.cpython-312-pytest-9.0.2.pyc
Normal file
Binary file not shown.
BIN
tests/__pycache__/test_llm.cpython-312-pytest-9.0.2.pyc
Normal file
BIN
tests/__pycache__/test_llm.cpython-312-pytest-9.0.2.pyc
Normal file
Binary file not shown.
Binary file not shown.
BIN
tests/__pycache__/test_properties.cpython-312-pytest-9.0.2.pyc
Normal file
BIN
tests/__pycache__/test_properties.cpython-312-pytest-9.0.2.pyc
Normal file
Binary file not shown.
BIN
tests/__pycache__/test_tools.cpython-312-pytest-9.0.2.pyc
Normal file
BIN
tests/__pycache__/test_tools.cpython-312-pytest-9.0.2.pyc
Normal file
Binary file not shown.
25
tests/test_agent.py
Normal file
25
tests/test_agent.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""Unit tests for agent initialization."""
|
||||
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import main
|
||||
|
||||
|
||||
class TestAgentInitialization:
|
||||
@patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"})
|
||||
def test_agent_has_all_four_tools(self):
|
||||
"""Agent should be initialized with all four file system tools."""
|
||||
agent = main.create_agent()
|
||||
# The agent's tools are accessible via the graph's nodes
|
||||
# create_agent stores tools in the agent; we can check
|
||||
# by inspecting the tool names from the agent's tool node.
|
||||
tool_node = agent.nodes.get("tools")
|
||||
assert tool_node is not None, "Agent should have a 'tools' node"
|
||||
|
||||
# The actual ToolNode is wrapped in a PregelNode; access via .bound
|
||||
tool_names = list(tool_node.bound.tools_by_name.keys())
|
||||
expected = {"read_file", "grep", "write_file", "list_dir", "replace_in_file"}
|
||||
assert set(tool_names) == expected, (
|
||||
f"Expected tools {expected}, got {set(tool_names)}"
|
||||
)
|
||||
40
tests/test_cli.py
Normal file
40
tests/test_cli.py
Normal file
@@ -0,0 +1,40 @@
|
||||
"""Unit tests for --workdir CLI argument handling."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class TestWorkdirCLI:
|
||||
def test_missing_workdir_argument(self):
|
||||
"""CLI should exit with error when --workdir is not provided."""
|
||||
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(self, tmp_path):
|
||||
"""CLI should exit with error when --workdir path doesn't exist."""
|
||||
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_not_directory(self, tmp_path):
|
||||
"""CLI should exit with error when --workdir is a file, not a directory."""
|
||||
file_path = tmp_path / "afile.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
|
||||
239
tests/test_llm.py
Normal file
239
tests/test_llm.py
Normal file
@@ -0,0 +1,239 @@
|
||||
"""Unit tests for the llm provider abstraction module."""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestDefaultProviderBehavior:
|
||||
"""3.1 - Default provider behavior: no env vars → ChatOpenAI with gpt-4o-mini."""
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_default_provider_returns_chatopenai(self, mock_openai):
|
||||
"""With no env vars set, create_model() should use ChatOpenAI."""
|
||||
mock_instance = MagicMock()
|
||||
mock_openai.return_value = mock_instance
|
||||
|
||||
env = {"PATH": os.environ.get("PATH", "")}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
result = create_model()
|
||||
|
||||
mock_openai.assert_called_once_with(model="gpt-4o-mini")
|
||||
assert result is mock_instance
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_default_model_is_gpt4o_mini(self, mock_openai):
|
||||
"""Default model name should be gpt-4o-mini when MODEL_NAME is not set."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
env = {"PATH": os.environ.get("PATH", "")}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
mock_openai.assert_called_once_with(model="gpt-4o-mini")
|
||||
|
||||
|
||||
class TestProviderDefaultModels:
|
||||
"""3.2 - Each provider's default model name and instance type."""
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_openai_default_model(self, mock_openai):
|
||||
"""OpenAI provider should default to gpt-4o-mini."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
with patch.dict(os.environ, {"LLM_PROVIDER": "openai"}, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
mock_openai.assert_called_once_with(model="gpt-4o-mini")
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_llama_server_default_model(self, mock_openai):
|
||||
"""Llama-server provider should default to local-model."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
mock_openai.assert_called_once()
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["model"] == "local-model"
|
||||
|
||||
@patch("llm.ChatBedrock")
|
||||
def test_bedrock_default_model(self, mock_bedrock):
|
||||
"""Bedrock provider should default to us.anthropic.claude-3-5-sonnet-20241022-v2:0."""
|
||||
mock_bedrock.return_value = MagicMock()
|
||||
|
||||
with patch.dict(os.environ, {"LLM_PROVIDER": "bedrock"}, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
mock_bedrock.assert_called_once()
|
||||
_, kwargs = mock_bedrock.call_args
|
||||
assert kwargs["model_id"] == "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
|
||||
|
||||
|
||||
class TestLlamaServerDefaults:
|
||||
"""3.3 - Llama-server defaults: URL, API key, model name."""
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_llama_server_default_url(self, mock_openai):
|
||||
"""Llama-server should default to http://localhost:8080/v1."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["base_url"] == "http://localhost:8080/v1"
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_llama_server_api_key(self, mock_openai):
|
||||
"""Llama-server should set api_key to 'not-needed'."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["api_key"] == "not-needed"
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_llama_server_default_model_name(self, mock_openai):
|
||||
"""Llama-server should default to 'local-model'."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["model"] == "local-model"
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_llama_server_custom_url(self, mock_openai):
|
||||
"""Llama-server should use LLAMA_SERVER_URL when set."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{"LLM_PROVIDER": "llama-server", "LLAMA_SERVER_URL": "http://myserver:9090/v1"},
|
||||
clear=True,
|
||||
):
|
||||
from llm import create_model
|
||||
|
||||
create_model()
|
||||
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["base_url"] == "http://myserver:9090/v1"
|
||||
|
||||
|
||||
class TestImportSideEffects:
|
||||
"""3.4 - Importing llm module does not create model instances."""
|
||||
|
||||
def test_import_does_not_call_constructors(self):
|
||||
"""Importing the llm module should not instantiate any models."""
|
||||
with patch("llm.ChatOpenAI") as mock_openai, \
|
||||
patch("llm.ChatBedrock") as mock_bedrock:
|
||||
# Force re-import by reloading
|
||||
import importlib
|
||||
import llm
|
||||
|
||||
importlib.reload(llm)
|
||||
|
||||
mock_openai.assert_not_called()
|
||||
mock_bedrock.assert_not_called()
|
||||
|
||||
def test_registry_and_defaults_are_dicts(self):
|
||||
"""PROVIDER_REGISTRY and DEFAULT_MODELS should be dicts at module level."""
|
||||
from llm import DEFAULT_MODELS, PROVIDER_REGISTRY
|
||||
|
||||
assert isinstance(PROVIDER_REGISTRY, dict)
|
||||
assert isinstance(DEFAULT_MODELS, dict)
|
||||
|
||||
def test_no_model_instances_at_module_level(self):
|
||||
"""No BaseChatModel instances should exist at module level."""
|
||||
import llm
|
||||
from langchain_core.language_models import BaseChatModel
|
||||
|
||||
for attr_name in dir(llm):
|
||||
attr = getattr(llm, attr_name)
|
||||
assert not isinstance(attr, BaseChatModel), (
|
||||
f"Module-level attribute '{attr_name}' is a model instance"
|
||||
)
|
||||
|
||||
|
||||
class TestProviderRegistry:
|
||||
"""3.5 - PROVIDER_REGISTRY exposes expected provider names."""
|
||||
|
||||
def test_registry_has_expected_providers(self):
|
||||
"""Registry should contain openai, llama-server, and bedrock."""
|
||||
from llm import PROVIDER_REGISTRY
|
||||
|
||||
expected = {"openai", "llama-server", "bedrock"}
|
||||
assert set(PROVIDER_REGISTRY.keys()) == expected
|
||||
|
||||
def test_registry_values_are_callable(self):
|
||||
"""All registry values should be callable factory functions."""
|
||||
from llm import PROVIDER_REGISTRY
|
||||
|
||||
for name, factory in PROVIDER_REGISTRY.items():
|
||||
assert callable(factory), f"Factory for '{name}' is not callable"
|
||||
|
||||
def test_registry_has_three_providers(self):
|
||||
"""Registry should have exactly 3 providers."""
|
||||
from llm import PROVIDER_REGISTRY
|
||||
|
||||
assert len(PROVIDER_REGISTRY) == 3
|
||||
|
||||
|
||||
class TestCreateAgentBackwardCompatibility:
|
||||
"""3.6 - create_agent() still registers all 5 tools after refactor."""
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_create_agent_has_all_five_tools(self, mock_openai):
|
||||
"""create_agent() should register read_file, grep, write_file, list_dir, replace_in_file."""
|
||||
mock_model = MagicMock()
|
||||
mock_openai.return_value = mock_model
|
||||
|
||||
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
|
||||
from main import create_agent
|
||||
|
||||
agent = create_agent()
|
||||
|
||||
tool_node = agent.nodes.get("tools")
|
||||
assert tool_node is not None, "Agent should have a 'tools' node"
|
||||
|
||||
tool_names = set(tool_node.bound.tools_by_name.keys())
|
||||
expected = {"read_file", "grep", "write_file", "list_dir", "replace_in_file"}
|
||||
assert tool_names == expected, f"Expected tools {expected}, got {tool_names}"
|
||||
|
||||
@patch("llm.ChatOpenAI")
|
||||
def test_create_agent_calls_create_model(self, mock_openai):
|
||||
"""create_agent() should use create_model() to get the LLM."""
|
||||
mock_openai.return_value = MagicMock()
|
||||
|
||||
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}), \
|
||||
patch("agent.create_model") as mock_create_model:
|
||||
mock_model = MagicMock()
|
||||
mock_model.bind_tools.return_value = MagicMock()
|
||||
mock_create_model.return_value = mock_model
|
||||
from main import create_agent
|
||||
|
||||
create_agent()
|
||||
|
||||
mock_create_model.assert_called_once()
|
||||
232
tests/test_llm_properties.py
Normal file
232
tests/test_llm_properties.py
Normal file
@@ -0,0 +1,232 @@
|
||||
"""Property-based tests for the LLM provider abstraction module.
|
||||
|
||||
Uses hypothesis to verify universal properties across many generated inputs.
|
||||
Each property test is tagged with its design document reference.
|
||||
"""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from hypothesis import given, settings, strategies as st, assume
|
||||
from langchain_core.language_models import BaseChatModel
|
||||
|
||||
from llm import PROVIDER_REGISTRY, DEFAULT_MODELS, create_model
|
||||
|
||||
|
||||
# ── Strategies ───────────────────────────────────────────────────────────────
|
||||
|
||||
registered_providers = st.sampled_from(list(PROVIDER_REGISTRY.keys()))
|
||||
|
||||
# Non-empty printable strings for model names
|
||||
model_name_strategy = st.text(
|
||||
alphabet=st.characters(whitelist_categories=("L", "N", "P", "S", "Z")),
|
||||
min_size=1,
|
||||
max_size=50,
|
||||
).filter(lambda s: s.strip() != "" and s.isprintable())
|
||||
|
||||
# Strings that are NOT registered provider names (exclude null bytes for env var compat)
|
||||
unknown_provider_strategy = st.text(
|
||||
alphabet=st.characters(blacklist_characters="\x00"),
|
||||
min_size=0,
|
||||
max_size=50,
|
||||
).filter(lambda s: s not in PROVIDER_REGISTRY)
|
||||
|
||||
# Non-empty strings for URL and region values (exclude null bytes for env var compat)
|
||||
non_empty_text = st.text(
|
||||
alphabet=st.characters(blacklist_characters="\x00"),
|
||||
min_size=1,
|
||||
max_size=100,
|
||||
).filter(lambda s: s.strip() != "")
|
||||
|
||||
|
||||
# ── Property 1: Provider registry produces valid models ──────────────────────
|
||||
|
||||
|
||||
class TestProperty1ProviderRegistryProducesValidModels:
|
||||
"""Feature: llm-provider-abstraction, Property 1: Provider registry produces valid models
|
||||
|
||||
For any registered provider name, setting LLM_PROVIDER and calling
|
||||
create_model() returns an instance of BaseChatModel.
|
||||
|
||||
**Validates: Requirements 1.1, 2.1, 6.1**
|
||||
"""
|
||||
|
||||
@settings(max_examples=10)
|
||||
@given(provider=registered_providers)
|
||||
def test_registered_provider_returns_base_chat_model(self, provider):
|
||||
"""For any registered provider, create_model returns BaseChatModel."""
|
||||
mock_instance = MagicMock(spec=BaseChatModel)
|
||||
|
||||
with patch("llm.ChatOpenAI", return_value=mock_instance), \
|
||||
patch("llm.ChatBedrock", return_value=mock_instance), \
|
||||
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
|
||||
result = create_model()
|
||||
|
||||
assert isinstance(result, BaseChatModel)
|
||||
|
||||
|
||||
# ── Property 2: Model name resolution ────────────────────────────────────────
|
||||
|
||||
|
||||
class TestProperty2ModelNameResolution:
|
||||
"""Feature: llm-provider-abstraction, Property 2: Model name resolution
|
||||
|
||||
For any provider × model name string, the model uses that name.
|
||||
Without MODEL_NAME, uses default from DEFAULT_MODELS.
|
||||
|
||||
**Validates: Requirements 2.3, 2.4**
|
||||
"""
|
||||
|
||||
@settings(max_examples=10)
|
||||
@given(provider=registered_providers, model_name=model_name_strategy)
|
||||
def test_custom_model_name_is_used(self, provider, model_name):
|
||||
"""For any provider and model name, the model is configured with that name."""
|
||||
mock_instance = MagicMock(spec=BaseChatModel)
|
||||
|
||||
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
|
||||
patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
|
||||
patch.dict(os.environ, {"LLM_PROVIDER": provider, "MODEL_NAME": model_name}, clear=True):
|
||||
create_model()
|
||||
|
||||
if provider in ("openai", "llama-server"):
|
||||
mock_openai.assert_called_once()
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["model"] == model_name
|
||||
else:
|
||||
mock_bedrock.assert_called_once()
|
||||
_, kwargs = mock_bedrock.call_args
|
||||
assert kwargs["model_id"] == model_name
|
||||
|
||||
@settings(max_examples=10)
|
||||
@given(provider=registered_providers)
|
||||
def test_default_model_name_when_not_set(self, provider):
|
||||
"""Without MODEL_NAME, uses default from DEFAULT_MODELS."""
|
||||
mock_instance = MagicMock(spec=BaseChatModel)
|
||||
expected_default = DEFAULT_MODELS[provider]
|
||||
|
||||
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
|
||||
patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
|
||||
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
|
||||
create_model()
|
||||
|
||||
if provider in ("openai", "llama-server"):
|
||||
mock_openai.assert_called_once()
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["model"] == expected_default
|
||||
else:
|
||||
mock_bedrock.assert_called_once()
|
||||
_, kwargs = mock_bedrock.call_args
|
||||
assert kwargs["model_id"] == expected_default
|
||||
|
||||
|
||||
# ── Property 3: Unknown provider error message ───────────────────────────────
|
||||
|
||||
|
||||
class TestProperty3UnknownProviderErrorMessage:
|
||||
"""Feature: llm-provider-abstraction, Property 3: Unknown provider error message
|
||||
|
||||
For any string NOT in PROVIDER_REGISTRY, ValueError contains the invalid
|
||||
name and all valid provider names.
|
||||
|
||||
**Validates: Requirements 2.5, 8.1**
|
||||
"""
|
||||
|
||||
@settings(max_examples=10)
|
||||
@given(invalid_provider=unknown_provider_strategy)
|
||||
def test_unknown_provider_raises_valueerror_with_details(self, invalid_provider):
|
||||
"""For any non-registry string, ValueError contains invalid name and all valid names."""
|
||||
with patch.dict(os.environ, {"LLM_PROVIDER": invalid_provider}, clear=True):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
create_model()
|
||||
|
||||
error_msg = str(exc_info.value)
|
||||
# Error message should contain the invalid provider name
|
||||
assert invalid_provider in error_msg
|
||||
# Error message should contain all valid provider names
|
||||
for valid_name in PROVIDER_REGISTRY.keys():
|
||||
assert valid_name in error_msg
|
||||
|
||||
|
||||
# ── Property 4: Llama server URL configuration ───────────────────────────────
|
||||
|
||||
|
||||
class TestProperty4LlamaServerUrlConfiguration:
|
||||
"""Feature: llm-provider-abstraction, Property 4: Llama server URL configuration
|
||||
|
||||
For any URL string in LLAMA_SERVER_URL, the ChatOpenAI instance gets
|
||||
that base_url.
|
||||
|
||||
**Validates: Requirements 4.2**
|
||||
"""
|
||||
|
||||
@settings(max_examples=10)
|
||||
@given(url=non_empty_text)
|
||||
def test_llama_server_uses_configured_url(self, url):
|
||||
"""For any URL string in LLAMA_SERVER_URL, model base_url matches."""
|
||||
mock_instance = MagicMock(spec=BaseChatModel)
|
||||
|
||||
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
|
||||
patch.dict(os.environ, {"LLM_PROVIDER": "llama-server", "LLAMA_SERVER_URL": url}, clear=True):
|
||||
create_model()
|
||||
|
||||
mock_openai.assert_called_once()
|
||||
_, kwargs = mock_openai.call_args
|
||||
assert kwargs["base_url"] == url
|
||||
|
||||
|
||||
# ── Property 5: Bedrock region configuration ─────────────────────────────────
|
||||
|
||||
|
||||
class TestProperty5BedrockRegionConfiguration:
|
||||
"""Feature: llm-provider-abstraction, Property 5: Bedrock region configuration
|
||||
|
||||
For any region string in AWS_REGION, ChatBedrock gets that region.
|
||||
|
||||
**Validates: Requirements 5.4**
|
||||
"""
|
||||
|
||||
@settings(max_examples=10)
|
||||
@given(region=non_empty_text)
|
||||
def test_bedrock_uses_configured_region(self, region):
|
||||
"""For any region string in AWS_REGION, model uses that region."""
|
||||
mock_instance = MagicMock(spec=BaseChatModel)
|
||||
|
||||
with patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
|
||||
patch.dict(os.environ, {"LLM_PROVIDER": "bedrock", "AWS_REGION": region}, clear=True):
|
||||
create_model()
|
||||
|
||||
mock_bedrock.assert_called_once()
|
||||
_, kwargs = mock_bedrock.call_args
|
||||
assert kwargs["region_name"] == region
|
||||
|
||||
|
||||
# ── Property 6: Factory exception propagation ────────────────────────────────
|
||||
|
||||
|
||||
class TestProperty6FactoryExceptionPropagation:
|
||||
"""Feature: llm-provider-abstraction, Property 6: Factory exception propagation
|
||||
|
||||
For any exception raised by a factory, create_model() propagates it unchanged.
|
||||
|
||||
**Validates: Requirements 8.2**
|
||||
"""
|
||||
|
||||
@settings(max_examples=10)
|
||||
@given(
|
||||
provider=registered_providers,
|
||||
error_msg=st.text(min_size=1, max_size=100).filter(lambda s: s.strip() != ""),
|
||||
)
|
||||
def test_factory_exception_propagates_unchanged(self, provider, error_msg):
|
||||
"""For any exception from factory, it propagates unchanged."""
|
||||
original_exception = RuntimeError(error_msg)
|
||||
|
||||
# Patch the factory in the registry to raise the exception
|
||||
with patch.dict(PROVIDER_REGISTRY, {provider: MagicMock(side_effect=original_exception)}), \
|
||||
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
create_model()
|
||||
|
||||
# Verify the exact same exception propagated
|
||||
assert exc_info.value is original_exception
|
||||
assert str(exc_info.value) == error_msg
|
||||
475
tests/test_properties.py
Normal file
475
tests/test_properties.py
Normal file
@@ -0,0 +1,475 @@
|
||||
"""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
|
||||
237
tests/test_tools.py
Normal file
237
tests/test_tools.py
Normal file
@@ -0,0 +1,237 @@
|
||||
"""Unit tests for file system tools and validate_path."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import tools
|
||||
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def _set_workdir(tmp_path: Path):
|
||||
"""Set tools.WORKDIR to the given tmp_path for testing."""
|
||||
tools.set_workdir(tmp_path.resolve())
|
||||
|
||||
|
||||
# ── 6.1 validate_path ──────────────────────────────────────────────────────
|
||||
|
||||
class TestValidatePath:
|
||||
def test_valid_relative_path(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "hello.txt").write_text("hi")
|
||||
result = tools.validate_path("hello.txt")
|
||||
assert result == str(tmp_path.resolve() / "hello.txt")
|
||||
|
||||
def test_valid_nested_path(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
sub = tmp_path / "a" / "b"
|
||||
sub.mkdir(parents=True)
|
||||
(sub / "file.txt").write_text("data")
|
||||
result = tools.validate_path("a/b/file.txt")
|
||||
assert result == str(sub.resolve() / "file.txt")
|
||||
|
||||
def test_dot_dot_traversal_rejected(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
import pytest
|
||||
with pytest.raises(ValueError, match="Access denied"):
|
||||
tools.validate_path("../outside.txt")
|
||||
|
||||
def test_absolute_path_outside_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
import pytest
|
||||
with pytest.raises(ValueError, match="Access denied"):
|
||||
tools.validate_path("/etc/passwd")
|
||||
|
||||
def test_symlink_escaping_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
# Create a directory outside workdir
|
||||
outside = tmp_path.parent / "outside_dir"
|
||||
outside.mkdir(exist_ok=True)
|
||||
(outside / "secret.txt").write_text("secret")
|
||||
|
||||
# Create symlink inside workdir pointing outside
|
||||
link = tmp_path / "escape_link"
|
||||
link.symlink_to(outside)
|
||||
|
||||
import pytest
|
||||
with pytest.raises(ValueError, match="Access denied"):
|
||||
tools.validate_path("escape_link/secret.txt")
|
||||
|
||||
def test_absolute_path_inside_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "inside.txt").write_text("ok")
|
||||
abs_path = str(tmp_path / "inside.txt")
|
||||
result = tools.validate_path(abs_path)
|
||||
assert result == str((tmp_path / "inside.txt").resolve())
|
||||
|
||||
|
||||
# ── 6.3 read_file ──────────────────────────────────────────────────────────
|
||||
|
||||
class TestReadFile:
|
||||
def test_read_existing_file(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "test.txt").write_text("hello world")
|
||||
result = tools.read_file.invoke({"path": "test.txt"})
|
||||
assert result == "hello world"
|
||||
|
||||
def test_read_missing_file(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.read_file.invoke({"path": "nonexistent.txt"})
|
||||
assert "Error: File not found" in result
|
||||
|
||||
def test_read_empty_file(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "empty.txt").write_text("")
|
||||
result = tools.read_file.invoke({"path": "empty.txt"})
|
||||
assert result == ""
|
||||
|
||||
def test_read_file_outside_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.read_file.invoke({"path": "../outside.txt"})
|
||||
assert "Access denied" in result
|
||||
|
||||
|
||||
# ── 6.4 grep ────────────────────────────────────────────────────────────────
|
||||
|
||||
class TestGrep:
|
||||
def test_matches_found(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "data.txt").write_text("foo bar\nbaz\nfoo again")
|
||||
result = tools.grep.invoke({"pattern": "foo"})
|
||||
assert "data.txt" in result
|
||||
assert "foo bar" in result
|
||||
assert "foo again" in result
|
||||
|
||||
def test_no_matches(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "data.txt").write_text("hello world")
|
||||
result = tools.grep.invoke({"pattern": "zzz_missing"})
|
||||
assert "No matches found" in result
|
||||
|
||||
def test_search_specific_directory(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
sub = tmp_path / "subdir"
|
||||
sub.mkdir()
|
||||
(sub / "a.txt").write_text("needle here")
|
||||
(tmp_path / "b.txt").write_text("needle there")
|
||||
result = tools.grep.invoke({"pattern": "needle", "path": "subdir"})
|
||||
assert "a.txt" in result
|
||||
# b.txt is outside the searched subdir
|
||||
assert "b.txt" not in result
|
||||
|
||||
def test_grep_path_outside_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.grep.invoke({"pattern": "x", "path": "../../etc"})
|
||||
assert "Access denied" in result
|
||||
|
||||
|
||||
# ── 6.5 write_file ─────────────────────────────────────────────────────────
|
||||
|
||||
class TestWriteFile:
|
||||
def test_write_new_file(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.write_file.invoke({"path": "new.txt", "content": "hello"})
|
||||
assert "Successfully wrote" in result
|
||||
assert (tmp_path / "new.txt").read_text() == "hello"
|
||||
|
||||
def test_overwrite_existing_file(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "exist.txt").write_text("old")
|
||||
result = tools.write_file.invoke({"path": "exist.txt", "content": "new"})
|
||||
assert "Successfully wrote" in result
|
||||
assert (tmp_path / "exist.txt").read_text() == "new"
|
||||
|
||||
def test_write_creates_nested_dirs(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.write_file.invoke(
|
||||
{"path": "a/b/c/deep.txt", "content": "deep"}
|
||||
)
|
||||
assert "Successfully wrote" in result
|
||||
assert (tmp_path / "a" / "b" / "c" / "deep.txt").read_text() == "deep"
|
||||
|
||||
def test_write_path_outside_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.write_file.invoke(
|
||||
{"path": "../../evil.txt", "content": "bad"}
|
||||
)
|
||||
assert "Access denied" in result
|
||||
|
||||
|
||||
# ── 6.6 list_dir ───────────────────────────────────────────────────────────
|
||||
|
||||
class TestListDir:
|
||||
def test_list_valid_directory(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "file.txt").write_text("x")
|
||||
(tmp_path / "subdir").mkdir()
|
||||
result = tools.list_dir.invoke({"path": "."})
|
||||
assert "[FILE] file.txt" in result
|
||||
assert "[DIR] subdir" in result
|
||||
|
||||
def test_list_missing_path(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.list_dir.invoke({"path": "nonexistent"})
|
||||
assert "Error: Path not found" in result
|
||||
|
||||
def test_list_file_path(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "afile.txt").write_text("x")
|
||||
result = tools.list_dir.invoke({"path": "afile.txt"})
|
||||
assert "Error: Not a directory" in result
|
||||
|
||||
def test_list_path_outside_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.list_dir.invoke({"path": "../../"})
|
||||
assert "Access denied" in result
|
||||
|
||||
|
||||
# ── 6.8 replace_in_file ────────────────────────────────────────────────────
|
||||
|
||||
class TestReplaceInFile:
|
||||
def test_replace_single_occurrence(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "test.txt").write_text("hello world")
|
||||
result = tools.replace_in_file.invoke(
|
||||
{"path": "test.txt", "search": "world", "replace": "universe"}
|
||||
)
|
||||
assert "Successfully replaced 1 occurrence" in result
|
||||
assert (tmp_path / "test.txt").read_text() == "hello universe"
|
||||
|
||||
def test_replace_multiple_occurrences(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "test.txt").write_text("foo bar foo baz foo")
|
||||
result = tools.replace_in_file.invoke(
|
||||
{"path": "test.txt", "search": "foo", "replace": "qux"}
|
||||
)
|
||||
assert "Successfully replaced 3 occurrence" in result
|
||||
assert (tmp_path / "test.txt").read_text() == "qux bar qux baz qux"
|
||||
|
||||
def test_replace_not_found(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "test.txt").write_text("hello world")
|
||||
result = tools.replace_in_file.invoke(
|
||||
{"path": "test.txt", "search": "missing", "replace": "new"}
|
||||
)
|
||||
assert "Error: Search text not found" in result
|
||||
|
||||
def test_replace_missing_file(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.replace_in_file.invoke(
|
||||
{"path": "nonexistent.txt", "search": "a", "replace": "b"}
|
||||
)
|
||||
assert "Error: File not found" in result
|
||||
|
||||
def test_replace_path_outside_workdir(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
result = tools.replace_in_file.invoke(
|
||||
{"path": "../outside.txt", "search": "a", "replace": "b"}
|
||||
)
|
||||
assert "Access denied" in result
|
||||
|
||||
def test_replace_on_directory(self, tmp_path):
|
||||
_set_workdir(tmp_path)
|
||||
(tmp_path / "subdir").mkdir()
|
||||
result = tools.replace_in_file.invoke(
|
||||
{"path": "subdir", "search": "a", "replace": "b"}
|
||||
)
|
||||
assert "Error: Not a file" in result
|
||||
Reference in New Issue
Block a user