Pytest:使用 pytest-xdist 对所有工作人员运行一次拆卸

Vla*_*llo 8 python pytest pytest-xdist

我有一个 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
Run Code Online (Sandbox Code Playgroud)

我使用https://pytest-xdist.readthedocs.io/en/latest/how-to.html?highlight=only%20once#making-session-scoped-fixtures-execute-only-once中的解决方案,效果很好对于 pytestsetup部分,但该teardown部分在每个 pytest 进程中都会被调用。

是否可以锁定pytest-xdist拆卸以在所有 pytest 会话完成后仅运行一次?我想为所有工人运行一次拆卸。

Jus*_*ess 3

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

def pytest_sessionfinish(session, exitstatus):
    """Insert teardown that you want to occur only once here"""
    if not hasattr(session.config, "workerinput"):
        pass
Run Code Online (Sandbox Code Playgroud)

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