refactor(api)!: remove the standalone API server (#6614)
This commit is contained in:
1 parent
5c72ced2fe
commit
220d5e6970
99 files changed
+240
-4133
No files matched your search
@@ -335,16 +335,13 @@ async def test_non_goal_direct_turn_cannot_reuse_prior_goal_command(tmp_path):
|
||||
])
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal)
|
||||
session = loop.sessions.get_or_create("api:default")
|
||||
session = loop.sessions.get_or_create("cli:direct")
|
||||
session.add_message("user", "/goal old completed request")
|
||||
session.add_message("assistant", "The old request is complete.")
|
||||
|
||||
result = await loop.process_direct(
|
||||
"Handle this as an ordinary one-time task.",
|
||||
session_key=session.key,
|
||||
channel="api",
|
||||
chat_id="default",
|
||||
persist_user_message=False,
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
|
||||
@@ -1807,32 +1807,6 @@ async def test_process_direct_rejects_reserved_system_channel(tmp_path: Path) ->
|
||||
loop._process_message.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_direct_skip_user_persist_does_not_save_retry_user(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("api:default")
|
||||
session.add_message("user", "hello")
|
||||
session.add_message("assistant", "previous empty-response attempt")
|
||||
loop.sessions.save(session)
|
||||
|
||||
await loop.process_direct(
|
||||
"hello",
|
||||
session_key=session.key,
|
||||
channel="api",
|
||||
chat_id="default",
|
||||
persist_user_message=False,
|
||||
)
|
||||
|
||||
session = loop.sessions.get_or_create("api:default")
|
||||
assert [(m["role"], m["content"]) for m in session.messages] == [
|
||||
("user", "hello"),
|
||||
("assistant", "previous empty-response attempt"),
|
||||
("assistant", "Test title"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_context_uses_effective_key_for_subagent_tool(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
|
||||
@@ -755,33 +755,6 @@ class TestChannelCommonRegistration:
|
||||
assert config.channels.feishu["appId"] == "test123"
|
||||
|
||||
|
||||
class TestApiServerRegistration:
|
||||
|
||||
def test_api_server_in_settings_sections(self):
|
||||
from nanobot.cli.onboard import _SETTINGS_SECTIONS
|
||||
|
||||
assert "API Server" in _SETTINGS_SECTIONS
|
||||
|
||||
def test_api_server_getter_returns_api(self):
|
||||
from nanobot.cli.onboard import _SETTINGS_GETTER
|
||||
|
||||
config = Config()
|
||||
result = _SETTINGS_GETTER["API Server"](config)
|
||||
assert result is config.api
|
||||
|
||||
def test_api_server_setter_writes_api(self):
|
||||
from nanobot.cli.onboard import _SETTINGS_SETTER
|
||||
|
||||
config = Config()
|
||||
from nanobot.config.schema import ApiConfig
|
||||
|
||||
new_api = ApiConfig(host="0.0.0.0", port=9999, api_key="secret")
|
||||
_SETTINGS_SETTER["API Server"](config, new_api)
|
||||
assert config.api.host == "0.0.0.0"
|
||||
assert config.api.port == 9999
|
||||
assert config.api.api_key == "secret"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def prompt_input():
|
||||
with create_pipe_input() as pipe:
|
||||
@@ -1708,35 +1681,6 @@ class TestMainMenuInteraction:
|
||||
assert result.should_save is True
|
||||
assert result.config.channels.send_tool_hints is True
|
||||
|
||||
def test_run_onboard_api_server_edit(self, monkeypatch):
|
||||
initial_config = Config()
|
||||
|
||||
responses = iter([
|
||||
"[A] Advanced Settings",
|
||||
"[I] API Server",
|
||||
KeyboardInterrupt(),
|
||||
"[S] Save and Exit",
|
||||
])
|
||||
|
||||
def fake_select_with_back(*_args, **_kwargs):
|
||||
response = next(responses)
|
||||
if isinstance(response, BaseException):
|
||||
raise response
|
||||
return response
|
||||
|
||||
def fake_configure_general_settings(config, section):
|
||||
if section == "API Server":
|
||||
config.api.port = 9999
|
||||
|
||||
monkeypatch.setattr(onboard_wizard, "_show_main_menu_header", lambda: None)
|
||||
monkeypatch.setattr(onboard_wizard, "_select_with_back", fake_select_with_back)
|
||||
monkeypatch.setattr(onboard_wizard, "_configure_general_settings", fake_configure_general_settings)
|
||||
|
||||
result = run_onboard(initial_config=initial_config)
|
||||
|
||||
assert result.should_save is True
|
||||
assert result.config.api.port == 9999
|
||||
|
||||
def test_view_summary_calls_pause(self, monkeypatch):
|
||||
initial_config = Config()
|
||||
pause_called = {"n": 0}
|
||||
|
||||
@@ -2614,7 +2614,7 @@ def test_optional_dependency_metadata_for_enable():
|
||||
assert "boto3>=1.43.0" not in data["project"]["dependencies"]
|
||||
assert deps["bedrock"] == ["boto3>=1.43.0", "botocore>=1.43.0,<2.0.0"]
|
||||
assert "aiohttp>=3.14.3,<4.0.0" in required
|
||||
assert deps["api"] == ["aiohttp>=3.9.0,<4.0.0"]
|
||||
assert deps["api"] == [] # Older updaters preserve this recorded extra.
|
||||
for dep_name in (
|
||||
"dingtalk-stream",
|
||||
"lark-oapi",
|
||||
@@ -2713,6 +2713,7 @@ def test_optional_dependency_metadata_for_enable():
|
||||
assert plugin.dependencies == expected
|
||||
|
||||
visible = optional_features.optional_dependency_groups()
|
||||
assert "api" not in visible
|
||||
assert "documents" not in visible
|
||||
assert "pdf" not in visible
|
||||
|
||||
@@ -2723,7 +2724,7 @@ def test_optional_dependency_groups_falls_back_to_package_metadata(monkeypatch):
|
||||
class _Metadata:
|
||||
def get_all(self, key: str):
|
||||
assert key == "Provides-Extra"
|
||||
return ["bedrock", "dev"]
|
||||
return ["api", "bedrock", "dev"]
|
||||
|
||||
monkeypatch.setattr(optional_features, "load_pyproject", lambda _path: {})
|
||||
monkeypatch.setattr("importlib.metadata.metadata", lambda _name: _Metadata())
|
||||
|
||||
@@ -3159,54 +3159,6 @@ def test_webui_foreground_reports_an_existing_gateway_without_leaking_secret(
|
||||
assert "do-not-leak" not in result.stdout
|
||||
|
||||
|
||||
def _patch_serve_runtime(monkeypatch, config: Config, seen: dict[str, object]) -> None:
|
||||
pytest.importorskip("aiohttp")
|
||||
|
||||
class _FakeApiApp:
|
||||
def __init__(self) -> None:
|
||||
self.on_startup: list[object] = []
|
||||
self.on_cleanup: list[object] = []
|
||||
|
||||
class _FakeAgentLoop:
|
||||
@classmethod
|
||||
def from_config(cls, config, bus=None, **extra):
|
||||
return cls(workspace=config.workspace_path, **extra)
|
||||
def __init__(self, **kwargs) -> None:
|
||||
seen["workspace"] = kwargs["workspace"]
|
||||
|
||||
async def aclose(self) -> None:
|
||||
return None
|
||||
|
||||
def _fake_create_app(
|
||||
agent_loop,
|
||||
model_name: str,
|
||||
request_timeout: float,
|
||||
api_key: str = "",
|
||||
prepare_agent=None,
|
||||
):
|
||||
seen["agent_loop"] = agent_loop
|
||||
seen["model_name"] = model_name
|
||||
seen["request_timeout"] = request_timeout
|
||||
seen["api_key"] = api_key
|
||||
seen["prepare_agent"] = prepare_agent
|
||||
return _FakeApiApp()
|
||||
|
||||
def _fake_run_app(api_app, host: str, port: int, print):
|
||||
seen["api_app"] = api_app
|
||||
seen["host"] = host
|
||||
seen["port"] = port
|
||||
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.commands.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.api.server.create_app", _fake_create_app)
|
||||
monkeypatch.setattr("aiohttp.web.run_app", _fake_run_app)
|
||||
|
||||
|
||||
def test_gateway_uses_workspace_from_config_by_default(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
@@ -4476,34 +4428,6 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
|
||||
assert shutdown_order == ["channels_stopped", "channel_task_cleaned_up"]
|
||||
|
||||
|
||||
def test_serve_uses_api_config_defaults_and_workspace_override(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
config.agents.defaults.workspace = str(tmp_path / "config-workspace")
|
||||
config.api.host = "127.0.0.2"
|
||||
config.api.port = 18900
|
||||
config.api.timeout = 45.0
|
||||
config.api.api_key = "secret"
|
||||
override_workspace = tmp_path / "override-workspace"
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
_patch_serve_runtime(monkeypatch, config, seen)
|
||||
|
||||
result = runner.invoke(
|
||||
app,
|
||||
["serve", "--config", str(config_file), "--workspace", str(override_workspace)],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0
|
||||
assert seen["workspace"] == override_workspace
|
||||
assert seen["host"] == "127.0.0.2"
|
||||
assert seen["port"] == 18900
|
||||
assert seen["request_timeout"] == 45.0
|
||||
assert seen["api_key"] == "secret"
|
||||
|
||||
|
||||
def test_trigger_cli_queues_message_in_workspace(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
@@ -4536,103 +4460,6 @@ def test_trigger_cli_queues_message_in_workspace(
|
||||
assert deliveries[0].content == "Review PR #4502"
|
||||
|
||||
|
||||
def test_serve_cli_options_override_api_config(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
config.api.host = "127.0.0.2"
|
||||
config.api.port = 18900
|
||||
config.api.timeout = 45.0
|
||||
config.api.api_key = "secret"
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
_patch_serve_runtime(monkeypatch, config, seen)
|
||||
|
||||
result = runner.invoke(
|
||||
app,
|
||||
[
|
||||
"serve",
|
||||
"--config",
|
||||
str(config_file),
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
"18901",
|
||||
"--timeout",
|
||||
"46",
|
||||
],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0
|
||||
assert seen["host"] == "127.0.0.1"
|
||||
assert seen["port"] == 18901
|
||||
assert seen["request_timeout"] == 46.0
|
||||
assert seen["api_key"] == "secret"
|
||||
|
||||
|
||||
def test_serve_allows_loopback_without_api_key(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
_patch_serve_runtime(monkeypatch, config, seen)
|
||||
|
||||
result = runner.invoke(app, ["serve", "--config", str(config_file)])
|
||||
|
||||
assert result.exit_code == 0
|
||||
assert seen["host"] == "127.0.0.1"
|
||||
assert seen["api_key"] == ""
|
||||
|
||||
|
||||
def test_serve_passes_configured_api_key(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
config.api.api_key = " secret "
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
_patch_serve_runtime(monkeypatch, config, seen)
|
||||
|
||||
result = runner.invoke(app, ["serve", "--config", str(config_file)])
|
||||
|
||||
assert result.exit_code == 0
|
||||
assert seen["api_key"] == "secret"
|
||||
|
||||
|
||||
def test_serve_rejects_wildcard_host_without_api_key(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
_patch_serve_runtime(monkeypatch, config, seen)
|
||||
|
||||
result = runner.invoke(app, ["serve", "--config", str(config_file), "--host", "0.0.0.0"])
|
||||
|
||||
assert result.exit_code == 1
|
||||
assert "api_key is not set" in result.stdout
|
||||
assert "workspace" not in seen
|
||||
assert "api_app" not in seen
|
||||
|
||||
|
||||
def test_serve_rejects_specific_network_interface_without_api_key(
|
||||
monkeypatch,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
_patch_serve_runtime(monkeypatch, config, seen)
|
||||
|
||||
result = runner.invoke(
|
||||
app,
|
||||
["serve", "--config", str(config_file), "--host", "192.168.1.10"],
|
||||
)
|
||||
|
||||
assert result.exit_code == 1
|
||||
assert "api_key" in result.stdout
|
||||
assert "prevent unauthenticated access" in result.stdout
|
||||
assert "api_app" not in seen
|
||||
|
||||
|
||||
def test_channels_login_requires_channel_name() -> None:
|
||||
result = runner.invoke(app, ["channels", "login"])
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -79,6 +80,24 @@ def test_home_rejects_file(tmp_path):
|
||||
assert result.exit_code == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy_args", [[], ["--help"], ["--host", "0.0.0.0", "-p", "8900", "-c", "old-config.json"]])
|
||||
def test_retired_serve_prints_migration_hint_without_initializing(tmp_path, legacy_args):
|
||||
instance = tmp_path / "old API instance"
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "nanobot", "--home", str(instance), "serve", *legacy_args],
|
||||
cwd=Path(__file__).parents[2],
|
||||
env=dict(os.environ, HOME=str(tmp_path), USERPROFILE=str(tmp_path)),
|
||||
capture_output=True, text=True, encoding="utf-8", check=False, timeout=20,
|
||||
)
|
||||
assert result.returncode == 2, result.stderr
|
||||
assert result.stdout == ""
|
||||
assert "'nanobot serve' has been removed" in result.stderr
|
||||
assert "'nanobot webui'" in result.stderr
|
||||
assert "/v1 endpoints have no drop-in replacement" in result.stderr
|
||||
assert "old-config.json" not in result.stderr
|
||||
assert not instance.exists()
|
||||
|
||||
|
||||
def test_home_bare_command_starts_agent_and_restores_selection(monkeypatch, tmp_path):
|
||||
from nanobot.cli import entry
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ def isolate_config_path(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
["agent", "--message", "hello"],
|
||||
["gateway", "--foreground"],
|
||||
["gateway", "--background"],
|
||||
["serve"],
|
||||
["webui", "--yes", "--no-open"],
|
||||
],
|
||||
)
|
||||
|
||||
@@ -3,8 +3,7 @@ import json
|
||||
import pytest
|
||||
|
||||
from nanobot.config.errors import ConfigLoadError
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars
|
||||
from nanobot.config.schema import ApiConfig
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars, save_config
|
||||
|
||||
|
||||
def test_load_config_missing_file_uses_defaults(tmp_path) -> None:
|
||||
@@ -173,14 +172,25 @@ def test_load_config_malformed_legacy_sections_use_structured_error(
|
||||
assert "tools" in str(error)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", ["0.0.0.0", "::"])
|
||||
def test_api_config_requires_key_for_wildcard_hosts(host: str) -> None:
|
||||
with pytest.raises(ValueError, match="api_key is not set"):
|
||||
ApiConfig(host=host)
|
||||
def test_loads_pre_removal_config_without_the_retired_service_secret(tmp_path, monkeypatch) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
monkeypatch.delenv("REMOVED_SERVE_TOKEN", raising=False)
|
||||
legacy = json.dumps({
|
||||
"api": {"host": "0.0.0.0", "port": 8900, "apiKey": "${REMOVED_SERVE_TOKEN}"},
|
||||
"gateway": {"port": 18791},
|
||||
"providers": {"custom": {"apiBase": "http://model:8000/v1"}},
|
||||
})
|
||||
config_path.write_text(legacy, encoding="utf-8")
|
||||
|
||||
stored = load_config(config_path)
|
||||
config = resolve_config_env_vars(stored, config_path=config_path)
|
||||
assert config.gateway.port == 18791
|
||||
assert config.providers.custom.api_base == "http://model:8000/v1"
|
||||
assert config_path.read_text(encoding="utf-8") == legacy
|
||||
|
||||
def test_api_config_allows_wildcard_host_with_key() -> None:
|
||||
config = ApiConfig(host="0.0.0.0", api_key="secret")
|
||||
|
||||
assert config.host == "0.0.0.0"
|
||||
assert config.api_key == "secret"
|
||||
stored.gateway.port = 18792
|
||||
save_config(stored, config_path)
|
||||
saved = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
assert "api" not in saved
|
||||
assert saved["gateway"]["port"] == 18792
|
||||
assert saved["providers"]["custom"]["apiBase"] == "http://model:8000/v1"
|
||||
@@ -40,7 +40,7 @@ class RuntimeImportBlocker(importlib.abc.MetaPathFinder):
|
||||
if fullname in config_modules:
|
||||
return None
|
||||
forbidden = (
|
||||
'nanobot.agent', 'nanobot.api', 'nanobot.apps', 'nanobot.channels',
|
||||
'nanobot.agent', 'nanobot.apps', 'nanobot.channels',
|
||||
'nanobot.cli', 'nanobot.session', 'nanobot.webui', 'nanobot.providers.base',
|
||||
)
|
||||
if any(fullname == name or fullname.startswith(name + '.') for name in forbidden):
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.api.runtime import ApiRuntime, ApiStartOptions, api_runtime_paths
|
||||
|
||||
|
||||
class FakeProcess:
|
||||
pid = 23456
|
||||
|
||||
|
||||
def test_api_runtime_uses_isolated_paths(tmp_path: Path) -> None:
|
||||
paths = api_runtime_paths(tmp_path / "config.json")
|
||||
|
||||
assert paths.state_path.parent == tmp_path / "run"
|
||||
assert paths.state_path.name.startswith("api.")
|
||||
assert paths.log_path.parent == tmp_path / "logs"
|
||||
|
||||
|
||||
def test_api_runtime_builds_detached_serve_command(tmp_path: Path, monkeypatch) -> None:
|
||||
calls: list[list[str]] = []
|
||||
|
||||
def fake_popen(command, **_kwargs):
|
||||
calls.append(command)
|
||||
return FakeProcess()
|
||||
|
||||
runtime = ApiRuntime(
|
||||
paths=api_runtime_paths(tmp_path / "config.json"),
|
||||
platform_name="Linux",
|
||||
python_executable="/python",
|
||||
popen=fake_popen,
|
||||
sleep=lambda _seconds: None,
|
||||
)
|
||||
monkeypatch.setattr(runtime, "_is_pid_running", lambda _pid: True)
|
||||
monkeypatch.setattr(runtime, "_process_identity", lambda _pid: 23456)
|
||||
|
||||
result = runtime.start_background(ApiStartOptions(
|
||||
host="0.0.0.0",
|
||||
port=9900,
|
||||
workspace="/tmp/workspace",
|
||||
config_path="/tmp/config.json",
|
||||
))
|
||||
|
||||
assert result.ok is True
|
||||
assert result.message == "api_started_background"
|
||||
assert calls == [[
|
||||
"/python",
|
||||
"-m",
|
||||
"nanobot",
|
||||
"serve",
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--port",
|
||||
"9900",
|
||||
"--workspace",
|
||||
"/tmp/workspace",
|
||||
"--config",
|
||||
"/tmp/config.json",
|
||||
]]
|
||||
@@ -1,440 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import subprocess
|
||||
import sys
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from nanobot.api.server import (
|
||||
_FileSizeExceeded,
|
||||
_parse_json_content,
|
||||
_save_base64_data_url,
|
||||
create_app,
|
||||
)
|
||||
|
||||
try:
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
HAS_AIOHTTP = True
|
||||
except ImportError:
|
||||
HAS_AIOHTTP = False
|
||||
|
||||
pytest_plugins = ("pytest_asyncio",)
|
||||
|
||||
API_KEY = "secret"
|
||||
AUTH_HEADERS = {"Authorization": f"Bearer {API_KEY}"}
|
||||
|
||||
|
||||
def _make_mock_agent(response_text: str = "mock response") -> MagicMock:
|
||||
agent = MagicMock()
|
||||
agent.process_direct = AsyncMock(return_value=response_text)
|
||||
agent.aclose = AsyncMock()
|
||||
return agent
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_agent():
|
||||
return _make_mock_agent()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def aiohttp_client():
|
||||
clients: list[TestClient] = []
|
||||
|
||||
async def _make_client(app):
|
||||
client = TestClient(TestServer(app))
|
||||
await client.start_server()
|
||||
clients.append(client)
|
||||
return client
|
||||
|
||||
try:
|
||||
yield _make_client
|
||||
finally:
|
||||
for client in clients:
|
||||
await client.close()
|
||||
|
||||
|
||||
def test_save_base64_data_url_saves_png(tmp_path) -> None:
|
||||
b64_data = base64.b64encode(b"fake png data").decode()
|
||||
data_url = f"data:image/png;base64,{b64_data}"
|
||||
result = _save_base64_data_url(data_url, tmp_path)
|
||||
assert result is not None
|
||||
assert result.endswith(".png")
|
||||
assert (tmp_path / result.replace(str(tmp_path) + "/", "")).read_bytes() == b"fake png data"
|
||||
|
||||
|
||||
def test_save_base64_data_url_handles_invalid_b64(tmp_path) -> None:
|
||||
result = _save_base64_data_url("data:image/png;base64,not-valid-base64!!!", tmp_path)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_save_base64_data_url_handles_unknown_mime(tmp_path) -> None:
|
||||
b64_data = base64.b64encode(b"some data").decode()
|
||||
data_url = f"data:unknown/type;base64,{b64_data}"
|
||||
result = _save_base64_data_url(data_url, tmp_path)
|
||||
assert result is not None
|
||||
assert result.endswith(".bin")
|
||||
|
||||
|
||||
def test_save_base64_data_url_rejects_oversized_payload(tmp_path) -> None:
|
||||
large_payload = base64.b64encode(b"x" * (11 * 1024 * 1024)).decode()
|
||||
data_url = f"data:image/png;base64,{large_payload}"
|
||||
|
||||
with pytest.raises(_FileSizeExceeded, match="10MB limit"):
|
||||
_save_base64_data_url(data_url, tmp_path)
|
||||
|
||||
|
||||
def test_parse_json_content_extracts_text_and_media(tmp_path) -> None:
|
||||
b64_data = base64.b64encode(b"img").decode()
|
||||
body = {
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "describe this"},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64_data}"}},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
import os
|
||||
original_cwd = os.getcwd()
|
||||
os.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
text, media_paths = _parse_json_content(body)
|
||||
assert text == "describe this"
|
||||
assert len(media_paths) == 1
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
|
||||
|
||||
def test_parse_json_content_rejects_malformed_parameter_header_without_stalling(tmp_path) -> None:
|
||||
# Isolate the parser so a backtracking regression cannot hang the test runner.
|
||||
code = """
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from nanobot.api.server import _parse_json_content
|
||||
|
||||
media_dir = Path(sys.argv[1])
|
||||
url = "data:image/png" + ";a" * 128 + ",eA=="
|
||||
body = {"messages": [{"role": "user", "content": [
|
||||
{"type": "text", "text": "describe this"},
|
||||
{"type": "image_url", "image_url": {"url": url}},
|
||||
]}]}
|
||||
with patch("nanobot.api.server.get_media_dir", return_value=media_dir):
|
||||
assert _parse_json_content(body) == ("describe this", [])
|
||||
assert list(media_dir.iterdir()) == []
|
||||
"""
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", code, str(tmp_path)],
|
||||
cwd=Path(__file__).resolve().parents[1],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_parse_json_content_plain_text_only() -> None:
|
||||
body = {"messages": [{"role": "user", "content": "hello"}]}
|
||||
text, media_paths = _parse_json_content(body)
|
||||
assert text == "hello"
|
||||
assert media_paths == []
|
||||
|
||||
|
||||
def test_parse_json_content_validates_single_message() -> None:
|
||||
body = {
|
||||
"messages": [
|
||||
{"role": "user", "content": "first"},
|
||||
{"role": "user", "content": "second"},
|
||||
]
|
||||
}
|
||||
with pytest.raises(ValueError, match="single user message"):
|
||||
_parse_json_content(body)
|
||||
|
||||
|
||||
def test_parse_json_content_validates_user_role() -> None:
|
||||
body = {"messages": [{"role": "system", "content": "you are a bot"}]}
|
||||
with pytest.raises(ValueError, match="single user message"):
|
||||
_parse_json_content(body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("part", "field"),
|
||||
[
|
||||
({"type": "text", "text": 1}, r"content\[\]\.text"),
|
||||
(
|
||||
{"type": "image_url", "image_url": "not-an-object"},
|
||||
r"content\[\]\.image_url",
|
||||
),
|
||||
(
|
||||
{"type": "image_url", "image_url": {"url": 1}},
|
||||
r"image_url\.url",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_parse_json_content_validates_typed_block_fields(part, field) -> None:
|
||||
body = {"messages": [{"role": "user", "content": [part]}]}
|
||||
|
||||
with pytest.raises(TypeError, match=field):
|
||||
_parse_json_content(body)
|
||||
|
||||
|
||||
def test_parse_json_content_rejects_oversized_base64_file(tmp_path) -> None:
|
||||
large_payload = base64.b64encode(b"x" * (11 * 1024 * 1024)).decode()
|
||||
body = {
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "describe"},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{large_payload}"}},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
import os
|
||||
original_cwd = os.getcwd()
|
||||
os.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
with pytest.raises(_FileSizeExceeded, match="10MB limit"):
|
||||
_parse_json_content(body)
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_multipart_upload_saves_file(aiohttp_client, mock_agent, tmp_path) -> None:
|
||||
import os
|
||||
original_cwd = os.getcwd()
|
||||
os.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
file_data = b"test file content"
|
||||
data = BytesIO(file_data)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
data={"message": "analyze this", "files": data},
|
||||
)
|
||||
assert resp.status == 200
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "analyze this"
|
||||
assert len(call_kwargs.get("media") or []) == 1
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_multipart_multiple_files(aiohttp_client, mock_agent, tmp_path, monkeypatch) -> None:
|
||||
import aiohttp
|
||||
|
||||
media_dir = tmp_path / "media"
|
||||
media_dir.mkdir()
|
||||
monkeypatch.setattr("nanobot.api.server.get_media_dir", lambda _channel=None: media_dir)
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
files = [("first.txt", b"first file content"), ("second.bin", b"\x00second file\xff")]
|
||||
data = aiohttp.FormData()
|
||||
data.add_field("message", "analyze both files")
|
||||
for filename, payload in files:
|
||||
data.add_field("files", payload, filename=filename, content_type="application/octet-stream")
|
||||
|
||||
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, data=data)
|
||||
|
||||
assert resp.status == 200
|
||||
mock_agent.process_direct.assert_called_once()
|
||||
mock_agent.process_direct.assert_awaited_once()
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "analyze both files"
|
||||
saved_paths = [Path(path) for path in call_kwargs["media"]]
|
||||
assert len(saved_paths) == 2
|
||||
assert saved_paths[0] != saved_paths[1]
|
||||
for path, (_, payload) in zip(saved_paths, files, strict=True):
|
||||
assert path.parent == media_dir
|
||||
assert path.read_bytes() == payload
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_multipart_file_size_limit(aiohttp_client, mock_agent, tmp_path) -> None:
|
||||
import os
|
||||
original_cwd = os.getcwd()
|
||||
os.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
large_data = b"x" * (11 * 1024 * 1024)
|
||||
data = BytesIO(large_data)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
data={"message": "analyze", "files": data},
|
||||
)
|
||||
assert resp.status == 413
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_multipart_defaults_text_when_missing(aiohttp_client, mock_agent, tmp_path) -> None:
|
||||
import os
|
||||
original_cwd = os.getcwd()
|
||||
os.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
file_data = b"content"
|
||||
data = BytesIO(file_data)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
data={"files": data},
|
||||
)
|
||||
assert resp.status == 200
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "请分析上传的文件"
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("session_id", "chat_id"), [
|
||||
("my-session", "my-session"), (" my-session ", "my-session"), (" ", "default"),
|
||||
])
|
||||
async def test_multipart_with_session_id(
|
||||
aiohttp_client, mock_agent, tmp_path, session_id, chat_id,
|
||||
) -> None:
|
||||
import os
|
||||
original_cwd = os.getcwd()
|
||||
os.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
file_data = b"content"
|
||||
data = BytesIO(file_data)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
data={"message": "hello", "session_id": session_id, "files": data},
|
||||
)
|
||||
assert resp.status == 200
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["session_key"] == f"api:{chat_id}"
|
||||
assert call_kwargs["chat_id"] == chat_id
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_plain_text_backward_compat(aiohttp_client, mock_agent) -> None:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hello world"}]},
|
||||
)
|
||||
assert resp.status == 200
|
||||
body = await resp.json()
|
||||
assert body["choices"][0]["message"]["content"] == "mock response"
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "hello world"
|
||||
assert call_kwargs.get("media") is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("marker", ["base64", "BASE64", "Base64"])
|
||||
async def test_json_base64_image_upload(
|
||||
aiohttp_client, mock_agent, tmp_path, monkeypatch, marker: str,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.api.server.get_media_dir", lambda _channel=None: tmp_path)
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
tiny_png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "what is this"},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;{marker},{tiny_png_b64}"}},
|
||||
],
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
assert resp.status == 200
|
||||
mock_agent.process_direct.assert_awaited_once()
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "what is this"
|
||||
saved, = call_kwargs["media"]
|
||||
assert Path(saved).parent == tmp_path
|
||||
assert Path(saved).read_bytes() == base64.b64decode(tiny_png_b64)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_docx_upload_passes_media_path(aiohttp_client, tmp_path) -> None:
|
||||
agent = _make_mock_agent("report summary")
|
||||
import os
|
||||
original_cwd = os.getcwd()
|
||||
os.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
from docx import Document
|
||||
doc = Document()
|
||||
doc.add_paragraph("Total revenue: $5,000,000")
|
||||
buf = BytesIO()
|
||||
doc.save(buf)
|
||||
|
||||
import aiohttp
|
||||
data = aiohttp.FormData()
|
||||
data.add_field("message", "summarize the report")
|
||||
data.add_field("files", buf.getvalue(), filename="report.docx",
|
||||
content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|
||||
|
||||
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, data=data)
|
||||
assert resp.status == 200
|
||||
call_kwargs = agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "summarize the report"
|
||||
media = call_kwargs.get("media", [])
|
||||
assert len(media) == 1
|
||||
assert "report.docx" in media[0]
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
@@ -1,360 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from nanobot.api.server import (
|
||||
_SSE_DONE,
|
||||
_sse_chunk,
|
||||
create_app,
|
||||
)
|
||||
|
||||
try:
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
HAS_AIOHTTP = True
|
||||
except ImportError:
|
||||
HAS_AIOHTTP = False
|
||||
|
||||
pytest_plugins = ("pytest_asyncio",)
|
||||
|
||||
API_KEY = "secret"
|
||||
AUTH_HEADERS = {"Authorization": f"Bearer {API_KEY}"}
|
||||
|
||||
|
||||
def test_sse_chunk_with_delta() -> None:
|
||||
raw = _sse_chunk("hello", "test-model", "chatcmpl-abc123")
|
||||
line = raw.decode()
|
||||
assert line.startswith("data: ")
|
||||
payload = json.loads(line[len("data: "):])
|
||||
assert payload["id"] == "chatcmpl-abc123"
|
||||
assert payload["object"] == "chat.completion.chunk"
|
||||
assert payload["model"] == "test-model"
|
||||
assert payload["choices"][0]["delta"]["content"] == "hello"
|
||||
assert payload["choices"][0]["finish_reason"] is None
|
||||
|
||||
|
||||
def test_sse_chunk_finish_reason() -> None:
|
||||
raw = _sse_chunk("", "m", "id1", finish_reason="stop")
|
||||
payload = json.loads(raw.decode().split("data: ", 1)[1])
|
||||
assert payload["choices"][0]["delta"] == {}
|
||||
assert payload["choices"][0]["finish_reason"] == "stop"
|
||||
|
||||
|
||||
def test_sse_done_format() -> None:
|
||||
assert _SSE_DONE == b"data: [DONE]\n\n"
|
||||
|
||||
|
||||
def _make_streaming_agent(tokens: list[str]) -> MagicMock:
|
||||
"""Create a mock agent that streams tokens via on_stream callback."""
|
||||
agent = MagicMock()
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
async def fake_process_direct(*, content="", media=None, session_key="",
|
||||
channel="", chat_id="", on_stream=None,
|
||||
on_stream_end=None, **kwargs):
|
||||
if on_stream:
|
||||
for token in tokens:
|
||||
await on_stream(token)
|
||||
if on_stream_end:
|
||||
await on_stream_end()
|
||||
return " ".join(tokens)
|
||||
|
||||
agent.process_direct = fake_process_direct
|
||||
return agent
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def aiohttp_client():
|
||||
clients: list[TestClient] = []
|
||||
|
||||
async def _make_client(app):
|
||||
client = TestClient(TestServer(app))
|
||||
await client.start_server()
|
||||
clients.append(client)
|
||||
return client
|
||||
|
||||
try:
|
||||
yield _make_client
|
||||
finally:
|
||||
for client in clients:
|
||||
await client.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_true_returns_sse(aiohttp_client) -> None:
|
||||
agent = _make_streaming_agent(["Hello", " world"])
|
||||
app = create_app(agent, model_name="test-model", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hi"}], "stream": True},
|
||||
)
|
||||
assert resp.status == 200
|
||||
assert resp.content_type == "text/event-stream"
|
||||
assert resp.headers["X-Request-ID"]
|
||||
|
||||
body = await resp.text()
|
||||
lines = [line for line in body.split("\n") if line.startswith("data: ")]
|
||||
|
||||
data_lines = [line[len("data: "):] for line in lines]
|
||||
assert data_lines[-1] == "[DONE]"
|
||||
|
||||
chunks = [json.loads(line) for line in data_lines[:-1]]
|
||||
assert chunks[0]["choices"][0]["delta"]["content"] == "Hello"
|
||||
assert chunks[1]["choices"][0]["delta"]["content"] == " world"
|
||||
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
|
||||
assert chunks[-1]["choices"][0]["delta"] == {}
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_false_returns_json(aiohttp_client) -> None:
|
||||
agent = MagicMock()
|
||||
agent.process_direct = AsyncMock(return_value="normal reply")
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hi"}], "stream": False},
|
||||
)
|
||||
assert resp.status == 200
|
||||
body = await resp.json()
|
||||
assert body["object"] == "chat.completion"
|
||||
assert body["choices"][0]["message"]["content"] == "normal reply"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_default_is_false(aiohttp_client) -> None:
|
||||
agent = MagicMock()
|
||||
agent.process_direct = AsyncMock(return_value="default reply")
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hi"}]},
|
||||
)
|
||||
assert resp.status == 200
|
||||
body = await resp.json()
|
||||
assert body["object"] == "chat.completion"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("stream", ["false", "true", 0, 1, [], {}])
|
||||
async def test_stream_rejects_non_boolean_values(aiohttp_client, stream) -> None:
|
||||
agent = MagicMock()
|
||||
agent.process_direct = AsyncMock(return_value="normal reply")
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hi"}], "stream": stream},
|
||||
)
|
||||
|
||||
assert resp.status == 400
|
||||
body = await resp.json()
|
||||
assert body["error"]["message"] == "stream must be a boolean"
|
||||
agent.process_direct.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_null_preserves_non_streaming_compatibility(aiohttp_client) -> None:
|
||||
agent = MagicMock()
|
||||
agent.process_direct = AsyncMock(return_value="normal reply")
|
||||
agent.aclose = AsyncMock()
|
||||
client = await aiohttp_client(create_app(agent, model_name="m", api_key=API_KEY))
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hi"}], "stream": None},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
assert resp.content_type == "application/json"
|
||||
assert (await resp.json())["choices"][0]["message"]["content"] == "normal reply"
|
||||
agent.process_direct.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_sse_chunk_ids_are_consistent(aiohttp_client) -> None:
|
||||
agent = _make_streaming_agent(["A", "B", "C"])
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "go"}], "stream": True},
|
||||
)
|
||||
body = await resp.text()
|
||||
data_lines = [
|
||||
line[len("data: "):]
|
||||
for line in body.split("\n")
|
||||
if line.startswith("data: ") and line != "data: [DONE]"
|
||||
]
|
||||
chunks = [json.loads(line) for line in data_lines]
|
||||
|
||||
chunk_ids = {c["id"] for c in chunks}
|
||||
assert len(chunk_ids) == 1, f"Expected single chunk id, got {chunk_ids}"
|
||||
assert chunk_ids.pop().startswith("chatcmpl-")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_segment_end_does_not_close_sse(aiohttp_client) -> None:
|
||||
agent = MagicMock()
|
||||
|
||||
async def fake_process_direct(*, on_stream=None, on_stream_end=None, **kwargs):
|
||||
assert on_stream is not None
|
||||
assert on_stream_end is not None
|
||||
await on_stream("planning")
|
||||
await on_stream_end(resuming=True)
|
||||
await asyncio.sleep(0)
|
||||
await on_stream(" final")
|
||||
await on_stream_end(resuming=False)
|
||||
return "planning final"
|
||||
|
||||
agent.process_direct = fake_process_direct
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "use a tool"}], "stream": True},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
body = await resp.text()
|
||||
data_lines = [
|
||||
line[len("data: "):] for line in body.split("\n") if line.startswith("data: ")
|
||||
]
|
||||
assert data_lines[-1] == "[DONE]"
|
||||
|
||||
chunks = [json.loads(line) for line in data_lines[:-1]]
|
||||
deltas = [c["choices"][0]["delta"].get("content", "") for c in chunks]
|
||||
assert "planning" in deltas
|
||||
assert " final" in deltas
|
||||
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_uses_final_response_when_no_deltas(aiohttp_client) -> None:
|
||||
agent = MagicMock()
|
||||
|
||||
async def fake_process_direct(*, on_stream=None, on_stream_end=None, **kwargs):
|
||||
assert on_stream is not None
|
||||
assert on_stream_end is not None
|
||||
await on_stream_end(resuming=False)
|
||||
return "plain final"
|
||||
|
||||
agent.process_direct = fake_process_direct
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hi"}], "stream": True},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
body = await resp.text()
|
||||
data_lines = [
|
||||
line[len("data: "):] for line in body.split("\n") if line.startswith("data: ")
|
||||
]
|
||||
chunks = [json.loads(line) for line in data_lines[:-1]]
|
||||
deltas = [c["choices"][0]["delta"].get("content", "") for c in chunks]
|
||||
|
||||
assert "plain final" in deltas
|
||||
assert data_lines[-1] == "[DONE]"
|
||||
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_with_session_id(aiohttp_client) -> None:
|
||||
captured_key: str = ""
|
||||
|
||||
async def fake_process_direct(*, session_key="", on_stream=None, on_stream_end=None, **kwargs):
|
||||
nonlocal captured_key
|
||||
captured_key = session_key
|
||||
if on_stream:
|
||||
await on_stream("ok")
|
||||
if on_stream_end:
|
||||
await on_stream_end()
|
||||
return "ok"
|
||||
|
||||
agent = MagicMock()
|
||||
agent.process_direct = fake_process_direct
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
"stream": True,
|
||||
"session_id": "my-session",
|
||||
},
|
||||
)
|
||||
assert resp.status == 200
|
||||
assert captured_key == "api:my-session"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_backend_failure_does_not_emit_success_terminator(aiohttp_client) -> None:
|
||||
agent = MagicMock()
|
||||
|
||||
async def boom(**kwargs):
|
||||
raise RuntimeError("backend blew up")
|
||||
|
||||
agent.process_direct = boom
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hi"}], "stream": True},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
body = await resp.text()
|
||||
assert '"finish_reason": "stop"' not in body
|
||||
assert "[DONE]" not in body
|
||||
@@ -12,8 +12,8 @@ from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars
|
||||
|
||||
|
||||
def _initialize(path: Path, web_token: str = "", api_key: str = "") -> subprocess.CompletedProcess[str]:
|
||||
env = dict(os.environ, NANOBOT_WEB_TOKEN=web_token, NANOBOT_API_KEY=api_key)
|
||||
def _initialize(path: Path, web_token: str = "") -> subprocess.CompletedProcess[str]:
|
||||
env = dict(os.environ, NANOBOT_WEB_TOKEN=web_token)
|
||||
return subprocess.run(
|
||||
[sys.executable, "-m", "nanobot.cli.docker_bootstrap", str(path)],
|
||||
env=env, capture_output=True, text=True,
|
||||
@@ -33,36 +33,34 @@ def test_first_boot_generates_valid_container_config(tmp_path):
|
||||
assert result.returncode == 0, result.stderr
|
||||
config = resolve_config_env_vars(load_config(path))
|
||||
ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"])
|
||||
assert config.gateway.host == ws.host == config.api.host == "0.0.0.0"
|
||||
assert config.gateway.host == ws.host == "0.0.0.0"
|
||||
assert ws.enabled and ws.websocket_requires_token
|
||||
assert len(ws.token_issue_secret) == len(config.api.api_key) == 32
|
||||
assert ws.token_issue_secret != config.api.api_key
|
||||
assert len(ws.token_issue_secret) == 32
|
||||
assert ws.token_issue_secret in result.stdout
|
||||
assert config.api.api_key in result.stdout
|
||||
|
||||
|
||||
@pytest.mark.parametrize("secret", ['review&secret', 'review|secret', 'review"secret', r'review\secret'])
|
||||
def test_custom_secrets_survive_json_serialization(tmp_path, secret):
|
||||
path = tmp_path / "config.json"
|
||||
result = _initialize(path, secret, secret)
|
||||
result = _initialize(path, secret)
|
||||
assert result.returncode == 0, result.stderr
|
||||
config = resolve_config_env_vars(load_config(path))
|
||||
ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"])
|
||||
assert ws.token_issue_secret == config.api.api_key == secret
|
||||
assert ws.token_issue_secret == secret
|
||||
|
||||
|
||||
def test_restart_preserves_user_settings_and_credentials(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
assert _initialize(path, "original-web", "original-api").returncode == 0
|
||||
assert _initialize(path, "original-web").returncode == 0
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data["api"] = {"host": "0.0.0.0", "apiKey": "${RETIRED_SERVE_TOKEN}"}
|
||||
data["providers"]["custom"] = {"apiKey": "provider-key", "apiBase": "http://model:8000/v1"}
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
previous = path.read_bytes()
|
||||
result = _initialize(path, "replacement-web", "replacement-api")
|
||||
result = _initialize(path, "replacement-web")
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert path.read_bytes() == previous
|
||||
assert "replacement-web" not in result.stdout
|
||||
assert "replacement-api" not in result.stdout
|
||||
|
||||
|
||||
def test_failed_write_does_not_leave_an_existing_config(tmp_path):
|
||||
|
||||
@@ -1,650 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.hook import AgentHook, AgentRunHookContext
|
||||
from nanobot.api.server import (
|
||||
API_CHAT_ID,
|
||||
API_SESSION_KEY,
|
||||
_chat_completion_response,
|
||||
_error_json,
|
||||
create_app,
|
||||
handle_chat_completions,
|
||||
)
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
|
||||
|
||||
try:
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
HAS_AIOHTTP = True
|
||||
except ImportError:
|
||||
HAS_AIOHTTP = False
|
||||
|
||||
pytest_plugins = ("pytest_asyncio",)
|
||||
|
||||
API_KEY = "secret"
|
||||
AUTH_HEADERS = {"Authorization": f"Bearer {API_KEY}"}
|
||||
|
||||
|
||||
def _make_mock_agent(response_text: str = "mock response") -> MagicMock:
|
||||
agent = MagicMock()
|
||||
agent.process_direct = AsyncMock(return_value=response_text)
|
||||
agent.aclose = AsyncMock()
|
||||
return agent
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_agent():
|
||||
return _make_mock_agent()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(mock_agent):
|
||||
return create_app(mock_agent, model_name="test-model", request_timeout=10.0, api_key=API_KEY)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def aiohttp_client():
|
||||
clients: list[TestClient] = []
|
||||
|
||||
async def _make_client(app):
|
||||
client = TestClient(TestServer(app))
|
||||
await client.start_server()
|
||||
clients.append(client)
|
||||
return client
|
||||
|
||||
try:
|
||||
yield _make_client
|
||||
finally:
|
||||
for client in clients:
|
||||
await client.close()
|
||||
|
||||
|
||||
def test_error_json() -> None:
|
||||
resp = _error_json(400, "bad request")
|
||||
assert resp.status == 400
|
||||
body = json.loads(resp.body)
|
||||
assert body["error"]["message"] == "bad request"
|
||||
assert body["error"]["code"] == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_unconfigured_model_returns_503_before_execution(aiohttp_client, mock_agent, stream):
|
||||
mock_agent.provider = UnconfiguredProvider("not-configured")
|
||||
prepare = AsyncMock()
|
||||
app = create_app(mock_agent, api_key=API_KEY, prepare_agent=prepare)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
assert (await client.get("/health")).status == 200
|
||||
denied = await client.post("/v1/chat/completions", json={"messages": []})
|
||||
assert denied.status == 401
|
||||
response = await client.post(
|
||||
"/v1/chat/completions", headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hello"}], "stream": stream},
|
||||
)
|
||||
assert response.status == 503
|
||||
error = (await response.json())["error"]
|
||||
assert error["type"] == "configuration_error"
|
||||
assert "Model is not configured" in error["message"]
|
||||
mock_agent.process_direct.assert_not_called()
|
||||
prepare.assert_not_called()
|
||||
|
||||
|
||||
def test_chat_completion_response() -> None:
|
||||
result = _chat_completion_response("hello world", "test-model")
|
||||
assert result["object"] == "chat.completion"
|
||||
assert result["model"] == "test-model"
|
||||
assert result["choices"][0]["message"]["content"] == "hello world"
|
||||
assert result["choices"][0]["finish_reason"] == "stop"
|
||||
assert result["id"].startswith("chatcmpl-")
|
||||
assert result["usage"]["prompt_tokens"] == 0
|
||||
assert result["usage"]["completion_tokens"] == 0
|
||||
assert result["usage"]["total_tokens"] == 0
|
||||
|
||||
|
||||
def test_chat_completion_response_with_usage() -> None:
|
||||
usage = LLMUsage.reported(input_tokens=150, output_tokens=42)
|
||||
result = _chat_completion_response("hello world", "test-model", usage)
|
||||
assert result["usage"]["prompt_tokens"] == 150
|
||||
assert result["usage"]["completion_tokens"] == 42
|
||||
assert result["usage"]["total_tokens"] == 192
|
||||
|
||||
|
||||
def test_chat_completion_response_preserves_explicit_total_usage() -> None:
|
||||
usage = LLMUsage.reported(input_tokens=70, output_tokens=7, total_tokens=175)
|
||||
result = _chat_completion_response("hello world", "test-model", usage)
|
||||
assert result["usage"]["prompt_tokens"] == 70
|
||||
assert result["usage"]["completion_tokens"] == 7
|
||||
assert result["usage"]["total_tokens"] == 175
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_messages_returns_400(aiohttp_client, app) -> None:
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, json={"model": "test"})
|
||||
assert resp.status == 400
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_key_protects_api_routes_but_not_health(aiohttp_client, mock_agent) -> None:
|
||||
app = create_app(mock_agent, model_name="test-model", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
health = await client.get("/health")
|
||||
missing = await client.get("/v1/models")
|
||||
wrong = await client.get("/v1/models", headers={"Authorization": "Bearer wrong"})
|
||||
ok = await client.get("/v1/models", headers=AUTH_HEADERS)
|
||||
|
||||
assert health.status == 200
|
||||
assert missing.status == 401
|
||||
assert wrong.status == 401
|
||||
assert ok.status == 200
|
||||
assert health.headers["X-Request-ID"]
|
||||
assert ok.headers["X-Request-ID"]
|
||||
assert health.headers["X-Request-ID"] != ok.headers["X-Request-ID"]
|
||||
assert (await missing.json())["error"]["message"].startswith("Missing Authorization")
|
||||
assert (await wrong.json())["error"]["message"] == "Invalid API key"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_request_log_has_correlation_and_completion_fields(
|
||||
aiohttp_client, mock_agent
|
||||
) -> None:
|
||||
records = []
|
||||
sink = logger.add(lambda message: records.append(message.record), level="INFO")
|
||||
try:
|
||||
client = await aiohttp_client(create_app(mock_agent, api_key=API_KEY))
|
||||
response = await client.get("/v1/models", headers=AUTH_HEADERS)
|
||||
finally:
|
||||
logger.remove(sink)
|
||||
|
||||
completion = next(
|
||||
record for record in records if record["extra"].get("event") == "http_request"
|
||||
)
|
||||
assert completion["extra"]["request_id"] == response.headers["X-Request-ID"]
|
||||
assert completion["extra"]["outcome"] == "success"
|
||||
assert completion["extra"]["status_code"] == 200
|
||||
assert completion["extra"]["duration_ms"] >= 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_routes_allow_requests_without_configured_api_key(aiohttp_client, mock_agent) -> None:
|
||||
app = create_app(mock_agent, model_name="test-model")
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
health = await client.get("/health")
|
||||
models = await client.get("/v1/models")
|
||||
chat = await client.post(
|
||||
"/v1/chat/completions",
|
||||
json={"messages": [{"role": "user", "content": "hello"}]},
|
||||
)
|
||||
|
||||
assert health.status == 200
|
||||
assert models.status == 200
|
||||
assert chat.status == 200
|
||||
mock_agent.process_direct.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_prepares_application_resources_before_each_turn(aiohttp_client) -> None:
|
||||
events: list[str] = []
|
||||
agent = _make_mock_agent()
|
||||
|
||||
async def prepare_agent() -> None:
|
||||
events.append("prepare")
|
||||
|
||||
async def process_direct(**_kwargs):
|
||||
events.append("process")
|
||||
return "ready"
|
||||
|
||||
agent.process_direct = process_direct
|
||||
app = create_app(agent, prepare_agent=prepare_agent)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
response = await client.post(
|
||||
"/v1/chat/completions",
|
||||
json={"messages": [{"role": "user", "content": "hello"}]},
|
||||
)
|
||||
|
||||
assert response.status == 200
|
||||
assert events == ["prepare", "process"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_preparation_is_bounded_by_request_timeout(aiohttp_client) -> None:
|
||||
agent = _make_mock_agent()
|
||||
started = asyncio.Event()
|
||||
|
||||
async def prepare_agent() -> None:
|
||||
started.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
app = create_app(
|
||||
agent,
|
||||
request_timeout=0.01,
|
||||
prepare_agent=prepare_agent,
|
||||
)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
response = await client.post(
|
||||
"/v1/chat/completions",
|
||||
json={"messages": [{"role": "user", "content": "hello"}]},
|
||||
)
|
||||
|
||||
assert started.is_set()
|
||||
assert response.status == 504
|
||||
agent.process_direct.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_user_message_returns_400(aiohttp_client, app) -> None:
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "system", "content": "you are a bot"}]},
|
||||
)
|
||||
assert resp.status == 400
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_model_mismatch_returns_400() -> None:
|
||||
request = MagicMock()
|
||||
request.json = AsyncMock(
|
||||
return_value={
|
||||
"model": "other-model",
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
}
|
||||
)
|
||||
request.app = create_app(_make_mock_agent(), model_name="test-model", request_timeout=10.0)
|
||||
|
||||
resp = await handle_chat_completions(request)
|
||||
assert resp.status == 400
|
||||
body = json.loads(resp.body)
|
||||
assert "test-model" in body["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_user_message_required() -> None:
|
||||
request = MagicMock()
|
||||
request.json = AsyncMock(
|
||||
return_value={
|
||||
"messages": [
|
||||
{"role": "user", "content": "hello"},
|
||||
{"role": "assistant", "content": "previous reply"},
|
||||
],
|
||||
}
|
||||
)
|
||||
request.app = create_app(_make_mock_agent(), model_name="test-model", request_timeout=10.0)
|
||||
|
||||
resp = await handle_chat_completions(request)
|
||||
assert resp.status == 400
|
||||
body = json.loads(resp.body)
|
||||
assert "single user message" in body["error"]["message"].lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_user_message_must_have_user_role() -> None:
|
||||
request = MagicMock()
|
||||
request.json = AsyncMock(
|
||||
return_value={
|
||||
"messages": [{"role": "system", "content": "you are a bot"}],
|
||||
}
|
||||
)
|
||||
request.app = create_app(_make_mock_agent(), model_name="test-model", request_timeout=10.0)
|
||||
|
||||
resp = await handle_chat_completions(request)
|
||||
assert resp.status == 400
|
||||
body = json.loads(resp.body)
|
||||
assert "single user message" in body["error"]["message"].lower()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_request_uses_fixed_api_session_and_run_usage(
|
||||
aiohttp_client,
|
||||
mock_agent,
|
||||
) -> None:
|
||||
usage = LLMUsage.reported(input_tokens=100, output_tokens=50)
|
||||
|
||||
async def process_direct(*, hooks: list[AgentHook], **_kwargs: object) -> str:
|
||||
for hook in hooks:
|
||||
await hook.after_run(AgentRunHookContext(messages=[], usage=usage))
|
||||
return "mock response"
|
||||
|
||||
mock_agent.process_direct = AsyncMock(side_effect=process_direct)
|
||||
app = create_app(mock_agent, model_name="test-model", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hello"}]},
|
||||
)
|
||||
assert resp.status == 200
|
||||
body = await resp.json()
|
||||
assert body["choices"][0]["message"]["content"] == "mock response"
|
||||
assert body["model"] == "test-model"
|
||||
assert body["usage"] == {
|
||||
"prompt_tokens": 100,
|
||||
"completion_tokens": 50,
|
||||
"total_tokens": 150,
|
||||
}
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "hello"
|
||||
assert call_kwargs["media"] is None
|
||||
assert call_kwargs["session_key"] == API_SESSION_KEY
|
||||
assert call_kwargs["channel"] == "api"
|
||||
assert call_kwargs["chat_id"] == API_CHAT_ID
|
||||
assert len(call_kwargs["hooks"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_followup_requests_share_same_session_key(aiohttp_client) -> None:
|
||||
call_log: list[str] = []
|
||||
|
||||
async def fake_process(content, session_key="", channel="", chat_id="", **kwargs):
|
||||
call_log.append(session_key)
|
||||
return f"reply to {content}"
|
||||
|
||||
agent = MagicMock()
|
||||
agent.process_direct = fake_process
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
r1 = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "first"}]},
|
||||
)
|
||||
r2 = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "second"}]},
|
||||
)
|
||||
|
||||
assert r1.status == 200
|
||||
assert r2.status == 200
|
||||
assert call_log == [API_SESSION_KEY, API_SESSION_KEY]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.parametrize(("session_id", "chat_id"), [
|
||||
("chat-a", "chat-a"),
|
||||
(" chat-a ", " chat-a "),
|
||||
(" ", " "),
|
||||
("api:chat-a", "api:chat-a"),
|
||||
("会话:a", "会话:a"),
|
||||
("default", "default"),
|
||||
(None, "default"),
|
||||
("", "default"),
|
||||
(0, "default"),
|
||||
(42, "42"),
|
||||
({"id": 1}, "{'id': 1}"),
|
||||
])
|
||||
async def test_session_route_preserves_existing_json_identity(
|
||||
aiohttp_client, mock_agent, session_id, chat_id, stream,
|
||||
) -> None:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
"session_id": session_id, "stream": stream,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 200
|
||||
await resp.read()
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["session_key"] == f"api:{chat_id}"
|
||||
assert call_kwargs["channel"] == "api"
|
||||
assert call_kwargs["chat_id"] == chat_id
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_fixed_session_requests_are_serialized(aiohttp_client) -> None:
|
||||
order: list[str] = []
|
||||
first_started = asyncio.Event()
|
||||
release_first = asyncio.Event()
|
||||
|
||||
async def slow_process(content, session_key="", channel="", chat_id="", **kwargs):
|
||||
order.append(f"start:{content}")
|
||||
if content == "first":
|
||||
first_started.set()
|
||||
await release_first.wait()
|
||||
order.append(f"end:{content}")
|
||||
return content
|
||||
|
||||
agent = MagicMock()
|
||||
agent.process_direct = slow_process
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
|
||||
async def send(msg: str):
|
||||
return await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": msg}]},
|
||||
)
|
||||
|
||||
first = asyncio.create_task(send("first"))
|
||||
await asyncio.wait_for(first_started.wait(), timeout=1.0)
|
||||
second = asyncio.create_task(send("second"))
|
||||
await asyncio.sleep(0)
|
||||
assert order == ["start:first"]
|
||||
|
||||
release_first.set()
|
||||
r1, r2 = await asyncio.gather(first, second)
|
||||
assert r1.status == 200
|
||||
assert r2.status == 200
|
||||
assert order == ["start:first", "end:first", "start:second", "end:second"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_models_endpoint(aiohttp_client, app) -> None:
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.get("/v1/models", headers=AUTH_HEADERS)
|
||||
assert resp.status == 200
|
||||
body = await resp.json()
|
||||
assert body["object"] == "list"
|
||||
assert body["data"][0]["id"] == "test-model"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_health_endpoint(aiohttp_client, app) -> None:
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.get("/health")
|
||||
assert resp.status == 200
|
||||
body = await resp.json()
|
||||
assert body["status"] == "ok"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_multimodal_content_extracts_text(aiohttp_client, mock_agent) -> None:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "describe this"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}},
|
||||
],
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
assert resp.status == 200
|
||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||
assert call_kwargs["content"] == "describe this"
|
||||
assert call_kwargs["session_key"] == API_SESSION_KEY
|
||||
assert call_kwargs["channel"] == "api"
|
||||
assert call_kwargs["chat_id"] == API_CHAT_ID
|
||||
assert len(call_kwargs.get("media") or []) >= 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("content_part", "expected_error"),
|
||||
[
|
||||
({"type": "text", "text": 123}, "messages[0].content[].text must be a string"),
|
||||
(
|
||||
{"type": "image_url", "image_url": "not-an-object"},
|
||||
"messages[0].content[].image_url must be an object",
|
||||
),
|
||||
(
|
||||
{"type": "image_url", "image_url": {"url": 123}},
|
||||
"messages[0].content[].image_url.url must be a string",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_multimodal_invalid_field_type_returns_400(
|
||||
aiohttp_client,
|
||||
mock_agent,
|
||||
content_part: dict[str, object],
|
||||
expected_error: str,
|
||||
) -> None:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [content_part],
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 400
|
||||
body = await resp.json()
|
||||
assert body["error"]["message"] == expected_error
|
||||
assert body["error"]["code"] == 400
|
||||
mock_agent.process_direct.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_multimodal_remote_image_url_returns_400(aiohttp_client, mock_agent) -> None:
|
||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "describe this"},
|
||||
{"type": "image_url", "image_url": {"url": "https://example.com/image.png"}},
|
||||
],
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status == 400
|
||||
body = await resp.json()
|
||||
assert "remote image urls are not supported" in body["error"]["message"].lower()
|
||||
mock_agent.process_direct.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:
|
||||
from nanobot.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
|
||||
|
||||
call_count = 0
|
||||
|
||||
async def always_empty(content, session_key="", channel="", chat_id="", **kwargs):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
return ""
|
||||
|
||||
agent = MagicMock()
|
||||
agent.process_direct = always_empty
|
||||
agent.aclose = AsyncMock()
|
||||
|
||||
app = create_app(agent, model_name="m", api_key=API_KEY)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions",
|
||||
headers=AUTH_HEADERS,
|
||||
json={"messages": [{"role": "user", "content": "hello"}]},
|
||||
)
|
||||
assert resp.status == 200
|
||||
body = await resp.json()
|
||||
assert body["choices"][0]["message"]["content"] == EMPTY_FINAL_RESPONSE_MESSAGE
|
||||
assert call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_direct_accepts_media() -> None:
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
loop = AgentLoop.__new__(AgentLoop)
|
||||
loop._session_locks = {}
|
||||
loop.bus = MessageBus()
|
||||
loop.turn_delivery_factory = TurnDeliveryFactory(loop.bus)
|
||||
loop.runtime_event_publisher = loop.turn_delivery_factory.runtime_event_publisher
|
||||
|
||||
captured_msg = None
|
||||
|
||||
async def fake_process(
|
||||
msg, *, session_key="", on_progress=None, on_stream=None, on_stream_end=None, ephemeral=False, delivery=None,
|
||||
):
|
||||
nonlocal captured_msg
|
||||
captured_msg = msg
|
||||
return None
|
||||
|
||||
loop._process_message = fake_process
|
||||
|
||||
await loop.process_direct(
|
||||
content="analyze this",
|
||||
media=["/tmp/image.png", "/tmp/report.pdf"],
|
||||
session_key="test:1",
|
||||
)
|
||||
|
||||
assert captured_msg is not None
|
||||
assert captured_msg.media == ["/tmp/image.png", "/tmp/report.pdf"]
|
||||
assert captured_msg.content == "analyze this"
|
||||
@@ -1,184 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import asynccontextmanager
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
from nanobot.api.server import API_CHAT_ID, API_SESSION_KEY, create_app
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
AUTH = {"Authorization": "Bearer test-api-key"}
|
||||
|
||||
|
||||
class RouteProvider(LLMProvider):
|
||||
def __init__(self, *, hold_first=False):
|
||||
super().__init__(provider_name="offline-api-test")
|
||||
self.calls = []
|
||||
self.hold_first = hold_first
|
||||
self.started = asyncio.Event()
|
||||
self.release = asyncio.Event()
|
||||
|
||||
def get_default_model(self):
|
||||
return "offline-api-test"
|
||||
|
||||
async def chat(self, messages, tools=None, **kwargs):
|
||||
ctx = current_request_context()
|
||||
assert ctx is not None
|
||||
self.calls.append({
|
||||
"session_key": ctx.session_key,
|
||||
"messages": deepcopy(self._sanitize_empty_content(messages)),
|
||||
"tools": deepcopy(tools),
|
||||
})
|
||||
if self.hold_first and len(self.calls) == 1:
|
||||
self.started.set()
|
||||
await asyncio.wait_for(self.release.wait(), 10)
|
||||
if messages[-1]["role"] != "tool":
|
||||
call_number = 1 + sum(len(message.get("tool_calls", [])) for message in messages)
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id=f"inspect-route-{call_number}", name="my",
|
||||
arguments={"action": "check", "key": "request.chat_id"},
|
||||
)])
|
||||
return LLMResponse(content=json.dumps({
|
||||
"session_key": ctx.session_key,
|
||||
"chat_id": ctx.chat_id,
|
||||
"tool_result": messages[-1]["content"],
|
||||
}))
|
||||
|
||||
async def chat_stream(self, messages, tools=None, on_content_delta=None, **kwargs):
|
||||
response = await self.chat(messages, tools, **kwargs)
|
||||
if response.content and on_content_delta:
|
||||
midpoint = len(response.content) // 2
|
||||
await on_content_delta(response.content[:midpoint])
|
||||
await on_content_delta(response.content[midpoint:])
|
||||
return response
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def runtime(workspace, provider, *, received=None):
|
||||
agent = AgentLoop(
|
||||
bus=MessageBus(), provider=provider, workspace=workspace,
|
||||
restrict_to_workspace=True, max_iterations=3,
|
||||
)
|
||||
app = create_app(agent, api_key="test-api-key")
|
||||
if received is not None:
|
||||
@web.middleware
|
||||
async def observe_request(request, handler):
|
||||
body = await request.json()
|
||||
if body["messages"][0]["content"] == "SECOND_TURN":
|
||||
received.set()
|
||||
return await handler(request)
|
||||
app.middlewares.append(observe_request)
|
||||
client = TestClient(TestServer(app))
|
||||
try:
|
||||
await client.start_server()
|
||||
yield agent, client
|
||||
finally:
|
||||
await client.close()
|
||||
await agent.aclose()
|
||||
|
||||
|
||||
async def post(client, session_id, text, stream=False):
|
||||
response = await client.post(
|
||||
"/v1/chat/completions", headers=AUTH,
|
||||
json={
|
||||
"session_id": session_id, "stream": stream,
|
||||
"messages": [{"role": "user", "content": text}],
|
||||
},
|
||||
)
|
||||
assert response.status == 200, await response.text()
|
||||
if not stream:
|
||||
return json.loads((await response.json())["choices"][0]["message"]["content"])
|
||||
body = await response.text()
|
||||
assert body.endswith("data: [DONE]\n\n")
|
||||
chunks = [json.loads(line[6:]) for line in body.splitlines()
|
||||
if line.startswith("data: ") and line != "data: [DONE]"]
|
||||
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
|
||||
assert len({chunk["id"] for chunk in chunks}) == 1
|
||||
return json.loads("".join(chunk["choices"][0]["delta"].get("content", "") for chunk in chunks))
|
||||
|
||||
|
||||
def assert_route(result, chat_id):
|
||||
assert result["session_key"] == f"api:{chat_id}"
|
||||
assert result["chat_id"] == chat_id
|
||||
assert result["tool_result"] == f"request.chat_id: {chat_id!r}"
|
||||
|
||||
|
||||
def assert_prefix(previous, following):
|
||||
assert json.dumps(previous["messages"], ensure_ascii=False) == json.dumps(
|
||||
following["messages"][:len(previous["messages"])], ensure_ascii=False,
|
||||
)
|
||||
assert json.dumps(previous["tools"], ensure_ascii=False) == json.dumps(
|
||||
following["tools"], ensure_ascii=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.parametrize("second_id", ["alpha", " alpha ", "beta"])
|
||||
async def test_concurrent_requests_keep_routes_history_and_order(tmp_path, stream, second_id):
|
||||
provider = RouteProvider(hold_first=True)
|
||||
received = asyncio.Event()
|
||||
async with runtime(tmp_path / "workspace", provider, received=received) as (_, client):
|
||||
first = asyncio.create_task(post(client, "alpha", "FIRST_TURN", stream))
|
||||
tasks = [first]
|
||||
try:
|
||||
await asyncio.wait_for(provider.started.wait(), 10)
|
||||
second = asyncio.create_task(post(client, second_id, "SECOND_TURN", stream))
|
||||
tasks.append(second)
|
||||
await asyncio.wait_for(received.wait(), 10)
|
||||
if second_id == "alpha":
|
||||
assert len(provider.calls) == 1
|
||||
assert not second.done()
|
||||
provider.release.set()
|
||||
else:
|
||||
assert_route(await asyncio.wait_for(second, 10), second_id)
|
||||
assert not first.done()
|
||||
provider.release.set()
|
||||
assert_route(await asyncio.wait_for(first, 10), "alpha")
|
||||
assert_route(await asyncio.wait_for(second, 10), second_id)
|
||||
second_call = next(call for call in provider.calls
|
||||
if "SECOND_TURN" in json.dumps(call["messages"]))
|
||||
assert ("FIRST_TURN" in json.dumps(second_call["messages"])) == (second_id == "alpha")
|
||||
finally:
|
||||
provider.release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("session_id", ["alpha", " alpha ", " ", None])
|
||||
async def test_old_history_survives_route_fix_restart_and_rollback(tmp_path, session_id):
|
||||
workspace = tmp_path / "workspace"
|
||||
old_key = f"api:{session_id}" if session_id else API_SESSION_KEY
|
||||
old_provider = RouteProvider()
|
||||
async with runtime(workspace, old_provider) as (agent, _):
|
||||
await agent.process_direct(
|
||||
"LEGACY_HISTORY", session_key=old_key, channel="api", chat_id=API_CHAT_ID,
|
||||
)
|
||||
|
||||
upgraded = RouteProvider()
|
||||
async with runtime(workspace, upgraded) as (_, client):
|
||||
result = await post(client, session_id, "UPGRADED_TURN")
|
||||
assert_route(result, session_id or "default")
|
||||
assert "LEGACY_HISTORY" in json.dumps(upgraded.calls[0]["messages"])
|
||||
assert_prefix(old_provider.calls[0], upgraded.calls[0])
|
||||
old_tool_prefix = old_provider.calls[1]["messages"]
|
||||
assert old_tool_prefix == upgraded.calls[0]["messages"][:len(old_tool_prefix)]
|
||||
assert_prefix(upgraded.calls[0], upgraded.calls[1])
|
||||
|
||||
reopened = RouteProvider()
|
||||
async with runtime(workspace, reopened) as (agent, client):
|
||||
assert_route(await post(client, session_id, "AFTER_RESTART"), session_id or "default")
|
||||
replay = json.dumps(reopened.calls[0]["messages"])
|
||||
assert "LEGACY_HISTORY" in replay and "UPGRADED_TURN" in replay
|
||||
await agent.process_direct(
|
||||
"ROLLBACK_TURN", session_key=old_key, channel="api", chat_id=API_CHAT_ID,
|
||||
)
|
||||
replay = json.dumps(reopened.calls[-1]["messages"])
|
||||
assert all(text in replay for text in ("LEGACY_HISTORY", "UPGRADED_TURN", "AFTER_RESTART"))
|
||||
@@ -6,9 +6,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from nanobot.utils.media_decode import (
|
||||
DEFAULT_MAX_BYTES,
|
||||
MAX_FILE_SIZE,
|
||||
FileSizeExceeded,
|
||||
FileSizeExceededError,
|
||||
save_base64_data_url,
|
||||
)
|
||||
|
||||
@@ -134,19 +132,15 @@ def test_unknown_mime_falls_back_to_bin(tmp_path) -> None:
|
||||
|
||||
|
||||
def test_default_limit_is_10mb(tmp_path) -> None:
|
||||
assert DEFAULT_MAX_BYTES == 10 * 1024 * 1024
|
||||
assert MAX_FILE_SIZE == 10 * 1024 * 1024
|
||||
|
||||
oversized = b"x" * (11 * 1024 * 1024)
|
||||
with pytest.raises(FileSizeExceeded, match="10MB limit"):
|
||||
oversized = b"x" * (10 * 1024 * 1024 + 1)
|
||||
with pytest.raises(FileSizeExceededError, match="10MB limit"):
|
||||
save_base64_data_url(_data_url(oversized), tmp_path)
|
||||
|
||||
|
||||
def test_explicit_max_bytes_overrides_default(tmp_path) -> None:
|
||||
"""WS channel passes 8 MB; a 9 MB payload should be rejected there even
|
||||
though it would pass the 10 MB API limit."""
|
||||
"""The caller can reject a payload smaller than the default limit."""
|
||||
payload = b"y" * (9 * 1024 * 1024)
|
||||
with pytest.raises(FileSizeExceeded, match="8MB limit"):
|
||||
with pytest.raises(FileSizeExceededError, match="8MB limit"):
|
||||
save_base64_data_url(_data_url(payload), tmp_path, max_bytes=8 * 1024 * 1024)
|
||||
|
||||
|
||||
@@ -154,13 +148,3 @@ def test_saved_file_lives_under_media_dir(tmp_path) -> None:
|
||||
result = save_base64_data_url(_data_url(b"ok"), tmp_path)
|
||||
assert result is not None
|
||||
assert result.startswith(str(tmp_path))
|
||||
|
||||
|
||||
def test_legacy_symbols_reexported_from_api_server() -> None:
|
||||
"""Existing tests import ``_save_base64_data_url`` / ``_FileSizeExceeded``
|
||||
from ``nanobot.api.server`` — keep the aliases working."""
|
||||
from nanobot.api import server
|
||||
|
||||
assert server._save_base64_data_url is save_base64_data_url
|
||||
assert server._FileSizeExceeded is FileSizeExceeded
|
||||
assert server.MAX_FILE_SIZE == MAX_FILE_SIZE
|
||||
@@ -38,7 +38,5 @@
|
||||
"network.proxy",
|
||||
"tools.web.use_proxy",
|
||||
"tools.web.user_agent",
|
||||
"tools.image_generation.save_dir",
|
||||
"api.host",
|
||||
"api.timeout"
|
||||
"tools.image_generation.save_dir"
|
||||
]
|
||||
@@ -229,6 +229,11 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
|
||||
gateway_port=gateway_port,
|
||||
)
|
||||
|
||||
legacy_config = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
legacy_config["api"] = {"host": "0.0.0.0", "apiKey": "${RETIRED_SMOKE_TOKEN}"}
|
||||
config_path.write_text(json.dumps(legacy_config), encoding="utf-8")
|
||||
before = config_path.read_bytes()
|
||||
|
||||
process = _start_gateway(config_path, log_path)
|
||||
base_url = f"http://127.0.0.1:{ws_port}"
|
||||
try:
|
||||
@@ -240,6 +245,17 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
|
||||
ready = await _recv_until(ws, "ready")
|
||||
assert ready["client_id"] == "smoke"
|
||||
|
||||
# An old WebUI can still connect, but cannot start the retired listener.
|
||||
await ws.send(json.dumps({
|
||||
"type": "webui_request", "request_id": "old-api-start",
|
||||
"action": "settings.api_service.start",
|
||||
"payload": {"host": "127.0.0.1", "port": _free_port(), "timeout": 120},
|
||||
}))
|
||||
rejected = await _recv_until(ws, "webui_response")
|
||||
assert rejected["request_id"] == "old-api-start"
|
||||
assert rejected["ok"] is False and rejected["error"]["status"] == 404
|
||||
assert config_path.read_bytes() == before
|
||||
|
||||
await ws.send(json.dumps({"type": "new_chat"}))
|
||||
attached = await _recv_until(ws, "attached")
|
||||
chat_id = attached["chat_id"]
|
||||
|
||||
@@ -34,7 +34,6 @@ from nanobot.webui.settings_api import (
|
||||
settings_payload,
|
||||
settings_usage_payload,
|
||||
update_agent_settings,
|
||||
update_api_settings,
|
||||
update_model_call_order,
|
||||
update_model_configuration,
|
||||
update_network_safety_settings,
|
||||
@@ -169,7 +168,6 @@ def test_settings_payload_includes_relocated_capabilities(
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.api.port = 9910
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
monkeypatch.setenv("LANGFUSE_SECRET_KEY", "secret")
|
||||
@@ -177,8 +175,6 @@ def test_settings_payload_includes_relocated_capabilities(
|
||||
|
||||
payload = settings_payload()
|
||||
|
||||
assert payload["api"]["port"] == 9910
|
||||
assert payload["api"]["api_key_hint"] is None
|
||||
assert payload["observability"]["provider"] == "langfuse"
|
||||
assert payload["observability"]["configured"] is True
|
||||
|
||||
@@ -198,56 +194,6 @@ def test_settings_payload_exposes_modelscope_image_model(
|
||||
assert providers["modelscope"]["default_model"] == "Qwen/Qwen-Image-2512"
|
||||
|
||||
|
||||
def test_update_api_settings_requires_key_for_network_access(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
with pytest.raises(WebUISettingsError, match="API key"):
|
||||
update_api_settings({"host": ["0.0.0.0"], "port": ["8900"]})
|
||||
|
||||
payload = update_api_settings(
|
||||
{
|
||||
"host": ["0.0.0.0"],
|
||||
"port": ["9900"],
|
||||
"api_key": ["secret-token"],
|
||||
}
|
||||
)
|
||||
saved = load_config(config_path)
|
||||
assert saved.api.host == "0.0.0.0"
|
||||
assert saved.api.port == 9900
|
||||
assert saved.api.api_key == "secret-token"
|
||||
assert payload["api"]["api_key_hint"]
|
||||
|
||||
|
||||
def test_update_api_settings_requires_key_for_specific_network_interface(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
with pytest.raises(WebUISettingsError, match="API key"):
|
||||
update_api_settings({"host": ["192.168.1.10"], "port": ["8900"]})
|
||||
|
||||
|
||||
def test_update_api_settings_allows_alternate_loopback_without_key(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
update_api_settings({"host": ["127.0.0.2"], "port": ["8900"]})
|
||||
|
||||
assert load_config(config_path).api.host == "127.0.0.2"
|
||||
|
||||
|
||||
def _dynamic_provider_config(
|
||||
*,
|
||||
api_base: str = DYNAMIC_PROVIDER_API_BASE,
|
||||
|
||||
@@ -7,7 +7,6 @@ import pytest
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.webui.settings_capabilities import (
|
||||
capability_settings_payload,
|
||||
update_api_settings,
|
||||
update_image_generation_settings,
|
||||
update_network_safety_settings,
|
||||
update_transcription_settings,
|
||||
@@ -75,10 +74,6 @@ def test_capability_domain_updates_representative_settings() -> None:
|
||||
"use_jina_reader": ["false"],
|
||||
},
|
||||
)
|
||||
update_api_settings(
|
||||
config,
|
||||
{"host": ["127.0.0.2"], "port": ["8900"], "timeout": ["90"]},
|
||||
)
|
||||
image_changed = update_image_generation_settings(
|
||||
config,
|
||||
{"enabled": ["true"], "provider": ["openrouter"]},
|
||||
@@ -102,7 +97,5 @@ def test_capability_domain_updates_representative_settings() -> None:
|
||||
assert transcription_changed is True
|
||||
assert (network_changed, access_mode) == (True, "default")
|
||||
assert payload["web_search"]["max_results"] == 7
|
||||
assert payload["api"]["host"] == "127.0.0.2"
|
||||
assert payload["api"]["port"] == 8900
|
||||
assert payload["image_generation"]["enabled"] is True
|
||||
assert payload["transcription"]["provider"] == "openrouter"
|
||||
@@ -974,19 +974,16 @@ async def test_runtime_config_route_authentication_validation_and_restart(tmp_pa
|
||||
assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"]
|
||||
|
||||
|
||||
async def test_runtime_settings_only_save_without_refreshing_or_rebinding(tmp_path, monkeypatch):
|
||||
async def test_runtime_settings_only_save_without_refreshing_or_rebinding(tmp_path):
|
||||
refresh = MagicMock()
|
||||
runtime = MagicMock()
|
||||
monkeypatch.setattr(WebUISettingsRouter, "_api_runtime", lambda _self: runtime)
|
||||
router = _router(config_path=tmp_path / "config.json", refresh_runtime_config=refresh)
|
||||
path = "/api/settings/runtime-config/update"
|
||||
response = await router.dispatch(None, _mutation_request(path, {
|
||||
"values": {"agents.defaults.dream.enabled": False, "api.timeout": 45},
|
||||
"values": {"agents.defaults.dream.enabled": False, "gateway.port": 19001},
|
||||
}), path)
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["requires_restart"]
|
||||
refresh.assert_not_called()
|
||||
runtime.restart.assert_not_called()
|
||||
|
||||
|
||||
async def test_reverting_runtime_switch_clears_restart_but_preserves_other_changes(tmp_path):
|
||||
@@ -1015,7 +1012,7 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
config = router.settings.config.load()
|
||||
original_reader = config.tools.web.fetch.use_jina_reader
|
||||
original_timeout = config.api.timeout
|
||||
original_port = config.gateway.port
|
||||
path = "/api/settings/web-search/update"
|
||||
first = await router.dispatch(None, _mutation_request(path, {
|
||||
"provider": "duckduckgo", "use_jina_reader": not original_reader,
|
||||
@@ -1025,7 +1022,7 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
|
||||
|
||||
runtime_path = "/api/settings/runtime-config/update"
|
||||
changed = await router.dispatch(None, _mutation_request(runtime_path, {
|
||||
"values": {"api.timeout": original_timeout + 1},
|
||||
"values": {"gateway.port": original_port + 1},
|
||||
}), runtime_path)
|
||||
assert changed.status_code == 200
|
||||
assert set(json.loads(changed.body)["restart_required_sections"]) == {"browser", "runtime"}
|
||||
@@ -1038,7 +1035,7 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
|
||||
refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings")
|
||||
assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"]
|
||||
reverted = await router.dispatch(None, _mutation_request(runtime_path, {
|
||||
"values": {"api.timeout": original_timeout},
|
||||
"values": {"gateway.port": original_port},
|
||||
}), runtime_path)
|
||||
assert reverted.status_code == 200
|
||||
assert json.loads(reverted.body)["restart_required_sections"] == []
|
||||
|
||||
@@ -121,7 +121,6 @@ def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
|
||||
assert saved.channels.telegram == {"token": "keep-me", "streaming": False}
|
||||
assert payload["requires_restart"]
|
||||
assert payload["runtime_config"]["tools.image_generation.save_dir"] == "images"
|
||||
assert "api.api_key" not in runtime_config_payload(saved)
|
||||
assert "PRIVATE_API_KEY" not in json.dumps(runtime_config_payload(saved))
|
||||
|
||||
|
||||
@@ -153,8 +152,6 @@ def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
|
||||
{"agents.defaults.timezone_mode": "manual", "agents.defaults.timezone": "Mars/Olympus"},
|
||||
{"gateway.port": 65536},
|
||||
{"gateway.heartbeat.interval_s": 0},
|
||||
{"api.host": "192.168.1.2"},
|
||||
{"api.timeout": float("nan")},
|
||||
{"tools.image_generation.save_dir": ""},
|
||||
{"tools.image_generation.save_dir": "../outside"},
|
||||
{"tools.image_generation.save_dir": "C:/outside"},
|
||||
@@ -230,13 +227,6 @@ def test_timezone_auto_and_nullable_fields():
|
||||
assert not update_runtime_config(config, {}, local_browser=True)
|
||||
|
||||
|
||||
def test_api_changes_require_explicit_restart(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
payload = update_runtime_config_settings({"api.timeout": 222.5}, config_path=path)
|
||||
assert payload["api"]["timeout"] == 222.5
|
||||
assert payload["requires_restart"]
|
||||
|
||||
|
||||
def test_runtime_payload_matches_shared_catalogue_contract():
|
||||
fixture = Path(__file__).with_name("fixtures") / "runtime-config-keys.json"
|
||||
paths = json.loads(fixture.read_text(encoding="utf-8"))
|
||||
|
||||
@@ -11,7 +11,11 @@ from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
from nanobot.webui.settings_api import settings_payload, update_agent_settings, update_api_settings
|
||||
from nanobot.webui.settings_api import (
|
||||
settings_payload,
|
||||
update_agent_settings,
|
||||
update_runtime_config_settings,
|
||||
)
|
||||
from nanobot.webui.settings_services import (
|
||||
WebUIOAuthFlowRegistry,
|
||||
WebUISettingsServices,
|
||||
@@ -56,9 +60,9 @@ def test_gateway_settings_services_isolate_config_paths_and_oauth_flows(
|
||||
first_path = tmp_path / "first" / "config.json"
|
||||
second_path = tmp_path / "second" / "config.json"
|
||||
first_config = Config()
|
||||
first_config.api.host = "127.0.0.2"
|
||||
first_config.gateway.host = "127.0.0.2"
|
||||
second_config = Config()
|
||||
second_config.api.host = "127.0.0.3"
|
||||
second_config.gateway.host = "127.0.0.3"
|
||||
save_config(first_config, first_path)
|
||||
save_config(second_config, second_path)
|
||||
|
||||
@@ -69,14 +73,14 @@ def test_gateway_settings_services_isolate_config_paths_and_oauth_flows(
|
||||
assert second.settings.config.path == second_path.resolve()
|
||||
assert first.http.settings_routes.settings is first.settings
|
||||
assert second.http.settings_routes.settings is second.settings
|
||||
assert first.settings.config.load().api.host == "127.0.0.2"
|
||||
assert second.settings.config.load().api.host == "127.0.0.3"
|
||||
assert first.settings.read(settings_payload)["api"]["host"] == "127.0.0.2"
|
||||
assert second.settings.read(settings_payload)["api"]["host"] == "127.0.0.3"
|
||||
assert first.settings.config.load().gateway.host == "127.0.0.2"
|
||||
assert second.settings.config.load().gateway.host == "127.0.0.3"
|
||||
assert first.settings.read(settings_payload)["runtime_config"]["gateway.host"] == "127.0.0.2"
|
||||
assert second.settings.read(settings_payload)["runtime_config"]["gateway.host"] == "127.0.0.3"
|
||||
|
||||
first.settings.mutate(update_api_settings, {"port": ["19001"]})
|
||||
assert load_config(first_path).api.port == 19001
|
||||
assert load_config(second_path).api.port != 19001
|
||||
first.settings.mutate(update_runtime_config_settings, {"gateway.port": 19001})
|
||||
assert load_config(first_path).gateway.port == 19001
|
||||
assert load_config(second_path).gateway.port != 19001
|
||||
|
||||
first_flow = _Flow()
|
||||
second_flow = _Flow()
|
||||
@@ -94,9 +98,9 @@ def test_settings_service_supports_a_new_config_directory(tmp_path: Path) -> Non
|
||||
config_path = tmp_path / "new" / "nested" / "config.json"
|
||||
|
||||
services = WebUISettingsServices.create(config_path)
|
||||
services.mutate(update_api_settings, {"port": ["19001"]})
|
||||
services.mutate(update_runtime_config_settings, {"gateway.port": 19001})
|
||||
|
||||
assert load_config(config_path).api.port == 19001
|
||||
assert load_config(config_path).gateway.port == 19001
|
||||
|
||||
|
||||
def test_settings_mutations_serialize_read_modify_write(
|
||||
@@ -137,7 +141,7 @@ def test_settings_mutations_serialize_read_modify_write(
|
||||
def run_second() -> None:
|
||||
try:
|
||||
second_started.set()
|
||||
services.mutate(update_api_settings, {"host": ["127.0.0.9"]})
|
||||
services.mutate(update_runtime_config_settings, {"gateway.host": "127.0.0.9"})
|
||||
except BaseException as exc: # noqa: BLE001 - re-raised in the test thread
|
||||
errors.append(exc)
|
||||
|
||||
@@ -157,7 +161,7 @@ def test_settings_mutations_serialize_read_modify_write(
|
||||
assert not errors
|
||||
saved = load_config(config_path)
|
||||
assert saved.agents.defaults.timezone == "Asia/Tokyo"
|
||||
assert saved.api.host == "127.0.0.9"
|
||||
assert saved.gateway.host == "127.0.0.9"
|
||||
|
||||
|
||||
def test_distinct_gateways_serialize_mutations_for_the_same_config(
|
||||
@@ -192,7 +196,7 @@ def test_distinct_gateways_serialize_mutations_for_the_same_config(
|
||||
def mutate(
|
||||
services: WebUISettingsServices,
|
||||
operation: Callable[..., object],
|
||||
query: dict[str, list[str]],
|
||||
query: dict[str, str],
|
||||
) -> None:
|
||||
try:
|
||||
services.mutate(operation, query)
|
||||
@@ -206,7 +210,7 @@ def test_distinct_gateways_serialize_mutations_for_the_same_config(
|
||||
)
|
||||
second = threading.Thread(
|
||||
target=mutate,
|
||||
args=(second_services, update_api_settings, {"host": ["127.0.0.9"]}),
|
||||
args=(second_services, update_runtime_config_settings, {"gateway.host": "127.0.0.9"}),
|
||||
name="gateway-second",
|
||||
)
|
||||
first.start()
|
||||
@@ -222,7 +226,7 @@ def test_distinct_gateways_serialize_mutations_for_the_same_config(
|
||||
assert not errors
|
||||
saved = load_config(config_path)
|
||||
assert saved.agents.defaults.timezone == "Asia/Tokyo"
|
||||
assert saved.api.host == "127.0.0.9"
|
||||
assert saved.gateway.host == "127.0.0.9"
|
||||
|
||||
|
||||
def test_oauth_registry_preserves_expiry_capacity_completion_and_cancel() -> None:
|
||||
|
||||
Reference in new issue
Block a user