Dan*_*ell 7 python pytest python-asyncio pytest-asyncio
我认为下面的例子是一个非常常见的用例:
改变@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"
Run Code Online (Sandbox Code Playgroud)
Dan*_*ell 12
解决方案是使用模块范围重新定义 event_loop 夹具。将其包含在测试文件中。
@pytest.fixture(scope="module")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
Run Code Online (Sandbox Code Playgroud)
类似的 ScopeMismatch 问题在 github 中针对 pytest-asyncio (链接)提出。解决方案(如下)对我有用:
@pytest.yield_fixture(scope='class')
def event_loop(request):
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2519 次 |
| 最近记录: |