chore: import upstream snapshot with attribution
CI / changes (push) Has been cancelled
CI / cd libs/checkpoint (push) Has been cancelled
CI / cd libs/checkpoint-conformance (push) Has been cancelled
CI / cd libs/checkpoint-postgres (push) Has been cancelled
CI / cd libs/checkpoint-sqlite (push) Has been cancelled
CI / cd libs/cli (push) Has been cancelled
CI / cd libs/prebuilt (push) Has been cancelled
CI / cd libs/sdk-py (push) Has been cancelled
CI / cd libs/langgraph (push) Has been cancelled
CI / Check SDK methods matching (push) Has been cancelled
CI / Check CLI schema hasn't changed #3.13 (push) Has been cancelled
CI / CLI integration test (push) Has been cancelled
CI / sdk-py integration test (push) Has been cancelled
CI / CI Success (push) Has been cancelled
baseline / benchmark (push) Has been cancelled
Deploy Redirects to GitHub Pages / deploy (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:37:18 +08:00
commit a7d6d88f6f
667 changed files with 232986 additions and 0 deletions
View File
@@ -0,0 +1,13 @@
import pytest
import requests
from langgraph_cli.templates import TEMPLATE_ID_TO_CONFIG
@pytest.mark.parametrize("template_key", TEMPLATE_ID_TO_CONFIG.keys())
def test_template_urls_work(template_key: str) -> None:
"""Integration test to verify that all template URLs are reachable."""
_, _, template_url = TEMPLATE_ID_TO_CONFIG[template_key]
response = requests.head(template_url)
# Returns 302 on a successful HEAD request
assert response.status_code == 302, f"URL {template_url} is not reachable."
+82
View File
@@ -0,0 +1,82 @@
import asyncio
import os
from collections.abc import Sequence
from typing import Annotated, TypedDict
from langchain_core.language_models.fake_chat_models import FakeListChatModel
from langchain_core.messages import BaseMessage, HumanMessage, ToolMessage
from langgraph.graph import END, StateGraph, add_messages
# check that env var is present
os.environ["SOME_ENV_VAR"]
class AgentState(TypedDict):
some_bytes: bytes
some_byte_array: bytearray
dict_with_bytes: dict[str, bytes]
messages: Annotated[Sequence[BaseMessage], add_messages]
sleep: int
async def call_model(state, config):
if sleep := state.get("sleep"):
await asyncio.sleep(sleep)
messages = state["messages"]
if len(messages) > 1:
assert state["some_bytes"] == b"some_bytes"
assert state["some_byte_array"] == bytearray(b"some_byte_array")
assert state["dict_with_bytes"] == {"more_bytes": b"more_bytes"}
# hacky way to reset model to the "first" response
if isinstance(messages[-1], HumanMessage):
model.i = 0
response = await model.ainvoke(messages)
return {
"messages": [response],
"some_bytes": b"some_bytes",
"some_byte_array": bytearray(b"some_byte_array"),
"dict_with_bytes": {"more_bytes": b"more_bytes"},
}
def call_tool(state):
last_message_content = state["messages"][-1].content
return {
"messages": [
ToolMessage(
f"tool_call__{last_message_content}", tool_call_id="tool_call_id"
)
]
}
def should_continue(state):
messages = state["messages"]
last_message = messages[-1]
if last_message.content == "end":
return END
else:
return "tool"
# NOTE: the model cycles through responses infinitely here
model = FakeListChatModel(responses=["begin", "end"])
workflow = StateGraph(AgentState)
workflow.add_node("agent", call_model)
workflow.add_node("tool", call_tool)
workflow.set_entry_point("agent")
workflow.add_conditional_edges(
"agent",
should_continue,
)
workflow.add_edge("tool", "agent")
graph = workflow.compile()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,70 @@
"""Unit tests for the 'new' CLI command.
This command creates a new LangGraph project using a specified template.
"""
import os
from io import BytesIO
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import MagicMock, patch
from urllib import request
from zipfile import ZipFile
from click.testing import CliRunner
from langgraph_cli.cli import cli
from langgraph_cli.templates import TEMPLATE_ID_TO_CONFIG
@patch.object(request, "urlopen")
def test_create_new_with_mocked_download(mock_urlopen: MagicMock) -> None:
"""Test the 'new' CLI command with a mocked download response using urllib."""
# Mock the response content to simulate a ZIP file
mock_zip_content = BytesIO()
with ZipFile(mock_zip_content, "w") as mock_zip:
mock_zip.writestr("test-file.txt", "Test content.")
# Create a mock response that behaves like a context manager
mock_response = MagicMock()
mock_response.read.return_value = mock_zip_content.getvalue()
mock_response.__enter__.return_value = mock_response # Setup enter context
mock_response.status = 200
mock_urlopen.return_value = mock_response
with TemporaryDirectory() as temp_dir:
runner = CliRunner()
template = next(
iter(TEMPLATE_ID_TO_CONFIG)
) # Select the first template for the test
result = runner.invoke(cli, ["new", temp_dir, "--template", template])
# Verify CLI command execution and success
assert result.exit_code == 0, result.output
assert "New project created" in result.output, (
"Expected success message in output."
)
# Verify that the directory is not empty
assert os.listdir(temp_dir), "Expected files to be created in temp directory."
# Check for a known file in the extracted content
extracted_files = [f.name for f in Path(temp_dir).glob("*")]
assert "test-file.txt" in extracted_files, (
"Expected 'test-file.txt' in the extracted content."
)
def test_invalid_template_id() -> None:
"""Test that an invalid template ID passed via CLI results in a graceful error."""
runner = CliRunner()
result = runner.invoke(
cli, ["new", "dummy_path", "--template", "invalid-template-id"]
)
# Verify the command failed and proper message is displayed
assert result.exit_code != 0, "Expected non-zero exit code for invalid template."
assert "Template 'invalid-template-id' not found" in result.output, (
"Expected error message in output."
)
+16
View File
@@ -0,0 +1,16 @@
import os
from unittest.mock import patch
import pytest
@pytest.fixture(autouse=True)
def disable_analytics_env() -> None:
"""Disable analytics for unit tests LANGGRAPH_CLI_NO_ANALYTICS."""
# First check if the environment variable is already set, if so, log a warning prior
# to overriding it.
if "LANGGRAPH_CLI_NO_ANALYTICS" in os.environ:
print("⚠️ LANGGRAPH_CLI_NO_ANALYTICS is set. Overriding it for the test.")
with patch.dict(os.environ, {"LANGGRAPH_CLI_NO_ANALYTICS": "0"}):
yield
@@ -0,0 +1,6 @@
from langgraph.func import entrypoint
@entrypoint()
def graph(state):
return None
+2
View File
@@ -0,0 +1,2 @@
def clean_empty_lines(input_str: str):
return "\n".join(filter(None, input_str.splitlines()))
+305
View File
@@ -0,0 +1,305 @@
import os
import tarfile
from unittest.mock import patch
import click
import pytest
from langgraph_cli.archive import (
_add_directory,
_build_ignore_spec,
_tar_filter,
create_archive,
)
# ---------------------------------------------------------------------------
# _tar_filter
# ---------------------------------------------------------------------------
class TestTarFilter:
def _make_info(self, name: str, *, type_: int = tarfile.REGTYPE) -> tarfile.TarInfo:
info = tarfile.TarInfo(name=name)
info.type = type_
return info
def test_regular_file_passes(self):
info = self._make_info("src/main.py")
assert _tar_filter(info) is info
def test_symlink_rejected(self):
info = self._make_info("link", type_=tarfile.SYMTYPE)
assert _tar_filter(info) is None
def test_hardlink_rejected(self):
info = self._make_info("link", type_=tarfile.LNKTYPE)
assert _tar_filter(info) is None
def test_path_traversal_rejected(self):
info = self._make_info("../../etc/passwd")
assert _tar_filter(info) is None
def test_path_traversal_in_middle_rejected(self):
info = self._make_info("src/../../../etc/passwd")
assert _tar_filter(info) is None
def test_dotdot_as_name_component_rejected(self):
info = self._make_info("foo/../bar")
assert _tar_filter(info) is None
def test_dotdot_in_filename_allowed(self):
"""A file literally named 'foo..bar' is not traversal."""
info = self._make_info("foo..bar")
assert _tar_filter(info) is info
def test_directory_passes(self):
info = self._make_info("src/", type_=tarfile.DIRTYPE)
assert _tar_filter(info) is info
# ---------------------------------------------------------------------------
# _build_ignore_spec
# ---------------------------------------------------------------------------
class TestBuildIgnoreSpec:
def test_always_excludes_builtins(self, tmp_path):
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("__pycache__/")
assert spec.match_file(".git/")
assert spec.match_file(".venv/")
assert spec.match_file("venv/")
assert spec.match_file("node_modules/")
assert spec.match_file(".tox/")
def test_regular_file_not_excluded(self, tmp_path):
spec = _build_ignore_spec(tmp_path)
assert not spec.match_file("main.py")
assert not spec.match_file("src/app.py")
def test_merges_dockerignore(self, tmp_path):
(tmp_path / ".dockerignore").write_text("*.log\nbuild/\n")
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("server.log")
assert spec.match_file("build/")
# builtins still present
assert spec.match_file("__pycache__/")
def test_merges_gitignore(self, tmp_path):
(tmp_path / ".gitignore").write_text("*.pyc\ndist/\n")
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("module.pyc")
assert spec.match_file("dist/")
def test_merges_both_ignore_files(self, tmp_path):
(tmp_path / ".dockerignore").write_text("*.log\n")
(tmp_path / ".gitignore").write_text("*.pyc\n")
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("app.log")
assert spec.match_file("mod.pyc")
def test_can_skip_gitignore(self, tmp_path):
(tmp_path / ".dockerignore").write_text("*.log\n")
(tmp_path / ".gitignore").write_text("*.pyc\n")
spec = _build_ignore_spec(tmp_path, include_gitignore=False)
assert spec.match_file("app.log")
assert not spec.match_file("mod.pyc")
def test_no_ignore_files_only_builtins(self, tmp_path):
spec = _build_ignore_spec(tmp_path)
assert spec.match_file("__pycache__/")
assert not spec.match_file("README.md")
# ---------------------------------------------------------------------------
# _add_directory
# ---------------------------------------------------------------------------
class TestAddDirectory:
def _create_project(self, tmp_path):
"""Create a small project structure for testing."""
(tmp_path / "main.py").write_text("print('hello')")
(tmp_path / "lib").mkdir()
(tmp_path / "lib" / "util.py").write_text("x = 1")
(tmp_path / "__pycache__").mkdir()
(tmp_path / "__pycache__" / "main.cpython-311.pyc").write_bytes(b"\x00")
return tmp_path
def test_adds_files_without_prefix(self, tmp_path):
project = self._create_project(tmp_path)
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix=None, ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert "main.py" in names
assert "lib/util.py" in names
def test_excludes_pycache(self, tmp_path):
project = self._create_project(tmp_path)
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix=None, ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert not any("__pycache__" in n for n in names)
def test_adds_files_with_prefix(self, tmp_path):
project = self._create_project(tmp_path)
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix="myapp", ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert "myapp/main.py" in names
assert "myapp/lib/util.py" in names
def test_respects_custom_ignore_patterns(self, tmp_path):
project = self._create_project(tmp_path)
(project / ".gitignore").write_text("lib/\n")
spec = _build_ignore_spec(project)
archive_path = tmp_path / "out.tar"
with tarfile.open(archive_path, "w") as tar:
_add_directory(tar, project, arcname_prefix=None, ignore_spec=spec)
with tarfile.open(archive_path, "r") as tar:
names = tar.getnames()
assert "main.py" in names
assert "lib/util.py" not in names
# ---------------------------------------------------------------------------
# create_archive (integration)
# ---------------------------------------------------------------------------
class TestCreateArchive:
def _make_project(self, tmp_path):
"""Set up a minimal project directory with a config file."""
project = tmp_path / "myproject"
project.mkdir()
config_file = project / "langgraph.json"
config_file.write_text('{"dependencies": ["."]}')
(project / "app.py").write_text("print('hello')")
(project / "__pycache__").mkdir()
(project / "__pycache__" / "app.cpython-311.pyc").write_bytes(b"\x00")
return config_file
@patch("langgraph_cli.archive._assemble_local_deps")
def test_yields_archive_with_config(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with create_archive(config_file, {}) as (archive_path, file_size, config_rel):
assert os.path.isfile(archive_path)
assert archive_path.endswith(".tar.gz")
assert file_size > 0
assert config_rel == "langgraph.json"
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
assert "langgraph.json" in names
assert "app.py" in names
@patch("langgraph_cli.archive._assemble_local_deps")
def test_excludes_pycache(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with create_archive(config_file, {}) as (archive_path, _size, _rel):
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
assert not any("__pycache__" in n for n in names)
@patch("langgraph_cli.archive._assemble_local_deps")
def test_cleans_up_tmp_dir_on_normal_exit(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with create_archive(config_file, {}) as (archive_path, _size, _rel):
tmp_dir = os.path.dirname(archive_path)
assert os.path.isdir(tmp_dir)
assert not os.path.exists(tmp_dir)
@patch("langgraph_cli.archive._assemble_local_deps")
def test_cleans_up_tmp_dir_on_exception(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with pytest.raises(RuntimeError, match="boom"):
with create_archive(config_file, {}) as (archive_path, _size, _rel):
tmp_dir = os.path.dirname(archive_path)
raise RuntimeError("boom")
assert not os.path.exists(tmp_dir)
@patch("langgraph_cli.archive._assemble_local_deps")
@patch("langgraph_cli.archive._MAX_SIZE", 10)
def test_raises_on_oversized_archive(self, mock_deps, tmp_path):
from langgraph_cli.config import LocalDeps
config_file = self._make_project(tmp_path)
mock_deps.return_value = LocalDeps(
pip_reqs=[], real_pkgs={}, faux_pkgs={}, additional_contexts=None
)
with pytest.raises(click.ClickException, match="exceeds the 200 MB limit"):
with create_archive(config_file, {}):
pass
@patch("langgraph_cli.archive._assemble_local_deps")
def test_handles_extra_contexts(self, mock_deps, tmp_path):
"""Monorepo case: project + sibling dependency directory."""
from langgraph_cli.config import LocalDeps
project = tmp_path / "myproject"
project.mkdir()
config_file = project / "langgraph.json"
config_file.write_text('{"dependencies": [".", "../shared"]}')
(project / "app.py").write_text("print('hello')")
shared = tmp_path / "shared"
shared.mkdir()
(shared / "lib.py").write_text("y = 2")
mock_deps.return_value = LocalDeps(
pip_reqs=[],
real_pkgs={},
faux_pkgs={},
additional_contexts=[shared],
)
with create_archive(config_file, {}) as (archive_path, _size, config_rel):
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
assert "myproject/app.py" in names
assert "shared/lib.py" in names
assert config_rel == "myproject/langgraph.json"
@@ -0,0 +1,19 @@
{
"python_version": "3.12",
"pip_config_file": "pipconfig.txt",
"dockerfile_lines": [
"ARG meow=woof"
],
"dependencies": [
"langchain_openai",
"starlette",
"."
],
"graphs": {
"agent": "graphs/agent.py:graph"
},
"env": ".env",
"http": {
"app": "../../examples/my_app.py:app"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,134 @@
import pathlib
import pytest
from langgraph_cli.dependency_tracking import (
TRACKED_PACKAGES,
find_tracked_packages,
)
def _write_project(
tmp_path: pathlib.Path,
*,
dep_subdir: str = ".",
uv_lock: str | None = None,
pyproject: str | None = None,
requirements: str | None = None,
dependencies: list[str] | None = None,
) -> tuple[pathlib.Path, dict]:
project_root = tmp_path
dep_dir = (project_root / dep_subdir).resolve()
dep_dir.mkdir(parents=True, exist_ok=True)
if uv_lock is not None:
(dep_dir / "uv.lock").write_text(uv_lock)
if pyproject is not None:
(dep_dir / "pyproject.toml").write_text(pyproject)
if requirements is not None:
(dep_dir / "requirements.txt").write_text(requirements)
config = project_root / "langgraph.json"
config.write_text("{}")
config_json = {"dependencies": dependencies or [dep_subdir]}
return config, config_json
def test_uv_lock_resolved_version_preferred(tmp_path: pathlib.Path) -> None:
config, config_json = _write_project(
tmp_path,
uv_lock='name = "google-adk"\nversion = "1.2.3"\n',
pyproject='dependencies = ["google-adk>=0.5"]',
)
assert find_tracked_packages(config, config_json) == ["google-adk:1.2.3"]
def test_pyproject_specifier_used_when_no_lock(tmp_path: pathlib.Path) -> None:
config, config_json = _write_project(
tmp_path,
pyproject='dependencies = ["google-adk>=0.5,<2"]',
)
assert find_tracked_packages(config, config_json) == ["google-adk:>=0.5,<2"]
def test_requirements_txt_specifier(tmp_path: pathlib.Path) -> None:
config, config_json = _write_project(
tmp_path,
requirements="google-adk==1.0.0\n",
)
assert find_tracked_packages(config, config_json) == ["google-adk:==1.0.0"]
def test_bare_reference_records_unknown(tmp_path: pathlib.Path) -> None:
config, config_json = _write_project(
tmp_path,
requirements="google-adk\nother-pkg==1.0\n",
)
assert find_tracked_packages(config, config_json) == ["google-adk:unknown"]
def test_extras_bracket_records_unknown(tmp_path: pathlib.Path) -> None:
config, config_json = _write_project(
tmp_path,
pyproject='dependencies = ["deployments-wrap-sdk[google-adk]>=0.0.1"]',
)
assert find_tracked_packages(config, config_json) == ["google-adk:unknown"]
def test_no_match_returns_empty(tmp_path: pathlib.Path) -> None:
config, config_json = _write_project(
tmp_path,
pyproject='dependencies = ["langgraph>=0.2"]',
)
assert find_tracked_packages(config, config_json) == []
def test_traversal_dep_path_is_skipped(tmp_path: pathlib.Path) -> None:
outside = tmp_path.parent / "outside-project"
outside.mkdir(exist_ok=True)
(outside / "uv.lock").write_text('name = "google-adk"\nversion = "9.9.9"\n')
project_root = tmp_path / "project"
project_root.mkdir()
config = project_root / "langgraph.json"
config.write_text("{}")
config_json = {"dependencies": ["../outside-project"]}
assert find_tracked_packages(config, config_json) == []
def test_dep_paths_scanned_in_order(tmp_path: pathlib.Path) -> None:
project_root = tmp_path
(project_root / "first").mkdir()
(project_root / "second").mkdir()
(project_root / "second" / "uv.lock").write_text(
'name = "google-adk"\nversion = "2.0.0"\n'
)
config = project_root / "langgraph.json"
config.write_text("{}")
config_json = {"dependencies": ["first", "second"]}
assert find_tracked_packages(config, config_json) == ["google-adk:2.0.0"]
def test_non_string_dep_entry_ignored(tmp_path: pathlib.Path) -> None:
project_root = tmp_path
config = project_root / "langgraph.json"
config.write_text("{}")
config_json = {"dependencies": [123, None]}
assert find_tracked_packages(config, config_json) == []
def test_oversized_file_is_truncated_not_raised(tmp_path: pathlib.Path) -> None:
project_root = tmp_path
config = project_root / "langgraph.json"
config.write_text("{}")
# 6 MB of irrelevant content followed by the tracked-package marker —
# the read cap drops the marker, so nothing should be found.
padded = ("x" * (6 * 1024 * 1024)) + '\nname = "google-adk"\nversion = "1.0.0"\n'
(project_root / "uv.lock").write_text(padded)
assert find_tracked_packages(config, {"dependencies": ["."]}) == []
@pytest.mark.parametrize("pkg", TRACKED_PACKAGES)
def test_every_tracked_package_is_detectable(tmp_path: pathlib.Path, pkg: str) -> None:
config, config_json = _write_project(
tmp_path,
uv_lock=f'name = "{pkg}"\nversion = "1.0.0"\n',
)
assert find_tracked_packages(config, config_json) == [f"{pkg}:1.0.0"]
@@ -0,0 +1,752 @@
import asyncio
import base64
import io
import json
import os
import sys
from unittest.mock import MagicMock
import click
import click.exceptions
import httpx
import pytest
import langgraph_cli.deploy as deploy_mod
from langgraph_cli.deploy import (
_call_host_backend_with_optional_tenant,
_create_host_backend_client,
_docker_config_for_token,
_Emitter,
_env_without_deployment_name,
_parse_env_from_config,
_resolve_env_path,
_resolve_pushed_image_digest,
_smith_dashboard_base_url,
_validate_prebuilt_image,
normalize_image_tag,
normalize_name,
)
from langgraph_cli.host_backend import HostBackendClient, HostBackendError
class TestDockerConfigForToken:
def test_creates_config_json(self):
with _docker_config_for_token("us-docker.pkg.dev", "my-token") as cfg:
config_path = os.path.join(cfg, "config.json")
assert os.path.isfile(config_path)
with open(config_path) as f:
data = json.load(f)
expected_auth = base64.b64encode(b"oauth2accesstoken:my-token").decode()
assert data == {"auths": {"us-docker.pkg.dev": {"auth": expected_auth}}}
def test_tempdir_cleaned_up(self):
with _docker_config_for_token("registry.example.com", "tok") as cfg:
assert os.path.isdir(cfg)
assert not os.path.exists(cfg)
def test_different_registries(self):
with _docker_config_for_token("gcr.io", "token123") as cfg:
with open(os.path.join(cfg, "config.json")) as f:
data = json.load(f)
assert "gcr.io" in data["auths"]
class TestNormalizeName:
def test_simple_name(self):
assert normalize_name("myapp") == "myapp"
def test_uppercase_lowered(self):
assert normalize_name("MyApp") == "myapp"
def test_special_chars_replaced(self):
assert normalize_name("my app!@#v2") == "my-app-v2"
def test_dots_replaced_with_hyphens(self):
assert normalize_name("my-app.v2") == "my-app-v2"
def test_underscores_replaced_with_hyphens(self):
assert normalize_name("simple_graph_name") == "simple-graph-name"
def test_leading_trailing_stripped(self):
assert normalize_name("--my-app..") == "my-app"
def test_empty_string_returns_app(self):
assert normalize_name("") == "app"
def test_none_returns_app(self):
assert normalize_name(None) == "app"
def test_all_invalid_chars_returns_app(self):
assert normalize_name("!!!") == "app"
class TestNormalizeImageTag:
def test_valid_tag(self):
assert normalize_image_tag("v1.2.3") == "v1.2.3"
def test_empty_defaults_to_latest(self):
assert normalize_image_tag("") == "latest"
def test_alphanumeric_and_special(self):
assert normalize_image_tag("my_tag-1.0") == "my_tag-1.0"
def test_invalid_chars_raises(self):
with pytest.raises(click.UsageError, match="Image tag may only contain"):
normalize_image_tag("v1.0:bad")
def test_spaces_raises(self):
with pytest.raises(click.UsageError, match="Image tag may only contain"):
normalize_image_tag("has space")
class _FakeRunner:
def run(self, coro):
return asyncio.run(coro)
class TestValidatePrebuiltImage:
def test_accepts_linux_amd64(self, monkeypatch):
calls = []
async def fake_subp_exec(*args, **kwargs):
calls.append((args, kwargs))
return "linux/amd64\n", None
monkeypatch.setattr(deploy_mod, "subp_exec", fake_subp_exec)
_validate_prebuilt_image(_FakeRunner(), "repo/app:tag", verbose=False)
assert calls == [
(
(
"docker",
"image",
"inspect",
"--format",
"{{.Os}}/{{.Architecture}}",
"repo/app:tag",
),
{"verbose": False, "collect": True},
)
]
def test_missing_docker_binary_raises_actionable_error(self, monkeypatch):
async def fake_subp_exec(*args, **kwargs):
raise FileNotFoundError("docker")
monkeypatch.setattr(deploy_mod, "subp_exec", fake_subp_exec)
with pytest.raises(click.ClickException, match="Docker is required"):
_validate_prebuilt_image(_FakeRunner(), "repo/app:tag", verbose=False)
def test_missing_image_raises_actionable_error(self, monkeypatch):
async def fake_subp_exec(*args, **kwargs):
raise click.exceptions.Exit(1)
monkeypatch.setattr(deploy_mod, "subp_exec", fake_subp_exec)
with pytest.raises(click.ClickException, match="not found locally"):
_validate_prebuilt_image(_FakeRunner(), "missing:tag", verbose=False)
def test_rejects_non_amd64_platform(self, monkeypatch):
async def fake_subp_exec(*args, **kwargs):
return "linux/arm64\n", None
monkeypatch.setattr(deploy_mod, "subp_exec", fake_subp_exec)
with pytest.raises(click.ClickException, match="requires linux/amd64"):
_validate_prebuilt_image(_FakeRunner(), "repo/app:arm", verbose=False)
class TestParseEnvFromConfig:
def test_env_dict(self, tmp_path):
config_path = tmp_path / "langgraph.json"
config_path.touch()
result = _parse_env_from_config({"env": {"FOO": "bar", "NUM": 42}}, config_path)
assert result == {"FOO": "bar", "NUM": "42"}
def test_env_string_dotenv_file(self, tmp_path):
env_file = tmp_path / "my.env"
env_file.write_text("KEY1=val1\nKEY2=val2\n")
config_path = tmp_path / "langgraph.json"
config_path.touch()
result = _parse_env_from_config({"env": "my.env"}, config_path)
assert result == {"KEY1": "val1", "KEY2": "val2"}
def test_env_missing_falls_back_to_dotenv(self, tmp_path, monkeypatch):
env_file = tmp_path / ".env"
env_file.write_text("DEFAULT_KEY=default_val\n")
monkeypatch.chdir(tmp_path)
config_path = tmp_path / "langgraph.json"
config_path.touch()
result = _parse_env_from_config({}, config_path)
assert result == {"DEFAULT_KEY": "default_val"}
def test_env_empty_dict_falls_back_to_dotenv(self, tmp_path, monkeypatch):
"""validate_config defaults env to {}, should still fall back to .env."""
env_file = tmp_path / ".env"
env_file.write_text("MY_KEY=my_val\n")
monkeypatch.chdir(tmp_path)
config_path = tmp_path / "langgraph.json"
config_path.touch()
result = _parse_env_from_config({"env": {}}, config_path)
assert result == {"MY_KEY": "my_val"}
def test_env_missing_no_dotenv_returns_empty(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
config_path = tmp_path / "langgraph.json"
config_path.touch()
result = _parse_env_from_config({}, config_path)
assert result == {}
def test_env_dotenv_filters_none_values(self, tmp_path):
# Lines like "KEY=" produce empty string, lines like "KEY" produce None
env_file = tmp_path / "test.env"
env_file.write_text("GOOD=value\nEMPTY=\n")
config_path = tmp_path / "langgraph.json"
config_path.touch()
result = _parse_env_from_config({"env": "test.env"}, config_path)
assert "GOOD" in result
assert result["GOOD"] == "value"
# EMPTY= gives empty string, not None, so it should be present
assert result["EMPTY"] == ""
class TestResolveEnvPath:
def test_inline_env_dict_returns_none(self, tmp_path):
config_path = tmp_path / "langgraph.json"
config_path.touch()
assert _resolve_env_path({"env": {"FOO": "bar"}}, config_path) is None
def test_relative_env_path_resolves(self, tmp_path):
env_file = tmp_path / "custom.env"
env_file.write_text("FOO=bar\n")
config_path = tmp_path / "langgraph.json"
config_path.touch()
resolved = _resolve_env_path({"env": "custom.env"}, config_path)
assert resolved == env_file.resolve()
def test_missing_env_file_returns_none(self, tmp_path):
config_path = tmp_path / "langgraph.json"
config_path.touch()
assert _resolve_env_path({"env": "missing.env"}, config_path) is None
def test_default_env_is_cwd_dotenv(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
config_path = tmp_path / "langgraph.json"
config_path.touch()
assert _resolve_env_path({}, config_path) == tmp_path / ".env"
class TestEnvWithoutDeploymentName:
def test_removes_deployment_name_only(self):
env = {
"LANGSMITH_DEPLOYMENT_NAME": "my-deploy",
"KEEP_ME": "value",
}
cleaned = _env_without_deployment_name(env)
assert "LANGSMITH_DEPLOYMENT_NAME" not in cleaned
assert cleaned["KEEP_ME"] == "value"
# Original dict should be unchanged.
assert env["LANGSMITH_DEPLOYMENT_NAME"] == "my-deploy"
def test_noop_when_deployment_name_absent(self):
env = {"FOO": "bar"}
assert _env_without_deployment_name(env) == {"FOO": "bar"}
class TestCallHostBackendWithOptionalTenant:
def _make_client(self, handler):
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
return c
def _make_eu_client(self, handler):
c = HostBackendClient("https://eu.api.host.langchain.com", "test-key")
c._client = httpx.Client(
base_url="https://eu.api.host.langchain.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
return c
def test_success_passes_through(self):
client = self._make_client(lambda req: httpx.Response(200, json={"ok": True}))
result = _call_host_backend_with_optional_tenant(
client, lambda c: c.list_deployments()
)
assert result == {"ok": True}
def test_403_not_enabled_gives_actionable_error(self):
detail = (
'{"detail":"LangSmith Deployment is not enabled for this organization"}'
)
client = self._make_client(lambda req: httpx.Response(403, text=detail))
with pytest.raises(HostBackendError, match="not enabled") as exc_info:
_call_host_backend_with_optional_tenant(
client, lambda c: c.list_deployments()
)
assert exc_info.value.status_code == 403
assert "smith.langchain.com" in exc_info.value.message
def test_403_not_enabled_eu_url(self):
detail = (
'{"detail":"LangSmith Deployment is not enabled for this organization"}'
)
client = self._make_eu_client(lambda req: httpx.Response(403, text=detail))
with pytest.raises(HostBackendError, match="not enabled") as exc_info:
_call_host_backend_with_optional_tenant(
client, lambda c: c.list_deployments()
)
assert "eu.smith.langchain.com" in exc_info.value.message
def test_workspace_retry_then_not_enabled_gives_actionable_error(self, monkeypatch):
requires_workspace = '{"detail":"requires workspace specification"}'
not_enabled = (
'{"detail":"LangSmith Deployment is not enabled for this organization"}'
)
seen_tenant_ids = []
def handler(req):
seen_tenant_ids.append(req.headers.get("X-Tenant-ID"))
if len(seen_tenant_ids) == 1:
return httpx.Response(403, text=requires_workspace)
if len(seen_tenant_ids) == 2:
return httpx.Response(403, text=not_enabled)
raise AssertionError("unexpected extra request")
monkeypatch.setattr(click, "prompt", lambda _text: "workspace-123")
client = self._make_client(handler)
with pytest.raises(HostBackendError, match="not enabled") as exc_info:
_call_host_backend_with_optional_tenant(
client, lambda c: c.list_deployments()
)
assert exc_info.value.status_code == 403
assert "smith.langchain.com" in exc_info.value.message
assert seen_tenant_ids == [None, "workspace-123"]
assert client._client.headers["X-Tenant-ID"] == "workspace-123"
def test_other_403_re_raises_original(self):
client = self._make_client(
lambda req: httpx.Response(403, text='{"detail":"some other error"}')
)
with pytest.raises(HostBackendError, match="some other error"):
_call_host_backend_with_optional_tenant(
client, lambda c: c.list_deployments()
)
def test_workspace_prompt_blocked_by_no_input(self, monkeypatch):
"""With _no_input=True, 403 requiring workspace should raise ClickException."""
import langgraph_cli.deploy as deploy_mod
monkeypatch.setattr(deploy_mod, "_no_input", True)
requires_workspace = '{"detail":"requires workspace specification"}'
client = self._make_client(
lambda req: httpx.Response(403, text=requires_workspace)
)
with pytest.raises(click.ClickException, match="workspace"):
_call_host_backend_with_optional_tenant(
client, lambda c: c.list_deployments()
)
# ---------------------------------------------------------------------------
# _Emitter JSON mode
# ---------------------------------------------------------------------------
class TestEmitterJsonMode:
"""Verify that _Emitter in json_mode writes valid JSON-lines to stdout."""
def _capture(self, fn):
"""Run fn with stdout captured and return parsed JSON objects."""
buf = io.StringIO()
old = sys.stdout
sys.stdout = buf
try:
fn()
finally:
sys.stdout = old
lines = [line for line in buf.getvalue().splitlines() if line.strip()]
return [json.loads(line) for line in lines]
def test_step_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.step(1, "Building image"))
assert len(events) == 1
assert events[0]["event"] == "step"
assert events[0]["step"] == 1
assert events[0]["message"] == "Building image"
def test_info_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.info("All good"))
assert events[0]["event"] == "info"
assert events[0]["message"] == "All good"
def test_warn_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.warn("Careful"))
assert events[0]["event"] == "warn"
def test_error_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.error("Boom"))
assert events[0]["event"] == "error"
assert events[0]["message"] == "Boom"
def test_status_change_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.status_change("building", 12.345))
assert events[0]["event"] == "status_change"
assert events[0]["status"] == "building"
assert events[0]["elapsed_seconds"] == 12.3
assert events[0]["message"] == "building... (12s)"
def test_status_change_event_with_minutes(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.status_change("deploying", 95.0))
assert events[0]["message"] == "deploying... (1m 35s)"
def test_log_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.log("some output"))
assert events[0] == {"event": "log", "message": "some output"}
def test_status_url_event(self):
em = _Emitter(json_mode=True)
events = self._capture(
lambda: em.status_url("https://smith.langchain.com/deploy/123")
)
assert events[0]["event"] == "status_url"
assert events[0]["url"] == "https://smith.langchain.com/deploy/123"
def test_result_event_full(self):
em = _Emitter(json_mode=True)
events = self._capture(
lambda: em.result(
"succeeded",
deployment_id="dep-1",
url="https://app.example.com",
status_url="https://smith.langchain.com/deploy/dep-1",
)
)
assert events[0]["event"] == "result"
assert events[0]["status"] == "succeeded"
assert events[0]["deployment_id"] == "dep-1"
assert events[0]["message"] == "Deployment successful!"
assert events[0]["url"] == "https://app.example.com"
assert events[0]["status_url"] == "https://smith.langchain.com/deploy/dep-1"
def test_result_event_minimal(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.result("failed", deployment_id="dep-2"))
assert events[0]["event"] == "result"
assert events[0]["status"] == "failed"
assert events[0]["message"] == "Deployment failed"
assert "url" not in events[0]
assert "status_url" not in events[0]
def test_heartbeat_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.heartbeat("building", 30.789))
assert events[0]["event"] == "heartbeat"
assert events[0]["elapsed_seconds"] == 30.8
assert events[0]["message"] == "building... (30s)"
def test_heartbeat_silent_in_text_mode(self, capsys):
em = _Emitter(json_mode=False)
em.heartbeat("building", 10.0)
captured = capsys.readouterr()
assert captured.out == ""
def test_upload_progress_event(self):
em = _Emitter(json_mode=True)
events = self._capture(lambda: em.upload_progress(5.678, 42))
assert events[0]["event"] == "upload_progress"
assert events[0]["size_mb"] == 5.7
assert events[0]["pct"] == 42
# ---------------------------------------------------------------------------
# _Emitter text mode (non-json)
# ---------------------------------------------------------------------------
class TestEmitterTextMode:
"""Verify that _Emitter in text mode uses click.echo/click.secho."""
def test_step_writes_text(self, capsys):
em = _Emitter(json_mode=False)
em.step(1, "Hello")
captured = capsys.readouterr()
assert "1. Hello" in captured.out
def test_log_writes_text(self, capsys):
em = _Emitter(json_mode=False)
em.log("my line")
captured = capsys.readouterr()
assert "my line" in captured.out
def test_result_succeeded_text(self, capsys):
em = _Emitter(json_mode=False)
em.result("succeeded", deployment_id="d1", url="https://app.test")
captured = capsys.readouterr()
lines = [line.strip() for line in captured.out.splitlines() if line.strip()]
assert "Deployment successful!" in lines
assert "URL: https://app.test" in lines
# ---------------------------------------------------------------------------
# --no-input guard on _create_host_backend_client
# ---------------------------------------------------------------------------
class TestCreateHostBackendClientNoInput:
def test_raises_when_no_api_key_and_no_input(self, monkeypatch, tmp_path):
import langgraph_cli.deploy as deploy_mod
monkeypatch.setattr(deploy_mod, "_no_input", True)
monkeypatch.delenv("LANGSMITH_API_KEY", raising=False)
monkeypatch.delenv("LANGCHAIN_API_KEY", raising=False)
monkeypatch.delenv("LANGGRAPH_HOST_API_KEY", raising=False)
with pytest.raises(click.ClickException, match="API key"):
_create_host_backend_client(
host_url="https://api.example.com",
api_key=None,
env_vars={},
)
def test_succeeds_with_api_key_in_env(self, monkeypatch, tmp_path):
import langgraph_cli.deploy as deploy_mod
monkeypatch.setattr(deploy_mod, "_no_input", True)
monkeypatch.setenv("LANGSMITH_API_KEY", "lsv2_test")
client = _create_host_backend_client(
host_url="https://api.example.com",
api_key=None,
env_vars={},
)
assert client is not None
class TestSmithDashboardBaseUrl:
def test_none_returns_default(self):
assert _smith_dashboard_base_url(None) == "https://smith.langchain.com"
def test_empty_returns_default(self):
assert _smith_dashboard_base_url("") == "https://smith.langchain.com"
def test_prod_host_url(self):
assert (
_smith_dashboard_base_url("https://api.host.langchain.com")
== "https://smith.langchain.com"
)
def test_dev_host_url(self):
assert (
_smith_dashboard_base_url("https://dev.api.host.langchain.com")
== "https://dev.smith.langchain.com"
)
def test_eu_host_url(self):
assert (
_smith_dashboard_base_url("https://eu.api.host.langchain.com")
== "https://eu.smith.langchain.com"
)
def test_staging_host_url(self):
assert (
_smith_dashboard_base_url("https://staging.api.host.langchain.com")
== "https://staging.smith.langchain.com"
)
def test_localhost(self):
assert (
_smith_dashboard_base_url("http://localhost:8080")
== "http://localhost:8080"
)
def test_localhost_trailing_slash(self):
assert (
_smith_dashboard_base_url("http://localhost:8080/")
== "http://localhost:8080"
)
def test_127_0_0_1(self):
assert (
_smith_dashboard_base_url("http://127.0.0.1:3000")
== "http://127.0.0.1:3000"
)
def test_unknown_domain_returns_default(self):
assert (
_smith_dashboard_base_url("https://custom.example.com")
== "https://smith.langchain.com"
)
class TestResolvePushedImageDigest:
"""Tests for ``_resolve_pushed_image_digest`` — runner is mocked to
return the ``(stdout, stderr)`` tuple that ``subp_exec(collect=True)``
would produce.
"""
@staticmethod
def _runner(stdout: str | None) -> MagicMock:
# Close the unawaited subp_exec coroutine to silence gc warnings.
runner = MagicMock()
def _run(coro, *args, **kwargs):
if hasattr(coro, "close"):
coro.close()
return (stdout, "")
runner.run.side_effect = _run
return runner
def test_happy_path_returns_digest(self):
runner = self._runner('["us-central1-docker.pkg.dev/proj/repo@sha256:abc123"]')
out = _resolve_pushed_image_digest(
runner,
remote_image="us-central1-docker.pkg.dev/proj/repo:latest",
docker_config_dir=None,
verbose=False,
)
assert out == "us-central1-docker.pkg.dev/proj/repo@sha256:abc123"
def test_filters_to_matching_repo(self):
# Same image ID can hold digests for multiple repos — pick the one
# matching the just-pushed repo.
runner = self._runner(
json.dumps(
[
"other-registry.example.com/some/repo@sha256:000000",
"us-central1-docker.pkg.dev/proj/repo@sha256:abc123",
]
)
)
out = _resolve_pushed_image_digest(
runner,
remote_image="us-central1-docker.pkg.dev/proj/repo:v1.2.3",
docker_config_dir=None,
verbose=False,
)
assert out == "us-central1-docker.pkg.dev/proj/repo@sha256:abc123"
def test_empty_repodigests_falls_back_with_warning(self, mocker):
emitter = mocker.MagicMock()
mocker.patch("langgraph_cli.deploy._get_emitter", return_value=emitter)
runner = self._runner("[]")
remote = "us-central1-docker.pkg.dev/proj/repo:latest"
out = _resolve_pushed_image_digest(
runner,
remote_image=remote,
docker_config_dir=None,
verbose=False,
)
assert out == remote
assert emitter.warn.called
assert remote in emitter.warn.call_args.args[0]
def test_null_repodigests_falls_back_with_warning(self, mocker):
# ``docker inspect --format '{{json .RepoDigests}}'`` emits ``null``
# when the field is absent.
emitter = mocker.MagicMock()
mocker.patch("langgraph_cli.deploy._get_emitter", return_value=emitter)
runner = self._runner("null")
remote = "us-central1-docker.pkg.dev/proj/repo:latest"
out = _resolve_pushed_image_digest(
runner,
remote_image=remote,
docker_config_dir=None,
verbose=False,
)
assert out == remote
assert emitter.warn.called
def test_no_matching_repo_falls_back_with_warning(self, mocker):
# No matching digest for the pushed repo — warn and fall back to the
# tag-based ref rather than failing the deploy.
emitter = mocker.MagicMock()
mocker.patch("langgraph_cli.deploy._get_emitter", return_value=emitter)
runner = self._runner('["other-registry.example.com/some/repo@sha256:000000"]')
remote = "us-central1-docker.pkg.dev/proj/repo:latest"
out = _resolve_pushed_image_digest(
runner,
remote_image=remote,
docker_config_dir=None,
verbose=False,
)
assert out == remote
assert emitter.warn.called
def test_registry_with_port_in_host(self):
# Only the rightmost ``:`` (the ``:latest`` tag) should be stripped.
runner = self._runner('["localhost:5000/repo@sha256:deadbeef"]')
out = _resolve_pushed_image_digest(
runner,
remote_image="localhost:5000/repo:latest",
docker_config_dir=None,
verbose=False,
)
assert out == "localhost:5000/repo@sha256:deadbeef"
@staticmethod
def _capturing_runner(stdout: str) -> tuple[MagicMock, dict]:
"""Like ``_runner`` but exposes the coroutine for arg introspection.
Caller must close ``captured["coro"]``.
"""
runner = MagicMock()
captured: dict = {}
def _run(coro, *args, **kwargs):
captured["coro"] = coro
return (stdout, "")
runner.run.side_effect = _run
return runner, captured
def test_passes_docker_config_dir(self):
runner, captured = self._capturing_runner(
'["us-central1-docker.pkg.dev/proj/repo@sha256:abc"]'
)
_resolve_pushed_image_digest(
runner,
remote_image="us-central1-docker.pkg.dev/proj/repo:latest",
docker_config_dir="/tmp/some-cfg",
verbose=False,
)
frame_locals = captured["coro"].cr_frame.f_locals
assert frame_locals["cmd"] == "docker"
assert "--config" in frame_locals["args"]
cfg_idx = frame_locals["args"].index("--config")
assert frame_locals["args"][cfg_idx + 1] == "/tmp/some-cfg"
captured["coro"].close()
def test_omits_docker_config_dir_when_none(self):
runner, captured = self._capturing_runner(
'["us-central1-docker.pkg.dev/proj/repo@sha256:abc"]'
)
_resolve_pushed_image_digest(
runner,
remote_image="us-central1-docker.pkg.dev/proj/repo:latest",
docker_config_dir=None,
verbose=False,
)
frame_locals = captured["coro"].cr_frame.f_locals
assert "--config" not in frame_locals["args"]
captured["coro"].close()
+442
View File
@@ -0,0 +1,442 @@
import pytest
from langgraph_cli.docker import (
DEFAULT_POSTGRES_URI,
DockerCapabilities,
Version,
_parse_version,
compose,
)
from langgraph_cli.util import clean_empty_lines
DEFAULT_DOCKER_CAPABILITIES = DockerCapabilities(
version_docker=Version(26, 1, 1),
version_compose=Version(2, 27, 0),
healthcheck_start_interval=False,
)
def test_compose_with_no_debugger_and_custom_db():
port = 8123
custom_postgres_uri = "custom_postgres_uri"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES, port=port, postgres_uri=custom_postgres_uri
)
expected_compose_str = f"""services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {custom_postgres_uri}"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_with_no_debugger_and_custom_db_with_healthcheck():
port = 8123
custom_postgres_uri = "custom_postgres_uri"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES._replace(healthcheck_start_interval=True),
port=port,
postgres_uri=custom_postgres_uri,
)
expected_compose_str = f"""services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {custom_postgres_uri}
healthcheck:
test: python /api/healthcheck.py
interval: 60s
start_interval: 1s
start_period: 10s"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_with_debugger_and_custom_db():
port = 8123
custom_postgres_uri = "custom_postgres_uri"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES,
port=port,
postgres_uri=custom_postgres_uri,
)
expected_compose_str = f"""services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {custom_postgres_uri}"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_with_debugger_and_default_db():
port = 8123
actual_compose_str = compose(DEFAULT_DOCKER_CAPABILITIES, port=port)
expected_compose_str = f"""volumes:
langgraph-data:
driver: local
services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-postgres:
image: pgvector/pgvector:pg16
ports:
- "5433:5432"
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
command:
- postgres
- -c
- shared_preload_libraries=vector
volumes:
- langgraph-data:/var/lib/postgresql/data
healthcheck:
test: pg_isready -U postgres
start_period: 10s
timeout: 1s
retries: 5
interval: 5s
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
langgraph-postgres:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {DEFAULT_POSTGRES_URI}"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_with_api_version():
"""Test compose function with api_version parameter."""
port = 8123
api_version = "0.2.74"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES, port=port, api_version=api_version
)
# The compose function should generate a compose file that doesn't directly
# reference the api_version, since it's handled in the docker tag creation
# when building the image. The compose function mainly sets up services.
expected_compose_str = f"""volumes:
langgraph-data:
driver: local
services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-postgres:
image: pgvector/pgvector:pg16
ports:
- "5433:5432"
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
command:
- postgres
- -c
- shared_preload_libraries=vector
volumes:
- langgraph-data:/var/lib/postgresql/data
healthcheck:
test: pg_isready -U postgres
start_period: 10s
timeout: 1s
retries: 5
interval: 5s
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
langgraph-postgres:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {DEFAULT_POSTGRES_URI}"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_with_api_version_and_base_image():
"""Test compose function with both api_version and base_image parameters."""
port = 8123
api_version = "1.0.0"
base_image = "my-registry/custom-api"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES,
port=port,
api_version=api_version,
base_image=base_image,
)
# Similar to the previous test - the compose function doesn't directly embed
# the api_version or base_image into the compose file since those are handled
# during the docker build process
expected_compose_str = f"""volumes:
langgraph-data:
driver: local
services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-postgres:
image: pgvector/pgvector:pg16
ports:
- "5433:5432"
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
command:
- postgres
- -c
- shared_preload_libraries=vector
volumes:
- langgraph-data:/var/lib/postgresql/data
healthcheck:
test: pg_isready -U postgres
start_period: 10s
timeout: 1s
retries: 5
interval: 5s
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
langgraph-postgres:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {DEFAULT_POSTGRES_URI}"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_with_api_version_and_custom_postgres():
"""Test compose function with api_version and custom postgres URI."""
port = 8123
api_version = "0.2.74"
custom_postgres_uri = "postgresql://user:pass@external-db:5432/mydb"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES,
port=port,
api_version=api_version,
postgres_uri=custom_postgres_uri,
)
expected_compose_str = f"""services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {custom_postgres_uri}"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_with_api_version_and_debugger():
"""Test compose function with api_version and debugger port."""
port = 8123
debugger_port = 8001
api_version = "0.2.74"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES,
port=port,
api_version=api_version,
debugger_port=debugger_port,
)
expected_compose_str = f"""volumes:
langgraph-data:
driver: local
services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-postgres:
image: pgvector/pgvector:pg16
ports:
- "5433:5432"
environment:
POSTGRES_DB: postgres
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
command:
- postgres
- -c
- shared_preload_libraries=vector
volumes:
- langgraph-data:/var/lib/postgresql/data
healthcheck:
test: pg_isready -U postgres
start_period: 10s
timeout: 1s
retries: 5
interval: 5s
langgraph-debugger:
image: langchain/langgraph-debugger
restart: on-failure
depends_on:
langgraph-postgres:
condition: service_healthy
ports:
- "{debugger_port}:3968"
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
langgraph-postgres:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {DEFAULT_POSTGRES_URI}"""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_distributed_mode_with_custom_db():
"""Test compose with engine_runtime_mode='distributed' adds N_JOBS_PER_WORKER=0."""
port = 8123
custom_postgres_uri = "custom_postgres_uri"
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES,
port=port,
postgres_uri=custom_postgres_uri,
engine_runtime_mode="distributed",
)
expected_compose_str = f"""services:
langgraph-redis:
image: redis:6
healthcheck:
test: redis-cli ping
interval: 5s
timeout: 1s
retries: 5
langgraph-api:
ports:
- "{port}:8000"
depends_on:
langgraph-redis:
condition: service_healthy
environment:
REDIS_URI: redis://langgraph-redis:6379
POSTGRES_URI: {custom_postgres_uri}
N_JOBS_PER_WORKER: "0\""""
assert clean_empty_lines(actual_compose_str) == expected_compose_str
def test_compose_distributed_mode_with_default_db():
"""Test compose distributed mode with default DB includes N_JOBS_PER_WORKER=0."""
port = 8123
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES,
port=port,
engine_runtime_mode="distributed",
)
assert 'N_JOBS_PER_WORKER: "0"' in actual_compose_str
assert "langgraph-postgres:" in actual_compose_str
assert "langgraph-redis:" in actual_compose_str
def test_compose_combined_mode_has_no_n_jobs():
"""Test compose with default combined_queue_worker mode does NOT set N_JOBS_PER_WORKER."""
port = 8123
actual_compose_str = compose(
DEFAULT_DOCKER_CAPABILITIES,
port=port,
engine_runtime_mode="combined_queue_worker",
)
assert "N_JOBS_PER_WORKER" not in actual_compose_str
@pytest.mark.parametrize(
"input_str,expected",
[
("1.2.3", Version(1, 2, 3)),
("v1.2.3", Version(1, 2, 3)),
("1.2.3-alpha", Version(1, 2, 3)),
("1.2.3+1", Version(1, 2, 3)),
("1.2.3-alpha+build", Version(1, 2, 3)),
("1.2", Version(1, 2, 0)),
("1", Version(1, 0, 0)),
("v28.1.1+1", Version(28, 1, 1)),
("2.0.0-beta.1+exp.sha.5114f85", Version(2, 0, 0)),
("v3.4.5-rc1+build.123", Version(3, 4, 5)),
],
)
def test_parse_version_w_edge_cases(input_str, expected):
assert _parse_version(input_str) == expected
@@ -0,0 +1,289 @@
import json
import httpx
import pytest
from langgraph_cli.host_backend import HostBackendClient, HostBackendError
@pytest.fixture
def mock_transport():
return httpx.MockTransport(lambda req: httpx.Response(200, json={"ok": True}))
@pytest.fixture
def client(mock_transport):
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=mock_transport,
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
return c
def test_constructor_strips_trailing_slash():
c = HostBackendClient("https://api.example.com/", "key")
assert str(c._client.base_url) == "https://api.example.com"
def test_constructor_empty_url_raises():
with pytest.raises(Exception, match="Host backend URL is required"):
HostBackendClient("", "key")
def test_request_sends_headers():
def handler(req: httpx.Request) -> httpx.Response:
assert req.headers["x-api-key"] == "test-key"
assert req.headers["accept"] == "application/json"
return httpx.Response(200, json={"ok": True})
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
result = c._request("GET", "/test")
assert result == {"ok": True}
def test_request_sends_json_payload():
def handler(req: httpx.Request) -> httpx.Response:
assert req.headers["content-type"] == "application/json"
assert req.content == b'{"key":"value"}'
return httpx.Response(200, json={"created": True})
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
result = c._request("POST", "/test", {"key": "value"})
assert result == {"created": True}
def test_request_empty_body_returns_none():
transport = httpx.MockTransport(lambda req: httpx.Response(200, content=b""))
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=transport,
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
assert c._request("DELETE", "/test") is None
def test_request_http_error_raises():
transport = httpx.MockTransport(lambda req: httpx.Response(404, text="not found"))
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=transport,
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
with pytest.raises(HostBackendError, match="404"):
c._request("GET", "/missing")
def test_request_invalid_json_raises():
transport = httpx.MockTransport(
lambda req: httpx.Response(200, content=b"not json")
)
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=transport,
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
with pytest.raises(HostBackendError, match="Failed to decode"):
c._request("GET", "/bad-json")
def test_request_transport_error_raises():
def handler(req: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("connection refused")
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
with pytest.raises(HostBackendError, match="connection refused"):
c._request("GET", "/test")
def test_create_deployment(client):
result = client.create_deployment(
name="my-deploy", deployment_type="dev", source="internal_docker"
)
assert result == {"ok": True}
def test_get_deployment(client):
result = client.get_deployment("dep-123")
assert result == {"ok": True}
def test_list_deployments(client):
result = client.list_deployments("my-app")
assert result == {"ok": True}
def test_list_deployments_sends_query_params():
def handler(req: httpx.Request) -> httpx.Response:
assert req.url.path == "/v2/deployments"
assert req.url.params["name_contains"] == "my app"
return httpx.Response(200, json={"ok": True})
c = HostBackendClient("https://api.example.com", "test-key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "test-key", "Accept": "application/json"},
timeout=30,
)
result = c.list_deployments("my app")
assert result == {"ok": True}
def test_delete_deployment(client):
result = client.delete_deployment("dep-123")
assert result == {"ok": True}
def test_request_push_token(client):
result = client.request_push_token("dep-123")
assert result == {"ok": True}
def test_update_deployment(client):
result = client.update_deployment(
"dep-123", "image:latest", secrets=[{"name": "KEY", "value": "val"}]
)
assert result == {"ok": True}
def test_update_deployment_no_secrets(client):
result = client.update_deployment("dep-123", "image:latest")
assert result == {"ok": True}
def _capturing_client(captured: dict) -> HostBackendClient:
def handler(req: httpx.Request) -> httpx.Response:
captured["body"] = req.read()
return httpx.Response(200, json={"ok": True})
c = HostBackendClient("https://api.example.com", "key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "key", "Accept": "application/json"},
timeout=30,
)
return c
def test_update_deployment_forwards_tracked_packages():
captured: dict = {}
c = _capturing_client(captured)
c.update_deployment(
"dep-123",
"image:latest",
tracked_packages=["google-adk:1.0.0"],
)
body = json.loads(captured["body"])
assert body["tracked_packages"] == ["google-adk:1.0.0"]
assert "tracked_packages" not in body["source_revision_config"]
def test_update_deployment_omits_tracked_packages_when_absent():
captured: dict = {}
c = _capturing_client(captured)
c.update_deployment("dep-123", "image:latest")
body = json.loads(captured["body"])
assert "tracked_packages" not in body
def test_update_deployment_internal_source_forwards_tracked_packages():
captured: dict = {}
c = _capturing_client(captured)
c.update_deployment_internal_source(
"dep-123",
source_tarball_path="path/to/tarball",
config_path="langgraph.json",
tracked_packages=["google-adk:>=0.5"],
)
body = json.loads(captured["body"])
assert body["tracked_packages"] == ["google-adk:>=0.5"]
assert body["source_revision_config"]["source_tarball_path"] == "path/to/tarball"
assert "tracked_packages" not in body["source_revision_config"]
def test_update_deployment_internal_source_omits_tracked_packages_when_absent():
captured: dict = {}
c = _capturing_client(captured)
c.update_deployment_internal_source(
"dep-123",
source_tarball_path="path/to/tarball",
config_path="langgraph.json",
)
body = json.loads(captured["body"])
assert "tracked_packages" not in body
def test_list_revisions(client):
result = client.list_revisions("dep-123", limit=5)
assert result == {"ok": True}
def test_get_revision(client):
result = client.get_revision("dep-123", "rev-456")
assert result == {"ok": True}
def test_get_build_logs(client):
result = client.get_build_logs("proj-1", "rev-1", {"limit": 10})
assert result == {"ok": True}
def test_get_deploy_logs_all_revisions():
def handler(req: httpx.Request) -> httpx.Response:
assert "/v1/projects/proj-1/deploy_logs" in str(req.url)
assert "/revisions/" not in str(req.url)
return httpx.Response(200, json={"logs": [{"message": "running"}]})
c = HostBackendClient("https://api.example.com", "key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "key", "Accept": "application/json"},
timeout=30,
)
result = c.get_deploy_logs("proj-1", {"limit": 10})
assert result == {"logs": [{"message": "running"}]}
def test_get_deploy_logs_specific_revision():
def handler(req: httpx.Request) -> httpx.Response:
assert "/v1/projects/proj-1/revisions/rev-2/deploy_logs" in str(req.url)
return httpx.Response(200, json={"logs": []})
c = HostBackendClient("https://api.example.com", "key")
c._client = httpx.Client(
base_url="https://api.example.com",
transport=httpx.MockTransport(handler),
headers={"X-Api-Key": "key", "Accept": "application/json"},
timeout=30,
)
result = c.get_deploy_logs("proj-1", {"limit": 10}, revision_id="rev-2")
assert result == {"logs": []}
@@ -0,0 +1,58 @@
from langgraph_cli.deploy import format_log_entry, format_timestamp, level_fg
class TestFormatTimestamp:
def test_epoch_ms(self):
assert format_timestamp(1773119644012) == "2026-03-10 05:14:04"
def test_string_passthrough(self):
assert format_timestamp("2026-03-08T00:00:00Z") == "2026-03-08T00:00:00Z"
def test_empty(self):
assert format_timestamp("") == ""
def test_none(self):
assert format_timestamp(None) == ""
class TestFormatLogEntry:
def test_full_entry_epoch(self):
entry = {"timestamp": 1773119644012, "level": "ERROR", "message": "boom"}
result = format_log_entry(entry)
assert result == "[2026-03-10 05:14:04] [ERROR] boom"
def test_full_entry_string(self):
entry = {
"timestamp": "2026-03-08T12:00:00Z",
"level": "ERROR",
"message": "boom",
}
assert format_log_entry(entry) == "[2026-03-08T12:00:00Z] [ERROR] boom"
def test_no_level(self):
entry = {"timestamp": "2026-03-08T12:00:00Z", "message": "hello"}
assert format_log_entry(entry) == "[2026-03-08T12:00:00Z] hello"
def test_no_timestamp(self):
entry = {"message": "bare message"}
assert format_log_entry(entry) == "bare message"
def test_empty_entry(self):
assert format_log_entry({}) == ""
class TestLevelFg:
def test_error(self):
assert level_fg("ERROR") == "red"
def test_error_lowercase(self):
assert level_fg("error") == "red"
def test_warning(self):
assert level_fg("WARNING") == "yellow"
def test_info_returns_none(self):
assert level_fg("INFO") is None
def test_empty_returns_none(self):
assert level_fg("") is None
+257
View File
@@ -0,0 +1,257 @@
from unittest.mock import patch
from langgraph_cli.deploy import (
_extract_deployment_url,
format_deployments_table,
format_revisions_table,
)
from langgraph_cli.util import clean_empty_lines, warn_non_wolfi_distro
def test_clean_empty_lines():
"""Test clean_empty_lines function."""
# Test with empty lines
input_str = "line1\n\nline2\n\nline3"
result = clean_empty_lines(input_str)
assert result == "line1\nline2\nline3"
# Test with no empty lines
input_str = "line1\nline2\nline3"
result = clean_empty_lines(input_str)
assert result == "line1\nline2\nline3"
# Test with only empty lines
input_str = "\n\n\n"
result = clean_empty_lines(input_str)
assert result == ""
# Test empty string
input_str = ""
result = clean_empty_lines(input_str)
assert result == ""
def test_warn_non_wolfi_distro_with_debian(capsys):
"""Test that warning is shown when image_distro is 'debian'."""
config = {"image_distro": "debian"}
warn_non_wolfi_distro(config)
captured = capsys.readouterr()
assert (
"⚠️ Security Recommendation: Consider switching to Wolfi Linux for enhanced security."
in captured.out
)
assert (
"Wolfi is a security-oriented, minimal Linux distribution designed for containers."
in captured.out
)
assert (
'To switch, add \'"image_distro": "wolfi"\' to your langgraph.json config file.'
in captured.out
)
def test_warn_non_wolfi_distro_with_default_debian(capsys):
"""Test that warning is shown when image_distro is missing (defaults to debian)."""
config = {} # No image_distro key, should default to debian
warn_non_wolfi_distro(config)
captured = capsys.readouterr()
assert (
"⚠️ Security Recommendation: Consider switching to Wolfi Linux for enhanced security."
in captured.out
)
assert (
"Wolfi is a security-oriented, minimal Linux distribution designed for containers."
in captured.out
)
assert (
'To switch, add \'"image_distro": "wolfi"\' to your langgraph.json config file.'
in captured.out
)
def test_warn_non_wolfi_distro_with_wolfi(capsys):
"""Test that no warning is shown when image_distro is 'wolfi'."""
config = {"image_distro": "wolfi"}
warn_non_wolfi_distro(config)
captured = capsys.readouterr()
assert captured.out == "" # No output should be generated
def test_warn_non_wolfi_distro_with_other_distro(capsys):
"""Test that warning is shown when image_distro is something other than 'wolfi'."""
config = {"image_distro": "ubuntu"}
warn_non_wolfi_distro(config)
captured = capsys.readouterr()
assert (
"⚠️ Security Recommendation: Consider switching to Wolfi Linux for enhanced security."
in captured.out
)
assert (
"Wolfi is a security-oriented, minimal Linux distribution designed for containers."
in captured.out
)
assert (
'To switch, add \'"image_distro": "wolfi"\' to your langgraph.json config file.'
in captured.out
)
def test_warn_non_wolfi_distro_output_formatting():
"""Test that the warning output is properly formatted with colors and empty line."""
config = {"image_distro": "debian"}
with patch("click.secho") as mock_secho:
warn_non_wolfi_distro(config)
# Verify click.secho was called with the correct parameters
expected_calls = [
(
(
"⚠️ Security Recommendation: Consider switching to Wolfi Linux for enhanced security.",
),
{"fg": "yellow", "bold": True},
),
(
(
" Wolfi is a security-oriented, minimal Linux distribution designed for containers.",
),
{"fg": "yellow"},
),
(
(
' To switch, add \'"image_distro": "wolfi"\' to your langgraph.json config file.',
),
{"fg": "yellow"},
),
(
("",), # Empty line
{},
),
]
assert mock_secho.call_count == 4
for i, (expected_args, expected_kwargs) in enumerate(expected_calls):
actual_call = mock_secho.call_args_list[i]
assert actual_call.args == expected_args
assert actual_call.kwargs == expected_kwargs
def test_warn_non_wolfi_distro_various_configs(capsys):
"""Test warn_non_wolfi_distro with various config scenarios."""
test_cases = [
# (config, should_warn, description)
({"image_distro": "debian"}, True, "explicit debian"),
({"image_distro": "wolfi"}, False, "explicit wolfi"),
({}, True, "missing image_distro (defaults to debian)"),
({"image_distro": "alpine"}, True, "other distro"),
({"image_distro": "ubuntu"}, True, "ubuntu distro"),
({"other_config": "value"}, True, "unrelated config keys"),
]
for config, should_warn, description in test_cases:
# Clear any previous output
capsys.readouterr()
warn_non_wolfi_distro(config)
captured = capsys.readouterr()
if should_warn:
assert "⚠️ Security Recommendation" in captured.out, (
f"Should warn for {description}"
)
assert "Wolfi" in captured.out, f"Should mention Wolfi for {description}"
else:
assert captured.out == "", f"Should not warn for {description}"
def test_warn_non_wolfi_distro_return_value():
"""Test that warn_non_wolfi_distro returns None."""
config = {"image_distro": "debian"}
result = warn_non_wolfi_distro(config)
assert result is None
config = {"image_distro": "wolfi"}
result = warn_non_wolfi_distro(config)
assert result is None
def test_warn_non_wolfi_distro_does_not_modify_config():
"""Test that warn_non_wolfi_distro does not modify the input config."""
original_config = {"image_distro": "debian", "other_key": "value"}
config_copy = original_config.copy()
warn_non_wolfi_distro(config_copy)
assert config_copy == original_config # Config should remain unchanged
def test_extract_deployment_url_uses_custom_url():
deployment = {"source_config": {"custom_url": "https://example.com/custom"}}
assert _extract_deployment_url(deployment) == "https://example.com/custom"
def test_extract_deployment_url_defaults_to_dash():
assert _extract_deployment_url({"id": "dep-123"}) == "-"
def test_format_deployments_table():
output = format_deployments_table(
[
{
"id": "dep-123",
"name": "alpha",
"source_config": {"custom_url": "https://alpha.example.com"},
},
{
"id": "dep-456",
"name": "beta",
"url": "https://beta.example.com",
},
]
)
assert "Deployment ID" in output
assert "Deployment Name" in output
assert "Deployment URL" in output
assert "dep-123" in output
assert "alpha" in output
assert "https://alpha.example.com" in output
assert "dep-456" in output
def test_format_revisions_table():
output = format_revisions_table(
[
{
"id": "rev-123",
"status": "DEPLOYED",
"created_at": "2023-11-09T10:00:00Z",
},
{
"id": "rev-456",
"status": "CREATING",
"created_at": "2023-11-07T05:31:56Z",
},
{
"id": "rev-789",
"status": "DEPLOYED",
"created_at": "2023-11-08T10:00:00Z",
},
]
)
assert "Revision ID" in output
assert "Status" in output
assert "Created At" in output
assert "rev-123" in output
assert "CREATING" in output
assert "2023-11-07T05:31:56Z" in output
assert "rev-456" in output
assert "rev-789" in output
assert "REPLACED" in output