mirror of
https://github.com/AstrBotDevs/AstrBot
synced 2026-07-16 01:40:15 +08:00
* refactor: migrate to fastapi * structure refactor * fix: pyright fix * refactor: improve error handling and public messages in plugin services * feat(api): refactor API client integration and enhance request handling - Updated API client configuration to use a dedicated HTTP client. - Introduced utility functions for generating options, queries, and form data for API requests. - Refactored multiple API methods to utilize the new utility functions for improved consistency and readability. - Renamed types for clarity and updated import statements accordingly. feat(docs): add script to update OpenAPI JSON from YAML spec - Created a Python script to convert OpenAPI YAML specification to JSON format. - The script supports customizable input and output paths. - Ensured the script handles directory creation for output paths and validates the YAML structure. * fix * feat(auth): implement rate limiting for v1 login endpoint and enhance request handling * Refactor dashboard API routers to use legacy_router for backward compatibility - Changed all instances of dashboard_router to legacy_router across multiple API modules including platform, plugins, providers, sessions, skills, stats, subagents, t2i, tools, updates, and asgi_runtime. - Updated route definitions to ensure existing endpoints remain functional under the new router structure. - Introduced support for Quart request context in asgi_runtime to enhance compatibility with existing Quart-based plugins. - Added a test case to validate the functionality of the new Quart request context handling in plugin extensions. * chore: remove cli test * fix: update dashboard tests for fastapi migration * chore: satisfy ruff checks * fix: update openapi api key scopes * fix: sync config scope chip selection * fix: restore quart dependency * docs: clarify quart plugin api compatibility * docs: update openapi scope documentation * fix: use singular skill openapi scope * fix: hide update service exception details * fix: address fastapi review comments * fix: address dashboard review findings * docs: revert unrelated package deployment changes * docs: update agent api generation guidance * feat: add plugin page web api helpers * docs: add plugin page bridge demo * fix: type plugin upload files * fix: stabilize plugin page uploads * fix: type plugin web request proxy * docs: remove plugin page docs example * fix: authenticate plugin page SSE bridge
143 lines
4.2 KiB
Python
143 lines
4.2 KiB
Python
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from starlette.websockets import WebSocketDisconnect
|
|
|
|
from astrbot.dashboard.services.live_chat_service import LiveChatService
|
|
|
|
|
|
def _service() -> LiveChatService:
|
|
core_lifecycle = SimpleNamespace(
|
|
astrbot_config={"dashboard": {"jwt_secret": "test-secret"}},
|
|
plugin_manager=SimpleNamespace(),
|
|
platform_message_history_manager=SimpleNamespace(),
|
|
)
|
|
return LiveChatService(SimpleNamespace(), core_lifecycle)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_websocket_session_closes_when_token_is_missing():
|
|
service = _service()
|
|
closed: list[tuple[int, str]] = []
|
|
|
|
async def close(code: int, reason: str) -> None:
|
|
closed.append((code, reason))
|
|
|
|
async def receive_json() -> dict:
|
|
raise AssertionError("receive_json should not be called")
|
|
|
|
async def send_json(payload: dict) -> None:
|
|
raise AssertionError(f"send_json should not be called: {payload}")
|
|
|
|
await service.run_websocket_session(
|
|
token=None,
|
|
force_ct=None,
|
|
receive_json=receive_json,
|
|
send_json=send_json,
|
|
close=close,
|
|
)
|
|
|
|
assert closed == [(1008, "Missing authentication token")]
|
|
assert service.sessions == {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_websocket_session_routes_messages_and_cleans_session(monkeypatch):
|
|
service = _service()
|
|
messages = iter(
|
|
[
|
|
{"ct": "chat", "t": "bind", "session_id": "chat-session"},
|
|
{"t": "start_speaking", "stamp": "s1"},
|
|
]
|
|
)
|
|
routed: list[tuple[str, str, dict]] = []
|
|
|
|
monkeypatch.setattr(service, "authenticate_token", lambda _token: "alice")
|
|
|
|
async def handle_chat_message(session, message, _send_json) -> None:
|
|
routed.append(("chat", session.username, message))
|
|
|
|
async def handle_live_message(session, message, _send_json) -> None:
|
|
routed.append(("live", session.username, message))
|
|
|
|
monkeypatch.setattr(service, "handle_chat_message", handle_chat_message)
|
|
monkeypatch.setattr(service, "handle_live_message", handle_live_message)
|
|
|
|
async def receive_json() -> dict:
|
|
try:
|
|
return next(messages)
|
|
except StopIteration as exc:
|
|
raise RuntimeError("disconnect") from exc
|
|
|
|
async def send_json(_payload: dict) -> None:
|
|
pass
|
|
|
|
async def close(_code: int, _reason: str) -> None:
|
|
raise AssertionError("close should not be called")
|
|
|
|
await service.run_websocket_session(
|
|
token="valid",
|
|
force_ct=None,
|
|
receive_json=receive_json,
|
|
send_json=send_json,
|
|
close=close,
|
|
)
|
|
|
|
assert [(kind, username) for kind, username, _ in routed] == [
|
|
("chat", "alice"),
|
|
("live", "alice"),
|
|
]
|
|
assert service.sessions == {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_websocket_session_handles_disconnect_without_error_log(
|
|
monkeypatch,
|
|
):
|
|
service = _service()
|
|
messages = iter([{"ct": "chat", "t": "bind", "session_id": "chat-session"}])
|
|
routed: list[dict] = []
|
|
|
|
monkeypatch.setattr(service, "authenticate_token", lambda _token: "alice")
|
|
|
|
async def handle_chat_message(session, message, _send_json) -> None:
|
|
routed.append({"username": session.username, "message": message})
|
|
|
|
monkeypatch.setattr(service, "handle_chat_message", handle_chat_message)
|
|
|
|
async def receive_json() -> dict:
|
|
try:
|
|
return next(messages)
|
|
except StopIteration as exc:
|
|
raise WebSocketDisconnect(1006) from exc
|
|
|
|
async def send_json(_payload: dict) -> None:
|
|
pass
|
|
|
|
async def close(_code: int, _reason: str) -> None:
|
|
raise AssertionError("close should not be called")
|
|
|
|
def fail_error_log(*_args, **_kwargs) -> None:
|
|
raise AssertionError("disconnect should not be logged as an error")
|
|
|
|
monkeypatch.setattr(
|
|
"astrbot.dashboard.services.live_chat_service.logger.error",
|
|
fail_error_log,
|
|
)
|
|
|
|
await service.run_websocket_session(
|
|
token="valid",
|
|
force_ct=None,
|
|
receive_json=receive_json,
|
|
send_json=send_json,
|
|
close=close,
|
|
)
|
|
|
|
assert routed == [
|
|
{
|
|
"username": "alice",
|
|
"message": {"ct": "chat", "t": "bind", "session_id": "chat-session"},
|
|
}
|
|
]
|
|
assert service.sessions == {}
|