Skip to content

The agent that turns websites into APIs!

feat: add `run` command to execute generated scripts

kalil0321b175ff9bbce3
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.py
index 0d6754c..4217d32 100644
--- a/src/reverse_api/cli.py
+++ b/src/reverse_api/cli.py
@@ -35,6 +35,7 @@ from .tui import (
)
from .utils import (
check_for_updates,
+ discover_scripts,
generate_folder_name,
generate_run_id,
get_actions_path,
@@ -48,6 +49,7 @@ from .utils import (
parse_codegen_tag,
parse_engineer_prompt,
parse_record_only_tag,
+ resolve_run,
)
setproctitle.setproctitle("reverse-api-engineer")
@@ -2060,6 +2062,109 @@ def show_run(run_id, as_json):
console.print(table)
[email protected]("identifier")
[email protected]("script_args", nargs=-1, type=click.UNPROCESSED)
[email protected]("--file", "-f", "file_name", default=None, help="Script filename to run (e.g. api_client.py).")
[email protected]("--ls", "list_scripts", is_flag=True, help="List available scripts without executing.")
+def run_script(ctx, identifier, script_args, file_name, list_scripts):
+ """Run a generated script from a previous run.
+
+ IDENTIFIER is a run ID or search term to match against prompts.
+ Any extra arguments after the identifier are passed to the script.
+
+ Examples:
+
+ reverse-api-engineer run a450e520ca30
+
+ reverse-api-engineer run ashby --ls
+
+ reverse-api-engineer run ashby --file api_client.py
+
+ reverse-api-engineer run ashby -- --org acme --limit 10
+ """
+ import subprocess
+ import sys
+
+ from rich.table import Table
+
+ # Resolve which run
+ run = resolve_run(identifier, session_manager)
+ run_id = run["run_id"]
+ output_dir = config_manager.get("output_dir")
+
+ # Discover scripts
+ scripts = discover_scripts(run_id, output_dir)
+
+ if not scripts:
+ console.print(f"[red]No Python scripts found for run {run_id}[/red]")
+ prompt_preview = (run.get("prompt") or "")[:60]
+ console.print(f" prompt: {prompt_preview}", style="dim")
+ raise SystemExit(1)
+
+ # --ls: just list and exit
+ if list_scripts:
+ table = Table(title=f"Scripts in run {run_id}")
+ table.add_column("File", style="cyan")
+ table.add_column("Size", justify="right")
+ table.add_column("Modified")
+ for s in scripts:
+ stat = s.stat()
+ size = f"{stat.st_size:,} B"
+ from datetime import datetime
+
+ modified = datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M")
+ table.add_row(s.name, size, modified)
+ console.print(table)
+ return
+
+ # Select script
+ if file_name:
+ # Exact filename match
+ matching = [s for s in scripts if s.name == file_name]
+ if not matching:
+ available = ", ".join(s.name for s in scripts)
+ raise click.ClickException(f"'{file_name}' not found. Available: {available}")
+ script = matching[0]
+ elif len(scripts) == 1:
+ script = scripts[0]
+ else:
+ # Interactive picker
+ choices = [questionary.Choice(title=s.name, value=s) for s in scripts]
+ script = questionary.select(
+ "Select script to run:",
+ choices=choices,
+ ).ask()
+ if script is None:
+ raise click.Abort()
+
+ # Venv / dependency management
+ scripts_dir = script.parent
+ requirements = scripts_dir / "requirements.txt"
+ venv_dir = scripts_dir / ".venv"
+
+ if requirements.exists():
+ python_path = venv_dir / "bin" / "python"
+ if not venv_dir.exists():
+ console.print("Installing dependencies...", style="dim")
+ subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True)
+ pip_path = venv_dir / "bin" / "pip"
+ subprocess.run(
+ [str(pip_path), "install", "-q", "-r", str(requirements)],
+ check=True,
+ )
+ console.print("Dependencies installed.", style="dim")
+ python_path = str(python_path)
+ else:
+ python_path = sys.executable
+
+ # Execute
+ console.print(f"Running [cyan]{script.name}[/cyan] from run [dim]{run_id}[/dim]")
+ result = subprocess.run([python_path, str(script), *script_args])
+ raise SystemExit(result.returncode)
+
+
@main.command("install-host")
@click.option(
"--extension-id",
diff --git a/src/reverse_api/utils.py b/src/reverse_api/utils.py
index 2d79808..531592e 100644
--- a/src/reverse_api/utils.py
+++ b/src/reverse_api/utils.py
@@ -665,6 +665,97 @@ def get_visible_save_path(domain: str, base_dir: Path | str, suffix: int = 0) ->
return path
+def resolve_run(identifier: str, session_manager) -> dict:
+ """Resolve a run by exact ID or fuzzy prompt/folder name match.
+
+ Args:
+ identifier: Run ID (12-char hex) or search term to fuzzy match
+ session_manager: SessionManager instance to search history
+
+ Returns:
+ The matching run dict
+
+ Raises:
+ click.ClickException: If no match or ambiguous match without TTY
+ """
+ import click
+ import questionary
+
+ # 1. Try exact run_id match
+ run = session_manager.get_run(identifier)
+ if run:
+ return run
+
+ # 2. Fuzzy match against prompt and folder names
+ identifier_lower = identifier.lower()
+ matches = []
+ for run in session_manager.history:
+ prompt = (run.get("prompt") or "").lower()
+ run_id = run.get("run_id", "")
+ # Also check the script folder name from paths
+ script_path = run.get("paths", {}).get("script_path", "")
+ folder_name = Path(script_path).parent.name if script_path else ""
+
+ if identifier_lower in prompt or identifier_lower in folder_name.lower() or identifier_lower in run_id:
+ matches.append(run)
+
+ if not matches:
+ raise click.ClickException(
+ f"No run matching '{identifier}'. Use 'reverse-api-engineer list' to see available runs."
+ )
+
+ if len(matches) == 1:
+ return matches[0]
+
+ # Multiple matches — show picker
+ choices = []
+ for m in matches:
+ prompt_preview = (m.get("prompt") or "")[:50]
+ ts = (m.get("timestamp") or "")[:19]
+ label = f"{m['run_id']} {ts} {prompt_preview}"
+ choices.append(questionary.Choice(title=label, value=m))
+
+ selected = questionary.select(
+ f"Multiple runs match '{identifier}':",
+ choices=choices,
+ ).ask()
+
+ if selected is None:
+ raise click.Abort()
+
+ return selected
+
+
+def discover_scripts(run_id: str, output_dir: str | None = None) -> list[Path]:
+ """Find all executable Python scripts in a run's script directory.
+
+ Args:
+ run_id: The run identifier
+ output_dir: Optional custom output directory
+
+ Returns:
+ Sorted list of .py file Paths (excludes __pycache__, .venv, __init__.py)
+ """
+ base_dir = get_base_output_dir(output_dir)
+ scripts_dir = base_dir / "scripts" / run_id
+
+ if not scripts_dir.exists():
+ return []
+
+ exclude_dirs = {"__pycache__", ".venv"}
+ exclude_files = {"__init__.py"}
+
+ scripts = []
+ for f in scripts_dir.iterdir():
+ if f.is_file() and f.suffix == ".py" and f.name not in exclude_files:
+ scripts.append(f)
+ # Don't recurse into excluded dirs
+ # Also skip files inside excluded subdirs (shouldn't happen with iterdir but defensive)
+ scripts = [s for s in scripts if not any(part in exclude_dirs for part in s.parts)]
+
+ return sorted(scripts, key=lambda p: p.name)
+
+
def extract_domain_from_har(har_path: Path) -> str | None:
"""Extract the primary domain from a HAR file.
diff --git a/tests/test_run_command.py b/tests/test_run_command.py
new file mode 100644
index 0000000..ca97de7
--- /dev/null
+++ b/tests/test_run_command.py
@@ -0,0 +1,531 @@
+"""Tests for the `run` command and its supporting functions (resolve_run, discover_scripts)."""
+
+import json
+import subprocess
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import click
+import pytest
+from click.testing import CliRunner
+
+from reverse_api.session import SessionManager
+from reverse_api.utils import discover_scripts, resolve_run
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+def session_with_runs(tmp_path):
+ """SessionManager with pre-populated runs."""
+ history_path = tmp_path / "history.json"
+ sm = SessionManager(history_path)
+ sm.add_run("abc123def456", "capture the ashby jobs api", mode="manual", paths={"script_path": "/scripts/abc123def456/api_client.py"})
+ sm.add_run("def789ghi012", "go to hubspot and create an api", mode="agent", paths={"script_path": "/scripts/def789ghi012/api_client.py"})
+ sm.add_run("111222333444", "browserbase mp4 recording api", mode="manual", paths={"script_path": "/scripts/111222333444/api_client.py"})
+ return sm
+
+
+def empty_session(tmp_path):
+ """SessionManager with no runs."""
+ history_path = tmp_path / "history.json"
+ return SessionManager(history_path)
+
+
+def scripts_dir(tmp_path):
+ """Create a fake scripts directory with multiple .py files."""
+ run_id = "abc123def456"
+ d = tmp_path / "scripts" / run_id
+ d.mkdir(parents=True)
+ (d / "api_client.py").write_text("print('hello from api_client')")
+ (d / "example_usage.py").write_text("print('hello from example')")
+ (d / "README.md").write_text("# docs")
+ (d / "requirements.txt").write_text("requests>=2.28")
+ return d
+
+
+def scripts_dir_single(tmp_path):
+ """Create a scripts directory with a single .py file."""
+ run_id = "abc123def456"
+ d = tmp_path / "scripts" / run_id
+ d.mkdir(parents=True)
+ (d / "api_client.py").write_text("print('only script')")
+ return d
+
+
+def scripts_dir_empty(tmp_path):
+ """Create a scripts directory with no .py files."""
+ run_id = "abc123def456"
+ d = tmp_path / "scripts" / run_id
+ d.mkdir(parents=True)
+ (d / "README.md").write_text("# no scripts here")
+ return d
+
+
+# ---------------------------------------------------------------------------
+# resolve_run tests
+# ---------------------------------------------------------------------------
+
+class TestResolveRunExactId:
+ """Test resolve_run with exact run_id matches."""
+
+ def test_exact_match(self, session_with_runs):
+ run = resolve_run("abc123def456", session_with_runs)
+ assert run["run_id"] == "abc123def456"
+
+ def test_exact_match_second_run(self, session_with_runs):
+ run = resolve_run("def789ghi012", session_with_runs)
+ assert run["run_id"] == "def789ghi012"
+
+ def test_exact_match_third_run(self, session_with_runs):
+ run = resolve_run("111222333444", session_with_runs)
+ assert run["run_id"] == "111222333444"
+
+
+class TestResolveRunFuzzyMatch:
+ """Test resolve_run with fuzzy prompt/name matching."""
+
+ def test_unique_prompt_match(self, session_with_runs):
+ run = resolve_run("ashby", session_with_runs)
+ assert run["run_id"] == "abc123def456"
+
+ def test_no_match_raises(self, session_with_runs):
+ with pytest.raises(click.ClickException, match="No run matching"):
+ resolve_run("nonexistent_xyz", session_with_runs)
+
+ def test_no_match_error_message_includes_identifier(self, session_with_runs):
+ with pytest.raises(click.ClickException, match="zzzznotfound"):
+ resolve_run("zzzznotfound", session_with_runs)
+
+ def test_empty_history_raises(self, empty_session):
+ with pytest.raises(click.ClickException, match="No run matching"):
+ resolve_run("anything", empty_session)
+
+ def test_case_insensitive_match(self, session_with_runs):
+ run = resolve_run("ASHBY", session_with_runs)
+ assert run["run_id"] == "abc123def456"
+
+ def test_partial_run_id_match(self, session_with_runs):
+ """Partial run_id substring should match via fuzzy search."""
+ run = resolve_run("abc123", session_with_runs)
+ assert run["run_id"] == "abc123def456"
+
+ def test_multiple_matches_shows_picker(self, session_with_runs):
+ """When multiple runs match, questionary picker is shown."""
+ # "api" appears in all three prompts
+ with patch("questionary.Choice", side_effect=lambda **kw: kw):
+ with patch("questionary.select") as mock_select:
+ mock_select.return_value.ask.return_value = session_with_runs.history[0]
+ run = resolve_run("api", session_with_runs)
+ mock_select.assert_called_once()
+ assert run is not None
+
+ def test_multiple_matches_user_cancels(self, session_with_runs):
+ """When user cancels the picker, click.Abort is raised."""
+ with patch("questionary.Choice", side_effect=lambda **kw: kw):
+ with patch("questionary.select") as mock_select:
+ mock_select.return_value.ask.return_value = None
+ with pytest.raises(click.Abort):
+ resolve_run("api", session_with_runs)
+
+ def test_matches_folder_name_from_paths(self, tmp_path):
+ """Matches against folder name derived from paths.script_path."""
+ history_path = tmp_path / "history.json"
+ sm = SessionManager(history_path)
+ sm.add_run("aaa111bbb222", "some generic prompt", paths={"script_path": "/scripts/aaa111bbb222/ashby_jobs_api/api_client.py"})
+ # "ashby_jobs" should match the folder name in the path
+ run = resolve_run("ashby_jobs", sm)
+ assert run["run_id"] == "aaa111bbb222"
+
+ def test_match_against_prompt_substring(self, tmp_path):
+ """Matches substring within prompt text."""
+ history_path = tmp_path / "history.json"
+ sm = SessionManager(history_path)
+ sm.add_run("xyz123", "go to stripe.com and reverse engineer the billing api")
+ run = resolve_run("stripe", sm)
+ assert run["run_id"] == "xyz123"
+
+ def test_match_is_case_insensitive_on_prompt(self, tmp_path):
+ """Case-insensitive matching on prompt content."""
+ history_path = tmp_path / "history.json"
+ sm = SessionManager(history_path)
+ sm.add_run("xyz123", "Go to GitHub.com and capture API")
+ run = resolve_run("github", sm)
+ assert run["run_id"] == "xyz123"
+
+
+# ---------------------------------------------------------------------------
+# discover_scripts tests
+# ---------------------------------------------------------------------------
+
+class TestDiscoverScripts:
+ """Test discover_scripts function."""
+
+ def test_finds_py_files(self, scripts_dir, tmp_path):
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ names = [s.name for s in scripts]
+ assert "api_client.py" in names
+ assert "example_usage.py" in names
+
+ def test_excludes_non_py(self, scripts_dir, tmp_path):
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ names = [s.name for s in scripts]
+ assert "README.md" not in names
+ assert "requirements.txt" not in names
+
+ def test_excludes_init(self, scripts_dir, tmp_path):
+ (scripts_dir / "__init__.py").write_text("")
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ names = [s.name for s in scripts]
+ assert "__init__.py" not in names
+
+ def test_excludes_venv_files(self, scripts_dir, tmp_path):
+ venv = scripts_dir / ".venv"
+ venv.mkdir()
+ (venv / "some_script.py").write_text("")
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ for s in scripts:
+ assert ".venv" not in str(s)
+
+ def test_empty_dir_returns_empty(self, scripts_dir_empty, tmp_path):
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ assert scripts == []
+
+ def test_nonexistent_dir_returns_empty(self, tmp_path):
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("doesnotexist999")
+ assert scripts == []
+
+ def test_sorted_by_name(self, scripts_dir, tmp_path):
+ (scripts_dir / "zzz_last.py").write_text("")
+ (scripts_dir / "aaa_first.py").write_text("")
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ names = [s.name for s in scripts]
+ assert names == sorted(names)
+
+ def test_custom_output_dir(self, tmp_path):
+ custom = tmp_path / "custom_out"
+ d = custom / "scripts" / "run1"
+ d.mkdir(parents=True)
+ (d / "main.py").write_text("print('hi')")
+ scripts = discover_scripts("run1", output_dir=str(custom))
+ assert len(scripts) == 1
+ assert scripts[0].name == "main.py"
+
+ def test_single_script(self, scripts_dir_single, tmp_path):
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ assert len(scripts) == 1
+ assert scripts[0].name == "api_client.py"
+
+ def test_pycache_dir_contents_excluded(self, scripts_dir, tmp_path):
+ cache = scripts_dir / "__pycache__"
+ cache.mkdir()
+ (cache / "module.cpython-313.pyc").write_text("")
+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):
+ scripts = discover_scripts("abc123def456")
+ for s in scripts:
+ assert "__pycache__" not in str(s)
+
+
+# ---------------------------------------------------------------------------
+# CLI `run` command integration tests (using Click's CliRunner)
+# ---------------------------------------------------------------------------
+
+def cli_runner():
+ return CliRunner()
+
+
+def mock_cli_env(tmp_path, session_with_runs):
+ """Patch the module-level globals in cli.py for testing."""
+ scripts_dir = tmp_path / "scripts" / "abc123def456"
+ scripts_dir.mkdir(parents=True)
+ (scripts_dir / "api_client.py").write_text("import sys; print('args:', sys.argv[1:])")
+ (scripts_dir / "example_usage.py").write_text("print('example')")
+
+ # Single-script run
+ scripts_dir2 = tmp_path / "scripts" / "def789ghi012"
+ scripts_dir2.mkdir(parents=True)
+ (scripts_dir2 / "api_client.py").write_text("print('hubspot client')")
+
+ # Empty run (no .py files)
+ scripts_dir3 = tmp_path / "scripts" / "111222333444"
+ scripts_dir3.mkdir(parents=True)
+
+ patches = [
+ patch("reverse_api.cli.session_manager", session_with_runs),
+ patch("reverse_api.cli.config_manager", MagicMock(get=MagicMock(return_value=None))),
+ patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path),
+ ]
+ for p in patches:
+ p.start()
+ yield tmp_path, session_with_runs
+ for p in patches:
+ p.stop()
+
+
+class TestRunCommandHelp:
+ """Test --help and basic CLI parsing."""
+
+ def test_help_output(self, cli_runner):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "--help"])
+ assert result.exit_code == 0
+ assert "IDENTIFIER" in result.output
+ assert "--ls" in result.output
+ assert "--file" in result.output
+
+ def test_help_shows_examples(self, cli_runner):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "--help"])
+ assert "reverse-api-engineer run" in result.output
+
+
+class TestRunCommandLs:
+ """Test --ls flag."""
+
+ def test_ls_shows_scripts(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "abc123def456", "--ls"])
+ assert result.exit_code == 0
+ assert "api_client.py" in result.output
+ assert "example_usage.py" in result.output
+
+ def test_ls_shows_file_sizes(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "abc123def456", "--ls"])
+ assert "Size" in result.output
+ assert "Modified" in result.output
+ assert "B" in result.output
+
+ def test_ls_no_scripts_error(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "111222333444", "--ls"])
+ assert result.exit_code == 1
+ assert "No Python scripts" in result.output
+
+ def test_ls_with_fuzzy_name(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "ashby", "--ls"])
+ assert result.exit_code == 0
+ assert "api_client.py" in result.output
+
+ def test_ls_does_not_execute(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run") as mock_sub:
+ result = cli_runner.invoke(main, ["run", "abc123def456", "--ls"])
+ mock_sub.assert_not_called()
+
+
+class TestRunCommandFileFlag:
+ """Test --file flag."""
+
+ def test_file_flag_selects_script(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_sub:
+ result = cli_runner.invoke(main, ["run", "abc123def456", "--file", "example_usage.py"])
+ assert mock_sub.called
+ call_args = mock_sub.call_args[0][0]
+ assert "example_usage.py" in str(call_args[1])
+
+ def test_file_flag_nonexistent_file(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "abc123def456", "--file", "nope.py"])
+ assert result.exit_code != 0
+ assert "nope.py" in result.output
+ assert "Available" in result.output
+
+ def test_file_flag_lists_available_on_error(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "abc123def456", "--file", "missing.py"])
+ assert "api_client.py" in result.output
+ assert "example_usage.py" in result.output
+
+
+class TestRunCommandExecution:
+ """Test actual script execution."""
+
+ def test_single_script_auto_selected(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_sub:
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+ assert mock_sub.called
+ call_args = mock_sub.call_args[0][0]
+ assert "api_client.py" in str(call_args[1])
+
+ def test_args_passthrough(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_sub:
+ result = cli_runner.invoke(main, ["run", "def789ghi012", "--", "--org", "acme", "--limit", "10"])
+ call_args = mock_sub.call_args[0][0]
+ assert "--org" in call_args
+ assert "acme" in call_args
+ assert "--limit" in call_args
+ assert "10" in call_args
+
+ def test_exit_code_forwarded(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=42)):
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+ assert result.exit_code == 42
+
+ def test_exit_code_zero_on_success(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)):
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+ assert result.exit_code == 0
+
+ def test_multiple_scripts_shows_picker(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ tmp_path = mock_cli_env[0]
+ script_path = tmp_path / "scripts" / "abc123def456" / "api_client.py"
+ with patch("questionary.Choice", side_effect=lambda **kw: kw):
+ with patch("questionary.select") as mock_select:
+ mock_select.return_value.ask.return_value = script_path
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)):
+ result = cli_runner.invoke(main, ["run", "abc123def456"])
+ mock_select.assert_called_once()
+
+ def test_multiple_scripts_user_cancels_picker(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("questionary.Choice", side_effect=lambda **kw: kw):
+ with patch("questionary.select") as mock_select:
+ mock_select.return_value.ask.return_value = None
+ result = cli_runner.invoke(main, ["run", "abc123def456"])
+ assert result.exit_code != 0
+
+
+class TestRunCommandNoScripts:
+ """Test error handling when no scripts exist."""
+
+ def test_no_scripts_shows_error(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "111222333444"])
+ assert result.exit_code == 1
+ assert "No Python scripts" in result.output
+
+ def test_no_scripts_shows_prompt_preview(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "111222333444"])
+ assert "browserbase" in result.output
+
+ def test_no_matching_run(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ result = cli_runner.invoke(main, ["run", "totallynonexistent"])
+ assert result.exit_code != 0
+ assert "No run matching" in result.output
+
+
+class TestRunCommandVenv:
+ """Test venv and dependency management."""
+
+ def test_creates_venv_when_requirements_exist(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ tmp_path = mock_cli_env[0]
+ req = tmp_path / "scripts" / "def789ghi012" / "requirements.txt"
+ req.write_text("requests>=2.28")
+
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_sub:
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+
+ # Should have called subprocess.run 3 times: venv create, pip install, script run
+ assert mock_sub.call_count == 3
+ calls = mock_sub.call_args_list
+
+ # First call: create venv
+ assert "-m" in calls[0][0][0]
+ assert "venv" in calls[0][0][0]
+
+ # Second call: pip install
+ pip_args = calls[1][0][0]
+ assert "pip" in str(pip_args[0])
+ assert "-r" in pip_args
+
+ # Third call: actual script, using venv python
+ python_path = str(calls[2][0][0][0])
+ assert ".venv" in python_path
+
+ def test_skips_venv_when_already_exists(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ tmp_path = mock_cli_env[0]
+ scripts = tmp_path / "scripts" / "def789ghi012"
+ req = scripts / "requirements.txt"
+ req.write_text("requests>=2.28")
+ # Pre-create venv
+ venv = scripts / ".venv"
+ venv.mkdir()
+ (venv / "bin").mkdir()
+ (venv / "bin" / "python").write_text("#!/bin/sh")
+
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_sub:
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+
+ # Should only call subprocess.run once (just the script), no venv/pip
+ assert mock_sub.call_count == 1
+
+ def test_no_venv_without_requirements(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_sub:
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+
+ # Should call subprocess.run exactly once (just the script, no venv/pip)
+ assert mock_sub.call_count == 1
+ # Should NOT have created a venv inside the scripts dir
+ tmp_path = mock_cli_env[0]
+ venv_path = tmp_path / "scripts" / "def789ghi012" / ".venv"
+ assert not venv_path.exists()
+
+ def test_venv_uses_requirements_txt_path(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ tmp_path = mock_cli_env[0]
+ req = tmp_path / "scripts" / "def789ghi012" / "requirements.txt"
+ req.write_text("httpx>=0.25\nbeautifulsoup4")
+
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_sub:
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+
+ # pip install call should reference the requirements.txt
+ pip_call = mock_sub.call_args_list[1][0][0]
+ assert str(req) in [str(a) for a in pip_call]
+
+
+class TestRunCommandOutputMessages:
+ """Test user-facing output messages."""
+
+ def test_shows_running_message(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)):
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+ assert "Running" in result.output
+ assert "api_client.py" in result.output
+
+ def test_shows_run_id_in_output(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)):
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+ assert "def789ghi012" in result.output
+
+ def test_installing_deps_message(self, cli_runner, mock_cli_env):
+ from reverse_api.cli import main
+ tmp_path = mock_cli_env[0]
+ req = tmp_path / "scripts" / "def789ghi012" / "requirements.txt"
+ req.write_text("requests")
+
+ with patch("subprocess.run", return_value=MagicMock(returncode=0)):
+ result = cli_runner.invoke(main, ["run", "def789ghi012"])
+ assert "Installing dependencies" in result.output
+ assert "Dependencies installed" in result.output