Skip to content

SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]

Save before removing split_actions

Kilian Lieret8dd7fb203727
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 34796044..d98c7ea6 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -881,7 +881,8 @@ class Agent:
return observation, done
def _run_step(self, observation: str | None) -> tuple[str | None, bool]:
- """Run a step of the agent (forward, execute, and save).
+ """Run a step of the agent: Forward the last observation to the LM,
+ then execute the action and save the trajectory.
Returns:
observation: Observation
@@ -903,6 +904,7 @@ class Agent:
done = False
observations: list[str | None] = list()
execution_t0 = time.perf_counter()
+ breakpoint()
for sub_action in self.split_actions(run_action):
observation, done = self._run_sub_action(sub_action)
# If the last sub-action is done, the observation is not
diff --git a/sweagent/agent/summarizer.py b/sweagent/agent/summarizer.py
index 3e3a0a4c..8f8950ef 100644
--- a/sweagent/agent/summarizer.py
+++ b/sweagent/agent/summarizer.py
@@ -10,7 +10,6 @@ from typing import Any
from sweagent.agent.models import APIStats, BaseModel, ContextWindowExceededError, ModelArguments
from sweagent.environment.swe_env import SWEEnv
-from sweagent.environment.utils import copy_anything_to_container
from sweagent.utils.log import get_logger
diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.py
index ecdcaccb..bcccb822 100644
--- a/sweagent/environment/config/problem_statement.py
+++ b/sweagent/environment/config/problem_statement.py
@@ -54,8 +54,8 @@ class GithubIssue(BaseModel):
@property
def id(self) -> str:
- org, repo, issue = self.issue_url.split("/")[-3:]
- return f"{org}__{repo}-i{issue}"
+ owner, repo, issue_number = _parse_gh_issue_url(self.issue_url)
+ return f"{owner}__{repo}-i{issue_number}"
def get_problem_statement(self) -> str:
owner, repo, issue_number = _parse_gh_issue_url(self.issue_url)
diff --git a/sweagent/run/hooks/open_pr.py b/sweagent/run/hooks/open_pr.py
index dc9f0a39..c98392b7 100644
--- a/sweagent/run/hooks/open_pr.py
+++ b/sweagent/run/hooks/open_pr.py
@@ -2,9 +2,8 @@ from typing import Any
from pydantic import BaseModel
-from sweagent.environment.utils import InvalidGithubURL
from sweagent.run.hooks.abstract import RunHook
-from sweagent.utils.github import _get_associated_commit_urls, _get_gh_issue_data, _parse_gh_issue_url
+from sweagent.utils.github import InvalidGithubURL, _get_associated_commit_urls, _get_gh_issue_data, _parse_gh_issue_url
from sweagent.utils.log import get_logger
# todo: Move this to run.py
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index f54fa33e..717953e9 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -24,10 +24,6 @@ class RunSingleActionConfig(BaseModel):
pr_config: OpenPRConfig = Field(default_factory=OpenPRConfig)
# When working with local repository: Apply patch
apply_patch_locally: bool = False
- # todo: implement this
- raise_exceptions: bool = False
- # todo: implement this
- print_config: bool = True
class RunSingleConfig(BaseSettings):
@@ -37,6 +33,10 @@ class RunSingleConfig(BaseSettings):
)
traj_dir: str = "."
actions: RunSingleActionConfig = Field(default_factory=RunSingleActionConfig)
+ # todo: implement this
+ raise_exceptions: bool = True
+ # todo: implement this
+ print_config: bool = True
class RunSingle:
diff --git a/sweagent/utils/github.py b/sweagent/utils/github.py
index 31247d28..cb319235 100644
--- a/sweagent/utils/github.py
+++ b/sweagent/utils/github.py
@@ -19,6 +19,11 @@ def _is_github_repo_url(data_path: str) -> bool:
return GITHUB_REPO_URL_PATTERN.search(data_path) is not None
+def _is_github_issue_url(data_path: str) -> bool:
+ """Check if data_path is an URL pointing to a github issue"""
+ return GITHUB_ISSUE_URL_PATTERN.search(data_path) is not None
+
+
def _get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):
"""Get commit object from github api
diff --git a/tests/test_replay.py b/tests/_test_replay.py
similarity index 100%
rename from tests/test_replay.py
rename to tests/_test_replay.py
diff --git a/tests/test_env.py b/tests/test_env.py
index d4d3a973..a4a38659 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -4,6 +4,7 @@ from pathlib import Path
from unittest import mock
import pytest
+from swerex.runtime.abstract import CommandTimeoutError
from sweagent.environment.hooks.abstract import EnvHook
@@ -44,3 +45,39 @@ def test_env_with_hook(test_env_args):
with swe_env_context(test_env_args) as env:
env.add_hook(EnvHook())
env.reset()
+
+
+def test_env_communicate_with_handling(test_env_args):
+ with swe_env_context(test_env_args) as env:
+ env.reset()
+ env.communicate_with_handling("echo 'hello world'", error_msg="Failed to echo", timeout_duration=1)
+
+
+def test_env_communicate_with_handling_timeout(test_env_args):
+ with swe_env_context(test_env_args) as env:
+ env.reset()
+ with pytest.raises(CommandTimeoutError):
+ env.communicate_with_handling("sleep 10", error_msg="Failed to sleep", timeout_duration=0.2)
+
+
+def test_env_step(test_env_args):
+ with swe_env_context(test_env_args) as env:
+ env.reset()
+ env.step(action="ls")
+
+
+def test_env_step_exit_forfeit(test_env_args):
+ with swe_env_context(test_env_args) as env:
+ env.reset()
+ env.step(action="exit_forfeit")
+
+
+def test_env_step_exit_cost(test_env_args):
+ with swe_env_context(test_env_args) as env:
+ env.reset()
+ env.step(action="exit_cost")
diff --git a/tests/test_env_utils.py b/tests/test_env_utils.py
index 6308903f..fa28f1f9 100644
--- a/tests/test_env_utils.py
+++ b/tests/test_env_utils.py
@@ -1,18 +1,14 @@
from __future__ import annotations
-import hashlib
import os
import subprocess
import pytest
-from sweagent.environment.utils import (
- InvalidGithubURL,
- get_instances,
-)
from sweagent.run.hooks.open_pr import _remove_triple_backticks, format_trajectory_markdown
from sweagent.utils.config import keys_config
from sweagent.utils.github import (
+ InvalidGithubURL,
_get_associated_commit_urls,
_is_github_issue_url,
_is_github_repo_url,
@@ -87,20 +83,6 @@ def test_get_associated_commit_urls():
assert len(assoc) > 0
-def test_get_instance_gh_issue():
- instance = get_instances("https://github.com/swe-agent/test-repo/issues/1", **_TOKEN)[0]
- compare_with = {
- "repo": "swe-agent/test-repo",
- "instance_id": "swe-agent__test-repo-i1",
- "repo_type": "github",
- }
- for key in compare_with:
- assert instance[key] == compare_with[key]
- assert "SyntaxError" in instance["problem_statement"]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
-
-
def clone_repo(tmp_path, repo_url):
cmd = [
"git",
@@ -108,92 +90,3 @@ def clone_repo(tmp_path, repo_url):
repo_url,
]
subprocess.run(cmd, check=True, cwd=tmp_path)
-
-
-def test_get_instance_gh_issue_local_repo(tmp_path):
- clone_repo(tmp_path, "https://github.com/swe-agent/test-repo/")
- instance = get_instances(
- file_path="https://github.com/swe-agent/test-repo/issues/1",
- repo_path=str(tmp_path / "test-repo"),
- **_TOKEN,
- )[0]
- compare_with = {
- "repo": str(tmp_path.resolve() / "test-repo"),
- "repo_type": "local",
- "instance_id": "swe-agent__test-repo-i1",
- }
- for key in compare_with:
- assert instance[key] == compare_with[key]
- assert "SyntaxError" in instance["problem_statement"]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
-
-
-def test_get_instance_local_issue_local_repo(tmp_path):
- clone_repo(tmp_path, "https://github.com/swe-agent/test-repo/")
- issue_path = tmp_path / "issue.txt"
- issue_path.write_text("asdf")
- instance = get_instances(
- file_path=str(issue_path),
- repo_path=str(tmp_path / "test-repo"),
- )[0]
- compare_with = {
- "repo": str(tmp_path.resolve() / "test-repo"),
- "repo_type": "local",
- "instance_id": hashlib.sha256(b"asdf").hexdigest()[:6],
- "problem_statement": "asdf",
- }
- for key in compare_with:
- assert instance[key] == compare_with[key]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
-
-
-def test_get_instance_gh_issue_gh_repo(tmp_path):
- instance = get_instances(
- file_path="https://github.com/swe-agent/test-repo/issues/1",
- repo_path="https://github.com/princeton-nlp/SWE-agent",
- **_TOKEN,
- )[0]
- compare_with = {
- "repo": "princeton-nlp/SWE-agent",
- "repo_type": "github",
- "instance_id": "swe-agent__test-repo-i1",
- }
- for key in compare_with:
- assert instance[key] == compare_with[key]
- assert "SyntaxError" in instance["problem_statement"]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
-
-
-def test_get_instance_text_issue_gh_repo(tmp_path):
- instance = get_instances(
- file_path="text://this is a test",
- repo_path="https://github.com/princeton-nlp/SWE-agent",
- **_TOKEN,
- )[0]
- compare_with = {
- "repo": "princeton-nlp/SWE-agent",
- "repo_type": "github",
- "problem_statement": "this is a test",
- }
- for key in compare_with:
- assert instance[key] == compare_with[key]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
-
-
-def test_load_instances(test_data_path, caplog):
- test_data_sources = test_data_path / "data_sources"
- examples = [example for example in test_data_sources.iterdir() if example.is_file()]
- for example in examples:
- get_instances(file_path=str(example), **_TOKEN)
-
-
-def test_load_ctf_instances(test_data_path, caplog):
- test_data_sources = test_data_path / "data_sources" / "ctf"
- examples = list(test_data_sources.glob("**/challenge.json"))
- for example in examples:
- get_instances(file_path=str(example), repo_path=str(example.parent))
diff --git a/tests/test_models.py b/tests/test_models.py
index ac3f57c8..3d1ae641 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -34,9 +34,9 @@ TEST_HISTORY = [{"role": "system", "content": "Hello, how are you?"}]
def test_openai_model(openai_mock_client):
for model_name in list(OpenAIModel.MODELS) + list(OpenAIModel.SHORTCUTS):
- TEST_MODEL_ARGUMENTS = ModelArguments(model_name)
+ model_args = ModelArguments(name=model_name)
with patch("sweagent.agent.models.keys_config"), patch("sweagent.agent.models.OpenAI"):
- model = OpenAIModel(TEST_MODEL_ARGUMENTS, [])
+ model = OpenAIModel(model_args, [])
model.client = openai_mock_client
model.query(TEST_HISTORY)
@@ -44,9 +44,9 @@ def test_openai_model(openai_mock_client):
# Test groq models
def test_groq_model(openai_mock_client):
for model_name in list(GroqModel.MODELS) + list(GroqModel.SHORTCUTS):
- TEST_MODEL_ARGUMENTS = ModelArguments(model_name)
+ model_args = ModelArguments(name=model_name)
with patch("sweagent.agent.models.keys_config"), patch("sweagent.agent.models.Groq"):
- model = GroqModel(TEST_MODEL_ARGUMENTS, [])
+ model = GroqModel(model_args, [])
model.client = openai_mock_client
model.query(TEST_HISTORY)
@@ -57,6 +57,6 @@ def test_together_model(mock_together_response, model_name):
mock_together.version = "1.1.0"
mock_together.Complete.create.return_value = mock_together_response
- model_args = ModelArguments(model_name)
+ model_args = ModelArguments(name=model_name)
model = TogetherModel(model_args, [])
model.query(TEST_HISTORY)
diff --git a/tests/test_replay_ctf.py b/tests/test_replay_ctf.py
deleted file mode 100644
index 75b1b8a4..00000000
--- a/tests/test_replay_ctf.py
+++ /dev/null
@@ -1,102 +0,0 @@
-from __future__ import annotations
-
-import copy
-from typing import Any
-
-import pytest
-
-from run_replay import get_args, main
-
-LOG_NOT_CONTAINS_DEFAULT = [
- "Traceback",
- "Exception",
- "socket.gaierror",
-]
-
-
-class ReplayRunValidator:
- def __init__(
- self,
- *,
- log_contains: list[str] | None = None,
- log_not_contains: list[str] | None = None,
- expected_traj: str | None = None,
- ):
- if log_contains is None:
- log_contains = []
- if log_not_contains is None:
- log_not_contains = copy.copy(LOG_NOT_CONTAINS_DEFAULT)
- self._log_contains = log_contains
- self._log_not_contains = log_not_contains + LOG_NOT_CONTAINS_DEFAULT
- self._expected_traj = expected_traj
-
- def _sanitize_observation(self, observation: str) -> str:
- # exclude everything that looks like a path
- return "\n".join(line for line in observation.splitlines() if "/" not in line).strip()
-
- def _sanitize_traj(self, traj: dict[str, Any]) -> dict[str, Any]:
- traj = copy.deepcopy(traj)
- # can restore later
- observations = [self._sanitize_observation(t["observation"]) for t in traj["trajectory"]]
- return {"trajectory": observations}
-
- def __call__(self, stdout: str, traj: str | None = None) -> None:
- for log in self._log_contains:
- assert log in stdout, log
- for log in self._log_not_contains:
- assert log not in stdout, log
- if self._expected_traj is not None:
- assert traj == self._expected_traj
-
-
-_REPLAY_TESTS = {
- "pwn/warmup.traj": ReplayRunValidator(
- log_contains=[
- "File updated.",
- "Opening connection to pwn.chal.csaw.io on port 8000: Done",
- "Receiving all data",
- ],
- ),
- "forensics/flash.traj": ReplayRunValidator(
- log_contains=["the black flag waved night and day from the"],
- ),
- # "web/i_got_id_demo.traj": r"4365",
- "misc/networking_1.traj": ReplayRunValidator(
- log_contains=["Password: "],
- ),
-}
-
-
- "traj_rel_path",
- ["pwn/warmup.traj", "forensics/flash.traj", "web/i_got_id_demo.traj", "rev/rock.traj", "misc/networking_1.traj"],
-)
-def test_ctf_traj_replay(test_ctf_trajectories_path, traj_rel_path, ctf_data_path, capsys):
- # if sys.platform == "darwin" and traj_rel_path in ["pwn/warmup.traj", "rev/rock.traj"]:
- # pytest.skip("Skipping test on macOS")
- traj_path = test_ctf_trajectories_path / traj_rel_path
- challenge_dir = ctf_data_path / traj_rel_path.removesuffix(".traj")
- assert challenge_dir.is_dir()
- data_path = challenge_dir / "challenge.json"
- assert data_path.is_file()
- assert traj_path.is_file()
- args = [
- "--traj_path",
- str(traj_path),
- "--data_path",
- str(data_path),
- "--repo_path",
- str(challenge_dir),
- "--config_file",
- "config/default_ctf.yaml",
- "--raise_exceptions",
- "--noprint_config",
- "--ctf",
- ]
- args, remaining_args = get_args(args)
- main(**vars(args), forward_args=remaining_args)
- captured = capsys.readouterr()
- if traj_rel_path in _REPLAY_TESTS:
- _REPLAY_TESTS[traj_rel_path](stdout=captured.out)
diff --git a/tests/test_run.py b/tests/test_run.py
index d9c4021d..86464748 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -1,238 +1,46 @@
from __future__ import annotations
-import dataclasses
-import json
-import logging
-import os
import subprocess
-from pathlib import Path
from typing import Any
import pytest
-import docker
-from run import Main, ScriptArguments
-from sweagent.agent.agents import Agent, AgentConfig, AgentHook
+from sweagent.agent.agents import AgentConfig
from sweagent.agent.models import ModelArguments
-from sweagent.environment.swe_env import EnvironmentInstanceConfig, SWEEnv
+from sweagent.environment.swe_env import EnvironmentInstanceConfig
from sweagent.run.hooks.abstract import RunHook
-from sweagent.run.hooks.open_pr import OpenPRHook
-from sweagent.run.run_single import RunSingleActionConfig
+from sweagent.run.run_single import RunSingle, RunSingleConfig
@pytest.mark.slow
def test_run_cli_help():
args = [
"python",
- "run.py",
+ "sweagent/run/run_single.py",
"--help",
]
subprocess.run(args, check=True)
-def open_pr_hook_init_for_sop():
- hook = OpenPRHook()
- hook._token = os.environ.get("GITHUB_TOKEN", "")
- hook._data_path = "https://github.com/swe-agent/test-repo/issues/1"
- hook._open_pr = True
- hook._skip_if_commits_reference_issue = True
- return hook
-
-
-def info_dict():
- return {
- "submission": "asdf",
- "exit_status": "submitted",
- }
-
-
-def test_should_open_pr_fail_submission(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- info_dict["submission"] = None
- assert not hook.should_open_pr(info_dict)
-
-
-def test_should_open_pr_fail_exit(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- info_dict["exit_status"] = "fail"
- assert not hook.should_open_pr(info_dict)
-
-
-def test_should_open_pr_fail_invalid_url(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- hook._data_path = "asdf"
- assert not hook.should_open_pr(info_dict)
-
-
-def test_should_open_pr_fail_closed(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- hook._data_path = "https://github.com/swe-agent/test-repo/issues/16"
- assert not hook.should_open_pr(info_dict)
-
-
-def test_should_open_pr_fail_assigned(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- hook._data_path = "https://github.com/swe-agent/test-repo/issues/17"
- assert not hook.should_open_pr(info_dict)
-
-
-def test_should_open_pr_fail_locked(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- hook._data_path = "https://github.com/swe-agent/test-repo/issues/18"
- assert not hook.should_open_pr(info_dict)
-
-
-def test_should_open_pr_fail_has_pr(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- hook._data_path = "https://github.com/swe-agent/test-repo/issues/19"
- assert not hook.should_open_pr(info_dict)
-
-
-def test_should_open_pr_success_has_pr_override(open_pr_hook_init_for_sop, info_dict):
- hook = open_pr_hook_init_for_sop
- hook._data_path = "https://github.com/swe-agent/test-repo/issues/19"
- hook._skip_if_commits_reference_issue = False
- assert hook.should_open_pr(info_dict)
-
-
class RaisesExceptionHook(RunHook):
def on_instance_start(self, *, index: int, instance: dict[str, Any]):
msg = "test exception"
raise ValueError(msg)
-def test_script_args():
- return ScriptArguments(
- suffix="",
- environment=EnvironmentInstanceConfig(
- image_name="sweagent/swe-agent:latest",
- data_path="https://github.com/swe-agent/test-repo/issues/1",
- split="dev",
- verbose=True,
- install_environment=True,
- ),
- skip_existing=False,
- agent=AgentConfig(
- model=ModelArguments(
- name="instant_empty_submit",
- ),
- ),
- actions=RunSingleActionConfig(open_pr=False, skip_if_commits_reference_issue=True),
- raise_exceptions=True,
- print_config=False,
- )
-
-
@pytest.mark.slow
-def test_exception_raised(test_script_args: ScriptArguments):
- assert test_script_args.raise_exceptions
- main = Main(test_script_args)
- main.add_hook(RaisesExceptionHook())
+def test_run_single_raises_exception():
+ rs = RunSingle.from_config(RunSingleConfig())
+ rs.add_hook(RaisesExceptionHook())
with pytest.raises(ValueError, match="test exception"):
- main.main()
-
-
-class CreateFakeLogFile(RunHook):
- """Testing the skip functionality"""
-
- def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
- self._traj_dir = traj_dir
- (traj_dir / "args.yaml").write_text("asdf")
-
- def on_instance_start(self, *, index: int, instance: dict[str, Any]):
- instance_id = instance["instance_id"]
- dct = {
- "info": {"exit_status": "submitted"},
- }
- (self._traj_dir / f"{instance_id}.traj").write_text(json.dumps(dct))
-
-
-def test_existing_corrupted_args(test_script_args: ScriptArguments):
- main = Main(test_script_args)
- main.add_hook(CreateFakeLogFile())
- main.main()
-
-
-def test_main_hook(test_script_args: ScriptArguments):
- main = Main(test_script_args)
- main.add_hook(RunHook())
- main.main()
+ rs.main()
@pytest.mark.slow
-def test_agent_with_hook(test_script_args: ScriptArguments):
- main = Main(test_script_args)
- main.agent.add_hook(AgentHook())
- main.main()
-
-
-PERSISTENT_CONTAINER_NAME = "sweagent-test-persistent-container"
-
-
-def _cleanup_persistent_container():
- yield
- client = docker.from_env()
- container = client.containers.get(PERSISTENT_CONTAINER_NAME)
- container.remove(force=True)
-
-
[email protected]("_cleanup_persistent_container")
-def test_agent_persistent_container(test_script_args: ScriptArguments, capsys):
- test_script_args = dataclasses.replace(
- test_script_args,
- environment=dataclasses.replace(test_script_args.environment, container_name=PERSISTENT_CONTAINER_NAME),
+def test_run_instant_empty_submit():
+ rsc = RunSingleConfig(
+ env=EnvironmentInstanceConfig(),
+ agent=AgentConfig(model=ModelArguments(name="instant_empty_submit")),
)
- assert test_script_args.environment.verbose
- main = Main(test_script_args)
- assert main.env.logger.isEnabledFor(logging.DEBUG)
- main.main()
- captured = capsys.readouterr()
- print("---")
- print(captured.out)
- print("---")
- print(captured.err)
- print("---")
- text = captured.out + captured.err
- assert "Trying to clone from non-mirror..." in text
- assert "Falling back to full cloning method" in text
-
-
-# todo: Add this back
-# def test_dummy_interactive_session(test_script_args: ScriptArguments):
-# test_script_args = dataclasses.replace(
-# test_script_args,
-# agent=AgentConfig(
-# model=ModelArguments(
-# model_name="instant_empty_submit",
-# ),
-# config_file=Path("tests", "test_data", "config_files", "dummy_interactive.yaml"),
-# ),
-# )
-# print(test_script_args.agent.config.command_docs) # type: ignore
-# main = Main(test_script_args)
-# env = main.env
-# env.reset()
-# main.agent.set_environment_vars(env, {})
-# action_obs = [
-# ("doesntexit", "command not found"),
-# ("dummy_stop", "is not running"),
-# ("dummy_send", "is not running"),
-# ("dummy_start", "Started interactive dummy command"),
-# ("dummy_start", "Interactive session already open"),
-# ("dummy_send asdf", "asdf"),
-# ("dummy_stop", "stopped successfully"),
-# ("dummy_stop", "is not running"),
-# ]
-# for action, expected_observation in action_obs:
-# observation, *_ = env.step(action)
-# assert observation is not None
-# assert expected_observation in observation, observation
-# env.close()
+ rs = RunSingle.from_config(rsc)
+ rs.main()
diff --git a/tests/test_run_hooks.py b/tests/test_run_hooks.py
new file mode 100644
index 00000000..23ad0d32
--- /dev/null
+++ b/tests/test_run_hooks.py
@@ -0,0 +1,71 @@
+import os
+
+import pytest
+
+from sweagent.run.hooks.open_pr import OpenPRConfig, OpenPRHook
+
+
+def open_pr_hook_init_for_sop():
+ hook = OpenPRHook(config=OpenPRConfig(skip_if_commits_reference_issue=True))
+ hook._token = os.environ.get("GITHUB_TOKEN", "")
+ hook._data_path = "https://github.com/swe-agent/test-repo/issues/1"
+ hook._open_pr = True
+ return hook
+
+
+def info_dict():
+ return {
+ "submission": "asdf",
+ "exit_status": "submitted",
+ }
+
+
+def test_should_open_pr_fail_submission(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ info_dict["submission"] = None
+ assert not hook.should_open_pr(info_dict)
+
+
+def test_should_open_pr_fail_exit(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ info_dict["exit_status"] = "fail"
+ assert not hook.should_open_pr(info_dict)
+
+
+def test_should_open_pr_fail_invalid_url(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ hook._data_path = "asdf"
+ assert not hook.should_open_pr(info_dict)
+
+
+def test_should_open_pr_fail_closed(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ hook._data_path = "https://github.com/swe-agent/test-repo/issues/16"
+ assert not hook.should_open_pr(info_dict)
+
+
+def test_should_open_pr_fail_assigned(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ hook._data_path = "https://github.com/swe-agent/test-repo/issues/17"
+ assert not hook.should_open_pr(info_dict)
+
+
+def test_should_open_pr_fail_locked(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ hook._data_path = "https://github.com/swe-agent/test-repo/issues/18"
+ assert not hook.should_open_pr(info_dict)
+
+
+def test_should_open_pr_fail_has_pr(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ hook._data_path = "https://github.com/swe-agent/test-repo/issues/19"
+ assert not hook.should_open_pr(info_dict)
+
+
+def test_should_open_pr_success_has_pr_override(open_pr_hook_init_for_sop, info_dict):
+ hook = open_pr_hook_init_for_sop
+ hook._data_path = "https://github.com/swe-agent/test-repo/issues/19"
+ hook._config.skip_if_commits_reference_issue = False
+ assert hook.should_open_pr(info_dict)
diff --git a/tests/test_utils.py b/tests/test_utils.py
index d9194bfc..49decc82 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -61,4 +61,4 @@ def test_convert_path_to_abspath():
def test_convert_paths_to_abspath():
- assert _convert_paths_to_abspath([Path("sadf"), "/sadf"]) == [REPO_ROOT / "sadf", Path("/sadf")]
+ assert _convert_paths_to_abspath([Path("sadf"), Path("/sadf")]) == [str(REPO_ROOT / "sadf"), str(Path("/sadf"))]