我需要使用 @method
库的 jsonrpcserver
注释修饰类方法。该类正在实现一个 rpc 服务器,该服务器作为 asyncio 服务器启动,并使用这样的 pytest 固定装置启动
# conftest.py
@pytest.fixture(autouse=True, scope="module")
@pytest.mark.asyncio
async def rpc_server(...):
rpc_server = RpcServer(
addr="127.0.0.1",
port=9500,
...
)
task = asyncio.create_task(rpc_server.start())
yield rpc_server
task.cancel()
测试应该对 RpcServer
类的方法之一进行猴子补丁
# test_rpc.py
@pytest.mark.asyncio
async def test_rpc_server_exception(
rpc_server: RpcServer,
...
monkeypatch: MonkeyPatch,
):
async def raise_runtime_error():
raise RuntimeError()
monkeypatch.setattr(
RpcServer, "method_to_be_patched", raise_runtime_error, raising=True
)
... # making an rpc request to launch method_to_be_patched
assert ...
method_to_be_patched
在收到新请求后由 async_dispatch
库的 jsonrpcserver
调用,如下所示
# rpc_server.py
@method
async def method_to_be_patched(self, ...) -> str:
...
return ...
问题是monkeypatch 没有修补任何东西,并且测试通过而没有引发任何异常(就像我需要的那样)。我已经尝试对 RpcServer
进行monkeypatch from ... import ...
和 pytest 固定装置的实例收益,但没有任何成功,但通过调试似乎类方法正确指向了虚拟函数,但仍然调用了原始函数。
编辑:问题是由于 python 导入工作而出现的。据我了解,在导入 test_rpc.py
时,我正在创建一个新的引用,所以基本上我正在修补从 rpc_server.py
创建的引用而不是 # test_rpc.py
@pytest.mark.asyncio
async def test_rpc_server_exception(
rpc_server: RpcServer,
...
monkeypatch: MonkeyPatch,
):
async def raise_runtime_error():
raise RuntimeError()
import network # the package containing rpc_server.py
monkeypatch.setattr(
network.rpc_server.RpcServer, "method_to_be_patched", raise_runtime_error, raising=True
)
... # making an rpc request to launch method_to_be_patched
assert ...
中的引用(纠正我,如果我错了)。
所以我尝试了
/src
|rpc_server.py
/test
|conftest.py
/e2e
|test_rpc.py
但仍然没有达到预期的行为。
项目树是这样的
Python Path
答案 0 :(得分:0)
解决方案是monkeypatch where 方法被调用,所以因为我在这里使用jsonrpcserver
我不得不monkeypatch {{1} 中定义的call
方法模块,现在它按我的预期工作