"""守护一类只会静默失败的 bug:方法被同名实例属性遮住。 nanobot channel 的 ``GatewayClient`` 里 ``self.stop = asyncio.Event()`` 把 ``async def stop()`` 遮住了,于是 channel 停机时 ``await self._client.stop()`` 抛 ``TypeError: 'Event' object is not callable``。它在正常收发消息时完全看不出来, 只在容器停机路径上炸,所以这里用 AST 静态拦一道(不依赖能否 import 被测文件)。 """ import ast import pathlib import pytest ROOT = pathlib.Path(__file__).resolve().parents[2] CHANNEL = ROOT / "deploy" / "nanobot-gateway" / "channel" / "agenthub" / "agenthub_client.py" def _shadowed_methods(path: pathlib.Path, cls_name: str) -> set[str]: """Return the class's own method names that __init__ rebinds as attributes.""" tree = ast.parse(path.read_text(encoding="utf-8")) for node in tree.body: if isinstance(node, ast.ClassDef) and node.name == cls_name: methods = { item.name for item in node.body if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef) } rebound: set[str] = set() for item in node.body: if not (isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef) and item.name == "__init__"): continue for sub in ast.walk(item): if isinstance(sub, ast.Attribute) and isinstance(sub.ctx, ast.Store): if isinstance(sub.value, ast.Name) and sub.value.id == "self": rebound.add(sub.attr) return methods & rebound raise AssertionError(f"class {cls_name} not found in {path}") @pytest.mark.parametrize( ("path", "cls_name"), [(CHANNEL, "GatewayClient")], ids=["embedded-channel"], ) def test_no_method_is_shadowed_by_an_instance_attribute(path: pathlib.Path, cls_name: str) -> None: assert path.exists(), f"missing {path}" assert _shadowed_methods(path, cls_name) == set(), ( f"{cls_name}.__init__ 用同名属性遮住了方法;调用方拿到的将是属性而不是方法" ) def test_channel_client_exposes_an_awaitable_request_stop() -> None: """停机入口必须存在且可 await;Event 信号仍叫 .stop(与 connector 侧同约定)。""" pytest.importorskip("websockets") import importlib.util import inspect import sys # 被测文件在 deploy/ 里,那份目录会被 compose 只读挂进容器:别让测试往里面写 __pycache__。 previous = sys.dont_write_bytecode sys.dont_write_bytecode = True spec = importlib.util.spec_from_file_location("agenthub_gateway_client", CHANNEL) assert spec and spec.loader module = importlib.util.module_from_spec(spec) # 先登记再执行:文件里的 @dataclass(slots=True) 要靠 sys.modules 解析注解。 sys.modules[spec.name] = module try: spec.loader.exec_module(module) finally: sys.dont_write_bytecode = previous client = module.GatewayClient assert inspect.iscoroutinefunction(client.request_stop) assert not hasattr(client, "stop"), "类属性 stop 会掩盖约定:stop 只是实例上的 Event"