Skip to content

Automate browser based workflows with AI

[CLI] Handle quickstart Docker cleanup and server extras (#5923)

Suchintanecd6018b63fc
diff --git a/skyvern/_cli_bootstrap.py b/skyvern/_cli_bootstrap.py
index 4fe028ca4..af4dcaf8e 100644
--- a/skyvern/_cli_bootstrap.py
+++ b/skyvern/_cli_bootstrap.py
@@ -10,6 +10,7 @@ _DEFAULT_CLI_LOG_LEVEL = "WARNING"
_QUIET_CLI_LOGGERS = ("skyvern", "httpx", "litellm", "playwright", "httpcore")
_RUNTIME_LOGGING_CONFIGURED = False
+_SILENCED_CLI_LOGGERS = ("posthog",)
def raise_unless_missing_optional_dependency(exc: ImportError, expected_modules: set[str]) -> None:
@@ -32,6 +33,10 @@ def configure_cli_bootstrap_logging() -> None:
logging.getLogger().setLevel(log_level)
for logger_name in _QUIET_CLI_LOGGERS:
logging.getLogger(logger_name).setLevel(log_level)
+ for logger_name in _SILENCED_CLI_LOGGERS:
+ logger = logging.getLogger(logger_name)
+ logger.setLevel(logging.CRITICAL + 1)
+ logger.propagate = False
def configure_cli_runtime_logging() -> None:
diff --git a/skyvern/cli/database.py b/skyvern/cli/database.py
index 1a181eafe..1e2d79edc 100644
--- a/skyvern/cli/database.py
+++ b/skyvern/cli/database.py
@@ -1,3 +1,4 @@
+import os
import shutil
import subprocess
import time
@@ -31,11 +32,22 @@ def command_exists(command: str) -> bool:
def run_command(command: str, check: bool = True) -> tuple[Optional[str], Optional[int]]:
try:
result = subprocess.run(command, shell=True, check=check, capture_output=True, text=True)
- return result.stdout.strip(), result.returncode
+ output = result.stdout.strip() or result.stderr.strip()
+ return output, result.returncode
except subprocess.CalledProcessError as e:
+ stdout = (e.stdout or "").strip()
+ stderr = (e.stderr or "").strip()
console.print(f"[red]Error executing command: [bold]{command}[/bold][/red]", style="red")
- console.print(f"[red]Stderr: {e.stderr.strip()}[/red]", style="red")
- return None, e.returncode
+ console.print(f"[red]Stderr: {stderr}[/red]", style="red")
+ return stdout or stderr, e.returncode
+
+
+def _subprocess_output(result: subprocess.CompletedProcess[str]) -> str:
+ return "\n".join(part for part in ((result.stdout or "").strip(), (result.stderr or "").strip()) if part)
+
+
+def _already_exists(result: subprocess.CompletedProcess[str]) -> bool:
+ return "already exists" in _subprocess_output(result).lower()
def is_postgres_running() -> bool:
@@ -78,29 +90,47 @@ def create_database_and_user() -> None:
console.print("✅ [green]Role 'skyvern' already exists.[/green]")
else:
console.print(" Creating role 'skyvern'...")
- _, code = run_command("createuser skyvern", check=False)
- if code != 0:
+ result = subprocess.run(
+ ["createuser", "skyvern"],
+ check=False,
+ capture_output=True,
+ text=True,
+ env={**os.environ, "LC_MESSAGES": "C"},
+ )
+ if result.returncode == 0:
+ console.print(" ✅ [green]Role 'skyvern' created.[/green]")
+ elif _already_exists(result):
+ console.print("✅ [green]Role 'skyvern' already exists.[/green]")
+ else:
console.print(
"[red]Failed to create role 'skyvern'. "
"You may need to create it manually:[/red]\n"
" [bold]createuser skyvern[/bold]"
)
raise SystemExit(1)
- console.print(" ✅ [green]Role 'skyvern' created.[/green]")
if _database_exists_via_catalog("skyvern"):
console.print("✅ [green]Database 'skyvern' already exists.[/green]")
else:
console.print(" Creating database 'skyvern'...")
- _, code = run_command("createdb skyvern -O skyvern", check=False)
- if code != 0:
+ result = subprocess.run(
+ ["createdb", "skyvern", "-O", "skyvern"],
+ check=False,
+ capture_output=True,
+ text=True,
+ env={**os.environ, "LC_MESSAGES": "C"},
+ )
+ if result.returncode == 0:
+ console.print(" ✅ [green]Database 'skyvern' created.[/green]")
+ elif _already_exists(result):
+ console.print("✅ [green]Database 'skyvern' already exists.[/green]")
+ else:
console.print(
"[red]Failed to create database 'skyvern'. "
"You may need to create it manually:[/red]\n"
" [bold]createdb skyvern -O skyvern[/bold]"
)
raise SystemExit(1)
- console.print(" ✅ [green]Database 'skyvern' created.[/green]")
console.print("✅ [bold green]Database and user are ready.[/bold green]")
@@ -191,18 +221,24 @@ def setup_postgresql(no_postgres: bool = False, *, env_path: Path | str | None =
if not is_postgres_container_exists():
with console.status("[bold blue]Pulling and starting PostgreSQL container...[/bold blue]"):
output, code = run_command(
- "docker run --name postgresql-container -e POSTGRES_HOST_AUTH_METHOD=trust -d -p 5432:5432 postgres:14"
+ "docker run --name postgresql-container "
+ "-e POSTGRES_HOST_AUTH_METHOD=trust -d -p 5432:5432 postgres:14",
+ check=False,
)
if code != 0:
- capture_setup_event(
- "database-container-fail",
- success=False,
- error_type="docker_run_error",
- error_message=output or "Failed to start PostgreSQL container",
- )
- console.print(
- "[red]Warning: Failed to start PostgreSQL container. Check Docker logs for details.[/red]"
- )
+ if is_postgres_container_exists():
+ run_command("docker start postgresql-container", check=False)
+ console.print("✅ [green]Existing PostgreSQL container started.[/green]")
+ else:
+ capture_setup_event(
+ "database-container-fail",
+ success=False,
+ error_type="docker_run_error",
+ error_message=output or "Failed to start PostgreSQL container",
+ )
+ console.print(
+ "[red]Warning: Failed to start PostgreSQL container. Check Docker logs for details.[/red]"
+ )
else:
console.print("✅ [green]PostgreSQL has been installed and started using Docker.[/green]")
else:
diff --git a/skyvern/cli/init_command.py b/skyvern/cli/init_command.py
index 78ff76bf8..4dca63769 100644
--- a/skyvern/cli/init_command.py
+++ b/skyvern/cli/init_command.py
@@ -1,12 +1,16 @@
import asyncio
+import importlib.metadata
import os
import subprocess
+import sys
import uuid
+from collections.abc import Callable, Coroutine
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Literal, overload
+from typing import Any, Literal, TypeVar, overload
import typer
+from rich.markup import escape
from rich.padding import Padding
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
@@ -202,6 +206,108 @@ def _select_backend_env_scope(*, run_local: bool, env_scope: str | None) -> EnvS
console.print(f"[red]{exc.message}[/red]")
+_T = TypeVar("_T")
+_SERVER_EXTRA_INSTALL_ATTEMPTED = False
+_LOCAL_SERVER_DEPENDENCY_HINT = (
+ "Local Skyvern needs the server dependencies, but this Python environment is missing "
+ "[cyan]{module}[/cyan].\n\n"
+ "Run [cyan]{install_command}[/cyan] and then rerun [cyan]skyvern quickstart[/cyan].\n\n"
+ "For the full UI + API + Postgres stack, clone the Skyvern repository and use Docker Compose."
+)
+
+
+def _missing_local_server_dependency(exc: ImportError) -> str | None:
+ missing_module = getattr(exc, "name", None)
+ if not missing_module:
+ return None
+
+ server_only_modules = {
+ "alembic",
+ "fastapi",
+ "fuzzysearch",
+ "playwright",
+ "psycopg",
+ "sqlalchemy",
+ "uvicorn",
+ }
+ root_module = missing_module.split(".", maxsplit=1)[0]
+ if root_module in server_only_modules:
+ return root_module
+ return None
+
+
+def _server_extra_install_target() -> str:
+ cwd = Path.cwd()
+ if (cwd / "pyproject.toml").is_file() and (cwd / "skyvern").is_dir():
+ return ".[server]"
+
+ try:
+ version = importlib.metadata.version("skyvern")
+ except importlib.metadata.PackageNotFoundError:
+ return "skyvern[server]"
+ return f"skyvern[server]=={version}"
+
+
+def _server_extra_install_command(target: str) -> str:
+ return f"{sys.executable} -m pip install {target!r}"
+
+
+def _print_local_server_dependency_hint(module: str, target: str | None = None) -> None:
+ target = target or _server_extra_install_target()
+ console.print(
+ Panel(
+ _LOCAL_SERVER_DEPENDENCY_HINT.format(
+ module=escape(module),
+ install_command=escape(_server_extra_install_command(target)),
+ ),
+ title="Missing Local Server Dependency",
+ border_style="red",
+ )
+ )
+
+
+def _install_server_extra_for_missing_dependency(exc: ImportError) -> None:
+ missing_module = _missing_local_server_dependency(exc)
+ if missing_module is None:
+ raise exc
+
+ global _SERVER_EXTRA_INSTALL_ATTEMPTED
+ target = _server_extra_install_target()
+ if _SERVER_EXTRA_INSTALL_ATTEMPTED:
+ _print_local_server_dependency_hint(missing_module, target)
+ raise typer.Exit(1) from exc
+
+ console.print(
+ Panel(
+ "Local quickstart needs the server dependencies, but this environment is missing "
+ f"[cyan]{escape(missing_module)}[/cyan].\n\n"
+ f"Install [cyan]{escape(target)}[/cyan] into the current Python environment now?",
+ title="Missing Local Server Dependency",
+ border_style="yellow",
+ )
+ )
+ if not Confirm.ask("Install the missing server dependencies now?", default=True):
+ _print_local_server_dependency_hint(missing_module, target)
+ raise typer.Exit(1) from exc
+
+ _SERVER_EXTRA_INSTALL_ATTEMPTED = True
+ console.print(f"📦 [bold blue]Installing {escape(target)}...[/bold blue]")
+ try:
+ subprocess.run([sys.executable, "-m", "pip", "install", target], check=True)
+ except subprocess.CalledProcessError as install_error:
+ console.print(f"[bold red]Failed to install {target}: {install_error}[/bold red]")
+ _print_local_server_dependency_hint(missing_module, target)
+ raise typer.Exit(1) from install_error
+
+
+def _run_with_server_dependency_install(action: Callable[[], _T]) -> _T:
+ while True:
+ try:
+ return action()
+ except ImportError as exc:
+ _install_server_extra_for_missing_dependency(exc)
+
+
@overload
def init_env(
no_postgres: bool = False,
@@ -275,16 +381,25 @@ def init_env(
console.print("📊 [bold blue]Running database migrations...[/bold blue]")
from skyvern.utils import migrate_db # noqa: PLC0415
- migrate_db()
+ _run_with_server_dependency_install(migrate_db)
console.print("✅ [green]Database migration complete.[/green]")
console.print("🔑 [bold blue]Generating local organization API key...[/bold blue]")
- from skyvern.forge.forge_app_initializer import start_forge_app # noqa: PLC0415
- from .mcp import setup_local_organization # noqa: PLC0415
+ def _load_start_forge_app() -> Callable[[], object]:
+ from skyvern.forge.forge_app_initializer import start_forge_app # noqa: PLC0415
+
+ return start_forge_app
+
+ def _load_setup_local_organization() -> Callable[[], Coroutine[Any, Any, str]]:
+ from .mcp import setup_local_organization # noqa: PLC0415
+
+ return setup_local_organization
- start_forge_app()
- api_key = asyncio.run(setup_local_organization())
+ start_forge_app = _run_with_server_dependency_install(_load_start_forge_app)
+ setup_local_organization = _run_with_server_dependency_install(_load_setup_local_organization)
+ _run_with_server_dependency_install(start_forge_app)
+ api_key = _run_with_server_dependency_install(lambda: asyncio.run(setup_local_organization()))
if api_key:
console.print("✅ [green]Local organization API key generated.[/green]")
else:
diff --git a/skyvern/cli/quickstart.py b/skyvern/cli/quickstart.py
index 8426c4e70..65f48d509 100644
--- a/skyvern/cli/quickstart.py
+++ b/skyvern/cli/quickstart.py
@@ -1,6 +1,8 @@
"""Quickstart command for Skyvern CLI."""
import asyncio
+import importlib
+import importlib.metadata
import subprocess
import sys
from enum import Enum
@@ -8,6 +10,7 @@ from pathlib import Path
from typing import Any
import typer
+from rich.markup import escape
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.prompt import Confirm, Prompt
@@ -18,6 +21,46 @@ from skyvern.utils.env_paths import EnvScope, parse_env_scope, resolve_frontend_
quickstart_app = typer.Typer(help="Quickstart command to set up and run Skyvern with one command.")
+_SKYVERN_COMPOSE_SERVICES = {"postgres", "skyvern", "skyvern-ui"}
+
+
+def _server_extra_install_target() -> str:
+ cwd = Path.cwd()
+ if (cwd / "pyproject.toml").is_file() and (cwd / "skyvern").is_dir():
+ return ".[server]"
+
+ try:
+ version = importlib.metadata.version("skyvern")
+ except importlib.metadata.PackageNotFoundError:
+ return "skyvern[server]"
+ return f"skyvern[server]=={version}"
+
+
+def _install_server_extra_for_quickstart() -> bool:
+ target = _server_extra_install_target()
+ console.print(
+ Panel(
+ "Local quickstart needs the server dependencies.\n\n"
+ f"Install [cyan]{escape(target)}[/cyan] into the current Python environment now?",
+ title="Missing Local Server Dependency",
+ border_style="yellow",
+ )
+ )
+ if not Confirm.ask("Install the missing server dependencies now?", default=True):
+ _print_server_guidance()
+ return False
+
+ console.print(f"📦 [bold blue]Installing {escape(target)}...[/bold blue]")
+ try:
+ subprocess.run([sys.executable, "-m", "pip", "install", target], check=True)
+ except subprocess.CalledProcessError as install_error:
+ console.print(f"[bold red]Failed to install {target}: {install_error}[/bold red]")
+ _print_server_guidance()
+ return False
+
+ importlib.invalidate_caches()
+ return True
+
def capture_setup_event(
event_name: str,
@@ -299,6 +342,8 @@ def _run_server_quickstart(
)
console.print("\n[bold yellow]Quickstart process interrupted by user.[/bold yellow]")
raise typer.Exit(0)
+ except typer.Exit:
+ raise
except Exception as e:
capture_setup_error("quickstart-fail", e, error_type="quickstart_error")
console.print(f"[bold red]Error during quickstart: {str(e)}[/bold red]")
@@ -340,18 +385,154 @@ def check_docker_compose_file() -> bool:
return Path("docker-compose.yml").exists() or Path("docker-compose.yaml").exists()
-def check_postgres_container_conflict() -> bool:
- """Check if postgresql-container exists and is using port 5432."""
+def _run_docker_command(args: list[str]) -> subprocess.CompletedProcess[str] | None:
try:
- result = subprocess.run(
- ["docker", "ps", "-a", "--filter", "name=postgresql-container", "--format", "{{.Names}}"],
+ return subprocess.run(
+ args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
- return "postgresql-container" in result.stdout
except (FileNotFoundError, subprocess.SubprocessError):
- return False
+ return None
+
+
+def get_postgres_container_state() -> str | None:
+ """Return the standalone quickstart Postgres container state when it exists."""
+ result = _run_docker_command(["docker", "inspect", "--format", "{{.State.Status}}", "postgresql-container"])
+ if result is None or result.returncode != 0:
+ return None
+ return result.stdout.strip() or "unknown"
+
+
+def check_postgres_container_conflict() -> bool:
+ """Check if the standalone quickstart Postgres container exists."""
+ return get_postgres_container_state() is not None
+
+
+def _running_skyvern_compose_services() -> list[str]:
+ """Return running services from the current Skyvern Docker Compose project."""
+ result = _run_docker_command(["docker", "compose", "ps", "--services", "--status", "running"])
+ if result is None or result.returncode != 0:
+ return []
+
+ services = [line.strip() for line in result.stdout.splitlines() if line.strip()]
+ return [service for service in services if service in _SKYVERN_COMPOSE_SERVICES]
+
+
+def _handle_running_compose_stack() -> None:
+ services = _running_skyvern_compose_services()
+ if not services:
+ return
+
+ capture_setup_event(
+ "docker-compose-existing-detected",
+ success=True,
+ extra_data={"services": services},
+ )
+ console.print(
+ Panel(
+ "[bold yellow]Skyvern Docker Compose is already running.[/bold yellow]\n\n"
+ f"Running services: [cyan]{', '.join(services)}[/cyan]\n\n"
+ "If you changed configuration during quickstart, restarting the compose stack "
+ "avoids stale containers and port conflicts.",
+ border_style="yellow",
+ )
+ )
+ if not Confirm.ask("Run [cyan]docker compose down[/cyan] before continuing?", default=True):
+ console.print("[yellow]Continuing with the existing Docker Compose stack.[/yellow]")
+ capture_setup_event(
+ "docker-compose-existing-keep",
+ success=True,
+ extra_data={"services": services},
+ )
+ return
+
+ try:
+ subprocess.run(
+ ["docker", "compose", "down"],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ except subprocess.CalledProcessError as e:
+ capture_setup_event(
+ "docker-compose-down-fail",
+ success=False,
+ error_type="docker_compose_down_error",
+ error_message=e.stderr.strip() if e.stderr else str(e),
+ )
+ console.print(f"[bold red]Error stopping Docker Compose: {e.stderr}[/bold red]")
+ raise typer.Exit(1)
+
+ console.print("✅ [green]Stopped existing Skyvern Docker Compose services.[/green]")
+ capture_setup_event(
+ "docker-compose-existing-stopped",
+ success=True,
+ extra_data={"services": services},
+ )
+
+
+def _handle_postgres_container_conflict() -> None:
+ container_state = get_postgres_container_state()
+ if container_state is None:
+ return
+
+ capture_setup_event(
+ "docker-postgres-container-detected",
+ success=True,
+ extra_data={"state": container_state},
+ )
+ console.print(
+ Panel(
+ "[bold yellow]Standalone PostgreSQL container detected.[/bold yellow]\n\n"
+ "A container named [cyan]postgresql-container[/cyan] already exists "
+ f"([cyan]{container_state}[/cyan]). This is the standalone Postgres container "
+ "created by the local quickstart path and can conflict with Docker Compose "
+ "setups that bind Postgres to the host.\n\n"
+ "Docker Compose will create and manage its own [cyan]postgres[/cyan] service.",
+ border_style="yellow",
+ )
+ )
+ remove_container = Confirm.ask(
+ "Remove [cyan]postgresql-container[/cyan] before continuing?",
+ default=False,
+ )
+ if not remove_container:
+ console.print(
+ "[yellow]Continuing without removing postgresql-container. "
+ "If Docker Compose reports a Postgres conflict, rerun quickstart and remove it.[/yellow]"
+ )
+ capture_setup_event(
+ "docker-postgres-container-keep",
+ success=True,
+ extra_data={"state": container_state},
+ )
+ return
+
+ try:
+ subprocess.run(
+ ["docker", "rm", "-f", "postgresql-container"],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ except subprocess.CalledProcessError as e:
+ capture_setup_event(
+ "docker-postgres-container-remove-fail",
+ success=False,
+ error_type="docker_rm_error",
+ error_message=e.stderr.strip() if e.stderr else str(e),
+ )
+ console.print(f"[bold red]Failed to remove postgresql-container: {e.stderr}[/bold red]")
+ raise typer.Exit(1)
+
+ console.print("✅ [green]Removed standalone postgresql-container.[/green]")
+ capture_setup_event(
+ "docker-postgres-container-removed",
+ success=True,
+ extra_data={"state": container_state},
+ )
def _configure_cdp_livestreaming_defaults() -> None:
@@ -382,35 +563,8 @@ def run_docker_compose_setup() -> None:
console.print("\n[bold blue]Setting up Skyvern with Docker Compose...[/bold blue]")
capture_setup_event("docker-compose-start")
- # Check for postgres container conflict
- if check_postgres_container_conflict():
- capture_setup_event(
- "docker-port-conflict",
- success=False,
- error_type="port_conflict",
- error_message="PostgreSQL container 'postgresql-container' already exists on port 5432",
- extra_data={"port": 5432},
- )
- console.print(
- Panel(
- "[bold yellow]Warning: Existing PostgreSQL container detected![/bold yellow]\n\n"
- "A container named 'postgresql-container' already exists, which may conflict\n"
- "with the PostgreSQL service in Docker Compose (both use port 5432).\n\n"
- "To avoid conflicts, remove the existing container first:\n"
- "[cyan]docker rm -f postgresql-container[/cyan]",
- border_style="yellow",
- )
- )
- proceed = Confirm.ask("Do you want to continue anyway?", default=False)
- if not proceed:
- console.print("[yellow]Aborting Docker Compose setup. Please remove the container and try again.[/yellow]")
- capture_setup_event(
- "docker-compose-abort",
- success=False,
- error_type="user_abort",
- error_message="User aborted due to port conflict",
- )
- raise typer.Exit(0)
+ _handle_running_compose_stack()
+ _handle_postgres_container_conflict()
# Configure LLM provider
console.print("\n[bold blue]Step 1: Configure LLM Provider[/bold blue]")
@@ -622,9 +776,9 @@ def quickstart(
run_docker_compose_setup()
return
- if not has_server_extra:
- _print_server_guidance()
- raise typer.Exit(0)
+ if not _has_server_quickstart_extra():
+ if not _install_server_extra_for_quickstart() or not _has_server_quickstart_extra():
+ raise typer.Exit(1)
_run_server_quickstart(
no_postgres=no_postgres,
diff --git a/tests/unit/test_cli_bootstrap.py b/tests/unit/test_cli_bootstrap.py
index b2f59413c..f8e84d93d 100644
--- a/tests/unit/test_cli_bootstrap.py
+++ b/tests/unit/test_cli_bootstrap.py
@@ -13,16 +13,21 @@ from skyvern.utils.env_paths import BACKEND_ENV_INTENT_ENV_VAR, EnvIntent
def test_bootstrap_defaults_to_warning_without_explicit_log_level(monkeypatch) -> None:
monkeypatch.delenv("LOG_LEVEL", raising=False)
- logger_names = ("", "skyvern", "httpx", "litellm", "playwright", "httpcore")
+ logger_names = ("", "skyvern", "httpx", "litellm", "playwright", "httpcore", "posthog")
previous_levels = {name: logging.getLogger(name).level for name in logger_names}
+ previous_propagate = {name: logging.getLogger(name).propagate for name in logger_names}
try:
cli_bootstrap.configure_cli_bootstrap_logging()
assert "LOG_LEVEL" not in cli_bootstrap.os.environ
- for name in logger_names:
+ for name in ("", "skyvern", "httpx", "litellm", "playwright", "httpcore"):
assert logging.getLogger(name).level == logging.WARNING
+ assert logging.getLogger("posthog").level > logging.CRITICAL
+ assert logging.getLogger("posthog").propagate is False
finally:
for name, level in previous_levels.items():
logging.getLogger(name).setLevel(level)
+ for name, propagate in previous_propagate.items():
+ logging.getLogger(name).propagate = propagate
def test_bootstrap_honors_explicit_log_level(monkeypatch) -> None:
diff --git a/tests/unit/test_cli_database.py b/tests/unit/test_cli_database.py
new file mode 100644
index 000000000..2df09b199
--- /dev/null
+++ b/tests/unit/test_cli_database.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from skyvern.cli import database
+
+
+def test_create_database_and_user_treats_already_exists_as_success(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ calls.append(args)
+ env = kwargs["env"]
+ assert isinstance(env, dict)
+ assert env["LC_MESSAGES"] == "C"
+ if args[0] == "createuser":
+ return subprocess.CompletedProcess(
+ args,
+ 1,
+ stdout="",
+ stderr='createuser: error: creation of new role failed: ERROR: role "skyvern" already exists',
+ )
+ if args[0] == "createdb":
+ return subprocess.CompletedProcess(
+ args,
+ 1,
+ stdout="",
+ stderr='createdb: error: database creation failed: ERROR: database "skyvern" already exists',
+ )
+ raise AssertionError(f"Unexpected command: {args}")
+
+ monkeypatch.setattr(database, "_role_exists_via_catalog", lambda _user: False)
+ monkeypatch.setattr(database, "_database_exists_via_catalog", lambda _dbname: False)
+ monkeypatch.setattr(database.subprocess, "run", fake_run)
+
+ database.create_database_and_user()
+
+ assert calls == [["createuser", "skyvern"], ["createdb", "skyvern", "-O", "skyvern"]]
+
+
+def test_missing_local_server_dependency_detects_fuzzysearch() -> None:
+ from skyvern.cli.init_command import _missing_local_server_dependency
+
+ assert _missing_local_server_dependency(ModuleNotFoundError("No module named fuzzysearch", name="fuzzysearch")) == (
+ "fuzzysearch"
+ )
diff --git a/tests/unit/test_init_command.py b/tests/unit/test_init_command.py
new file mode 100644
index 000000000..4fad7634b
--- /dev/null
+++ b/tests/unit/test_init_command.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from skyvern.cli import init_command
+
+
+def test_server_extra_install_target_pins_installed_version(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(init_command.importlib.metadata, "version", lambda _package: "1.2.3")
+
+ assert init_command._server_extra_install_target() == "skyvern[server]==1.2.3"
+
+
+def test_server_extra_install_target_uses_source_checkout(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ (tmp_path / "pyproject.toml").write_text("[project]\nname = 'skyvern'\n", encoding="utf-8")
+ (tmp_path / "skyvern").mkdir()
+ monkeypatch.chdir(tmp_path)
+
+ assert init_command._server_extra_install_target() == ".[server]"
+
+
+def test_run_with_server_dependency_install_installs_and_retries(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[str] = []
+ install_calls: list[list[str]] = []
+
+ def action() -> str:
+ calls.append("action")
+ if len(calls) == 1:
+ raise ModuleNotFoundError("No module named fuzzysearch", name="fuzzysearch")
+ return "ok"
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ install_calls.append(args)
+ assert kwargs == {"check": True}
+ return subprocess.CompletedProcess(args, 0)
+
+ monkeypatch.setattr(init_command, "_SERVER_EXTRA_INSTALL_ATTEMPTED", False)
+ monkeypatch.setattr(init_command, "_server_extra_install_target", lambda: "skyvern[server]==1.2.3")
+ monkeypatch.setattr(init_command.Confirm, "ask", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr(init_command.subprocess, "run", fake_run)
+ monkeypatch.setattr(init_command.sys, "executable", "/usr/bin/python")
+
+ assert init_command._run_with_server_dependency_install(action) == "ok"
+ assert calls == ["action", "action"]
+ assert install_calls == [["/usr/bin/python", "-m", "pip", "install", "skyvern[server]==1.2.3"]]
diff --git a/tests/unit/test_quickstart.py b/tests/unit/test_quickstart.py
new file mode 100644
index 000000000..ddf3ca2be
--- /dev/null
+++ b/tests/unit/test_quickstart.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+import typer
+
+from skyvern.cli import init_command, quickstart
+
+
+def test_running_skyvern_compose_services_filters_expected_services(monkeypatch: pytest.MonkeyPatch) -> None:
+ result = subprocess.CompletedProcess(
+ ["docker", "compose", "ps"],
+ 0,
+ stdout="postgres\nskyvern\nskyvern-ui\nunrelated\n",
+ stderr="",
+ )
+ monkeypatch.setattr(quickstart, "_run_docker_command", lambda _args: result)
+
+ assert quickstart._running_skyvern_compose_services() == ["postgres", "skyvern", "skyvern-ui"]
+
+
+def test_handle_running_compose_stack_runs_down_when_confirmed(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+
+ def fake_run(args: list[str], **_: object) -> subprocess.CompletedProcess[str]:
+ calls.append(args)
+ return subprocess.CompletedProcess(args, 0, stdout="", stderr="")
+
+ monkeypatch.setattr(quickstart, "_running_skyvern_compose_services", lambda: ["skyvern", "skyvern-ui"])
+ monkeypatch.setattr(quickstart.Confirm, "ask", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr(quickstart.subprocess, "run", fake_run)
+ monkeypatch.setattr(quickstart, "capture_setup_event", lambda *_args, **_kwargs: None)
+
+ quickstart._handle_running_compose_stack()
+
+ assert calls == [["docker", "compose", "down"]]
+
+
+def test_handle_postgres_container_conflict_removes_when_confirmed(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+
+ def fake_run(args: list[str], **_: object) -> subprocess.CompletedProcess[str]:
+ calls.append(args)
+ return subprocess.CompletedProcess(args, 0, stdout="", stderr="")
+
+ monkeypatch.setattr(quickstart, "get_postgres_container_state", lambda: "running")
+ monkeypatch.setattr(quickstart.Confirm, "ask", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr(quickstart.subprocess, "run", fake_run)
+ monkeypatch.setattr(quickstart, "capture_setup_event", lambda *_args, **_kwargs: None)
+
+ quickstart._handle_postgres_container_conflict()
+
+ assert calls == [["docker", "rm", "-f", "postgresql-container"]]
+
+
+def test_quickstart_reraises_intentional_typer_exit(monkeypatch: pytest.MonkeyPatch) -> None:
+ capture_errors: list[object] = []
+
+ monkeypatch.setattr(
+ init_command,
+ "init_env",
+ lambda **_kwargs: (_ for _ in ()).throw(typer.Exit(1)),
+ )
+ monkeypatch.setattr(quickstart, "capture_setup_error", lambda *args, **_kwargs: capture_errors.append(args))
+
+ with pytest.raises(typer.Exit):
+ quickstart._run_server_quickstart(
+ no_postgres=False,
+ database_string="",
+ skip_browser_install=False,
+ server_only=False,
+ )
+
+ assert capture_errors == []
diff --git a/tests/unit/test_quickstart_command.py b/tests/unit/test_quickstart_command.py
index f3250ff4d..50d42271a 100644
--- a/tests/unit/test_quickstart_command.py
+++ b/tests/unit/test_quickstart_command.py
@@ -469,10 +469,20 @@ def test_quickstart_explicit_local_choice_without_local_extra_prints_install_ste
def test_quickstart_server_flags_select_server_path_without_server_extra(monkeypatch) -> None:
+ install_calls = []
+ server_calls = []
+ server_extra_checks = iter([False, False, True])
+
monkeypatch.setattr(quickstart_module, "check_docker_compose_file", lambda: False)
monkeypatch.setattr(quickstart_module, "_has_local_quickstart_extra", lambda: True)
- monkeypatch.setattr(quickstart_module, "_has_server_quickstart_extra", lambda: False)
+ monkeypatch.setattr(quickstart_module, "_has_server_quickstart_extra", lambda: next(server_extra_checks))
monkeypatch.setattr(quickstart_module, "_is_interactive_input", lambda: False)
+ monkeypatch.setattr(
+ quickstart_module,
+ "_install_server_extra_for_quickstart",
+ lambda: install_calls.append("install") or True,
+ )
+ monkeypatch.setattr(quickstart_module, "_run_server_quickstart", lambda **kwargs: server_calls.append(kwargs))
result = CliRunner().invoke(
quickstart_module.quickstart_app,
@@ -482,8 +492,15 @@ def test_quickstart_server_flags_select_server_path_without_server_extra(monkeyp
assert result.exit_code == 0
assert "Embedded local Python SDK" not in result.output
assert "Cloud/API SDK usage" not in result.output
- assert 'Install: pip install "skyvern[server]"' in result.output
- assert "Next: python -m skyvern quickstart" in result.output
+ assert install_calls == ["install"]
+ assert server_calls == [
+ {
+ "no_postgres": False,
+ "database_string": "postgresql+psycopg://user/db",
+ "skip_browser_install": False,
+ "server_only": False,
+ }
+ ]
def test_quickstart_explicit_install_type_overrides_server_flags(monkeypatch) -> None:
@@ -514,10 +531,11 @@ def test_quickstart_interactive_server_choice_without_server_extra_prints_instal
monkeypatch.setattr(quickstart_module, "_has_server_quickstart_extra", lambda: False)
monkeypatch.setattr(quickstart_module, "_is_interactive_input", lambda: True)
- result = CliRunner().invoke(quickstart_module.quickstart_app, [], input="3\n")
+ result = CliRunner().invoke(quickstart_module.quickstart_app, [], input="3\nn\n")
- assert result.exit_code == 0
+ assert result.exit_code == 1
assert "Choose a quickstart path" in result.output
+ assert "Install the missing server dependencies now?" in result.output
assert 'Install: pip install "skyvern[server]"' in result.output
assert "Next: python -m skyvern quickstart" in result.output
assert "local server, database, local API key, and MCP" in result.output
@@ -543,11 +561,12 @@ def test_quickstart_interactive_choice_reprompts_invalid_alias(monkeypatch) -> N
monkeypatch.setattr(quickstart_module, "_has_server_quickstart_extra", lambda: False)
monkeypatch.setattr(quickstart_module, "_is_interactive_input", lambda: True)
- result = CliRunner().invoke(quickstart_module.quickstart_app, [], input="wat\nserver\n")
+ result = CliRunner().invoke(quickstart_module.quickstart_app, [], input="wat\nserver\nn\n")
- assert result.exit_code == 0
+ assert result.exit_code == 1
assert "Choose one of: cloud/api, local/embedded, server/self-hosted, 1, 2, or 3." in result.output
assert "Please select a valid option:" not in result.output
+ assert "Install the missing server dependencies now?" in result.output
assert 'Install: pip install "skyvern[server]"' in result.output
@@ -571,19 +590,36 @@ def test_quickstart_interactive_eof_falls_back_to_default(monkeypatch) -> None:
def test_quickstart_server_flags_skip_docker_compose_offer_without_server_extra(monkeypatch) -> None:
calls = []
+ install_calls = []
+ server_calls = []
+ server_extra_checks = iter([False, False, True])
monkeypatch.setattr(quickstart_module, "check_docker", lambda: True)
monkeypatch.setattr(quickstart_module, "check_docker_compose_file", lambda: True)
monkeypatch.setattr(quickstart_module, "_has_local_quickstart_extra", lambda: False)
- monkeypatch.setattr(quickstart_module, "_has_server_quickstart_extra", lambda: False)
+ monkeypatch.setattr(quickstart_module, "_has_server_quickstart_extra", lambda: next(server_extra_checks))
monkeypatch.setattr(quickstart_module, "_is_interactive_input", lambda: False)
monkeypatch.setattr(quickstart_module, "run_docker_compose_setup", lambda: calls.append("docker"))
+ monkeypatch.setattr(
+ quickstart_module,
+ "_install_server_extra_for_quickstart",
+ lambda: install_calls.append("install") or True,
+ )
+ monkeypatch.setattr(quickstart_module, "_run_server_quickstart", lambda **kwargs: server_calls.append(kwargs))
result = CliRunner().invoke(quickstart_module.quickstart_app, ["--server-only"])
assert result.exit_code == 0
assert "Docker Compose file detected" not in result.output
- assert 'Install: pip install "skyvern[server]"' in result.output
+ assert install_calls == ["install"]
+ assert server_calls == [
+ {
+ "no_postgres": False,
+ "database_string": "",
+ "skip_browser_install": False,
+ "server_only": True,
+ }
+ ]
assert calls == []