首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pytest:为所有使用pytest-xdist的工人运行一次teardown。

Pytest:为所有使用pytest-xdist的工人运行一次teardown。
EN

Stack Overflow用户
提问于 2022-05-13 07:26:55
回答 1查看 527关注 0票数 5

我有一个pytest夹具,我只需要在所有的pytest工作人员中运行一次。

代码语言:javascript
复制
@pytest.fixture(scope="session")
@shared  # this will call setup once for all processes
def cache(request):
    acc = Account(id=10)
    acc.create()
    request.addfinilizer(acc.delete)
    return acc


def shared(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        request = kwargs['request']
        root = request.config._tmp_path_factory.getbasetemp().parent
        filepath = root / "shared"

        with filelock.FileLock(f'{filepath}.lock'):
            if filepath.is_file():
                result = json.loads(filepath.read_text())
            else:
                result = func(*args, **kwargs)
                filepath.write_text(json.dumps(result.id))

        return result
    return wrapper

我使用来自https://pytest-xdist.readthedocs.io/en/latest/how-to.html?highlight=only%20once#making-session-scoped-fixtures-execute-only-once的解决方案,它对pytest setup部件很好,但是在每个pytest过程中都调用了teardown部分。

在所有pytest会话完成之后,可以锁定pytest-xdist teardown来运行它一次吗?我想为所有的工人做一次催泪弹。

EN

回答 1

Stack Overflow用户

发布于 2022-10-13 04:21:38

不确定这是否回答了您的问题,或者是最理想的方法(我不太确定您想要删除的是什么样子),但是pytest_sessionfinish函数在所有测试结束时运行。如果您检查worker输入属性,它将在所有其他进程完成测试后在主线程中运行。

代码语言:javascript
复制
def pytest_sessionfinish(session, exitstatus):
    """Insert teardown that you want to occur only once here"""
    if not hasattr(session.config, "workerinput"):
        pass

来源:https://github.com/pytest-dev/pytest-xdist/issues/271#issuecomment-826396320

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72225847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档