我认为下面的示例是一个非常常见的用例:
更改@pytest.fixture(scope="module")
的范围将导致ScopeMismatch: You tried to access the 'function' scoped fixture 'event_loop' with a 'module' scoped request object, involved factories
。
另外,test_insert
和test_find
协同器不需要event_loop参数,因为通过传递连接已经可以访问循环。
有什么办法解决这两个问题吗?
import pytest
@pytest.fixture(scope="function") # <-- want this to be scope="module"; run once!
@pytest.mark.asyncio
async def connection(event_loop):
""" Expensive function; want to do in the module scope. Only this function needs `event_loop`!
"""
conn await = make_connection(event_loop)
return conn
@pytest.mark.dependency()
@pytest.mark.asyncio
async def test_insert(connection, event_loop): # <-- does not need event_loop arg
""" Test insert into database.
NB does not need event_loop argument; just the connection.
"""
_id = 0
success = await connection.insert(_id, "data")
assert success == True
@pytest.mark.dependency(depends=['test_insert'])
@pytest.mark.asyncio
async def test_find(connection, event_loop): # <-- does not need event_loop arg
""" Test database find.
NB does not need event_loop argument; just the connection.
"""
_id = 0
data = await connection.find(_id)
assert data == "data"
发布于 2019-05-21 12:33:13
解决方案是重新定义带有模块作用域的event_loop夹具。将其包含在测试文件中。
@pytest.fixture(scope="module")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
发布于 2020-08-19 17:53:47
github中也提出了类似的ScopeMismatch问题,用于pytest-异步(链接)。解决方案(以下)适用于我:
@pytest.yield_fixture(scope='class')
def event_loop(request):
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
https://stackoverflow.com/questions/56236637
复制相似问题