我正在使用DBus进行进程间通信。为了在整个程序生命周期中只有一个总线,我在这里使用单例模式。为了演示,我连接NetworkManager,但可以替换为其他服务。此外,我在整个项目中都使用asyncio。
以下是该模块的最小工作示例,可以突出下面描述的问题:
import asyncio # noqa
from dbus_next.aio import MessageBus
from dbus_next import BusType
BUS = None
async def get_bus():
# Returns a BUS singleton
global BUS
if not BUS:
BUS = await MessageBus(bus_type=BusType(2)).connect()
return BUS
async def introspect():
# Get the dbus singleton and call a method on that singleton
bus = await get_bus()
return await bus.introspect(
'org.freedesktop.NetworkManager',
'/org/freedesktop/NetworkManager',
)
我正在使用带有pytest-asyncio
插件的pytest
进行测试,这非常有效,除了这个问题。
这是一个极简的工作测试模块:
import pytest
from example import introspect
@pytest.mark.asyncio
async def test_example_first():
# With only this first call the test passes
await introspect()
@pytest.mark.asyncio
async def test_example_second():
# This second call will lead to the exception below.
await introspect()
当我执行该测试时,我得到了以下异常,指示事件循环已更改:
example.py:22: in introspect
'/org/freedesktop/NetworkManager',
../.local/lib/python3.7/site-packages/dbus_next/aio/message_bus.py:133: in introspect
return await asyncio.wait_for(future, timeout=timeout)
/usr/lib/python3.7/asyncio/tasks.py:403: in wait_for
fut = ensure_future(fut, loop=loop)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
coro_or_future = <Future pending>
def ensure_future(coro_or_future, *, loop=None):
"""Wrap a coroutine or an awaitable in a future.
If the argument is a Future, it is returned directly.
"""
if coroutines.iscoroutine(coro_or_future):
if loop is None:
loop = events.get_event_loop()
task = loop.create_task(coro_or_future)
if task._source_traceback:
del task._source_traceback[-1]
return task
elif futures.isfuture(coro_or_future):
if loop is not None and loop is not futures._get_loop(coro_or_future):
> raise ValueError('loop argument must agree with Future')
E ValueError: loop argument must agree with Future
我猜测pytest启动了一个事件循环,并且在模块导入期间启动了另一个事件循环,但我不确定。我尝试使用pytest
或模块事件循环来强制执行,使用asyncio.set_event_loop()
,但没有成功。结果保持不变。
我的假设是否正确?如何强制使用全局事件循环?或者,我应该如何定义此单例以使其能够与pytest
一起工作?
值得注意的是,在程序的上下文中,此单例构造完全正常。只是测试时我无法想出如何使其正常工作。