Files
KiloStar/tests/unit/test_utils_actor.py
T

95 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""进程内 actor 运行时(``kilostar.utils.actor``)单元测试。
覆盖:注册/寻址/注销;句柄对同步与异步方法都返回 awaitable;便捷 getter
未注册抛 KeyError。
"""
from __future__ import annotations
import pytest
from kilostar.utils import actor as actor_mod
from kilostar.utils.actor import (
clear_actors,
get_actor,
get_gsm,
get_gwm,
get_postgres,
register_actor,
unregister_actor,
)
@pytest.fixture(autouse=True)
def _clean_registry():
clear_actors()
yield
clear_actors()
class _Sample:
def __init__(self) -> None:
self.value = 7
def sync_method(self, x):
return x + 1
async def async_method(self, x):
return x * 2
@pytest.mark.asyncio
async def test_sync_method_is_awaitable_through_handle():
register_actor("sample", _Sample())
handle = get_actor("sample")
assert await handle.sync_method(41) == 42
@pytest.mark.asyncio
async def test_async_method_forwards_through_handle():
register_actor("sample", _Sample())
handle = get_actor("sample")
assert await handle.async_method(21) == 42
def test_non_callable_attribute_passthrough():
register_actor("sample", _Sample())
assert get_actor("sample").value == 7
def test_get_unregistered_raises_keyerror():
with pytest.raises(KeyError):
get_actor("does_not_exist")
def test_unregister_then_missing():
register_actor("sample", _Sample())
assert get_actor("sample") is not None
unregister_actor("sample")
with pytest.raises(KeyError):
get_actor("sample")
# 幂等:再次注销不报错
unregister_actor("sample")
def test_convenience_getters_resolve_named_actors():
register_actor("postgres_database", _Sample())
register_actor("global_state_machine", _Sample())
register_actor("global_workflow_manager", _Sample())
assert get_postgres() is get_actor("postgres_database")
assert get_gsm() is get_actor("global_state_machine")
assert get_gwm() is get_actor("global_workflow_manager")
@pytest.mark.asyncio
async def test_reregister_overwrites_underlying_instance():
first = _Sample()
first.value = 100
register_actor("sample", first)
assert get_actor("sample").value == 100
second = _Sample()
second.value = 200
register_actor("sample", second)
assert get_actor("sample").value == 200