Skip to content

Commit f4bc865

Browse files
committed
Handle sync command service handlers
1 parent 7357848 commit f4bc865

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/core/interfaces/command_service.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import inspect
34
from collections.abc import Awaitable, Callable
45
from typing import Any
56

@@ -24,7 +25,18 @@ def __init__(self, handler: CommandServiceHandler):
2425
async def process_commands(
2526
self, messages: list[Any], session_id: str
2627
) -> ProcessedResult:
27-
return await self._handler(messages, session_id)
28+
result = self._handler(messages, session_id)
29+
30+
if inspect.isawaitable(result):
31+
return await result
32+
33+
if isinstance(result, ProcessedResult):
34+
return result
35+
36+
raise TypeError(
37+
"The command service handler must return a ProcessedResult or an awaitable"
38+
" resolving to ProcessedResult."
39+
)
2840

2941

3042
def ensure_command_service(

tests/unit/core/test_command_service_module.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import pytest
2+
23
from src.core.domain.processed_result import ProcessedResult
34
from src.core.interfaces.command_service import ensure_command_service
45
from src.core.interfaces.command_service_interface import ICommandService
@@ -48,6 +49,23 @@ async def handler(messages: list[str], session_id: str) -> ProcessedResult:
4849
assert result.command_results == ["session"]
4950

5051

52+
@pytest.mark.asyncio
53+
async def test_ensure_command_service_wraps_sync_callable() -> None:
54+
def handler(messages: list[str], session_id: str) -> ProcessedResult:
55+
return ProcessedResult(
56+
modified_messages=[value.upper() for value in messages],
57+
command_executed=True,
58+
command_results=[session_id],
59+
)
60+
61+
validated_service = ensure_command_service(handler)
62+
63+
result = await validated_service.process_commands(["hello"], "session")
64+
assert result.modified_messages == ["HELLO"]
65+
assert result.command_executed is True
66+
assert result.command_results == ["session"]
67+
68+
5169
def test_ensure_command_service_rejects_none() -> None:
5270
with pytest.raises(ValueError) as exc:
5371
ensure_command_service(None)

0 commit comments

Comments
 (0)