【问题标题】:Pytest: run teardown once for all workers using pytest-xdistPytest:使用 pytest-xdist 为所有工作人员运行一次拆卸
【发布时间】:2022-10-13 12:21:38
【问题描述】:

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

@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-xdist teardown 在所有 pytest 会话完成后只运行一次?我想为所有工人运行一次拆卸。

【问题讨论】:

    标签: python pytest pytest-xdist


    【解决方案1】:

    不确定这是否回答了您的问题或者是最佳方法(我不太确定您希望拆解看起来像什么),但是 pytest_sessionfinish 函数在所有测试结束时运行,并且只运行一次。它可能对你有用。

    def pytest_sessionfinish(session, exitstatus):
        """Insert teardown that you want to occur only once here"""
        pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      相关资源
      最近更新 更多