【问题标题】:pytest issues with a session scoped fixture and asyncio会话范围内的夹具和异步的 pytest 问题
【发布时间】:2020-09-02 21:08:16
【问题描述】:

我有多个测试文件,每个都有一个如下所示的异步夹具:


@pytest.fixture(scope="module")
def event_loop(request):
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()


@pytest.fixture(scope="module")
async def some_fixture():
    return await make_fixture()

我正在使用 xdist 进行并行化。另外我有这个装饰器:

@toolz.curry
def throttle(limit, f):
    semaphore = asyncio.Semaphore(limit)

    @functools.wraps(f)
    async def wrapped(*args, **kwargs):
        async with semaphore:
            return await f(*args, **kwargs)

    return wrapped

我有一个函数使用它:

@throttle(10)
def f():
    ...

现在 f 从多个测试文件中被调用,我收到一个异常,告诉我我不能使用来自不同事件循环的信号量。

我尝试转移到会话级事件循环装置:



@pytest.fixture(scope="session", autouse=True)
def event_loop(request):
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

但这只是给了我:

ScopeMismatch:您尝试使用“模块”范围的请求对象访问“功能”范围的夹具“事件循环”,涉及工厂

甚至可以让 xdist + async fixture + semaphore 一起工作吗?

【问题讨论】:

    标签: python pytest python-asyncio semaphore pytest-xdist


    【解决方案1】:

    最终使用以下conftest.py 让它工作:

    import asyncio
    
    import pytest
    
    
    @pytest.fixture(scope="session")
    def event_loop():
        return asyncio.get_event_loop()
    

    【讨论】:

    • 这对我有用,但它似乎是 pytest-asyncio 的错误
    猜你喜欢
    • 2022-06-12
    • 2020-01-16
    • 2020-04-27
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多