Pytest:使用Pytest -xdist对所有工人运行一次teardown



我有一个pytest fixture,我只需要在所有pytest worker上运行一次。

@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的解决方案,它适用于pytestsetup部分,但teardown部分在每个pytest进程中都被调用。

是否有可能锁定pytest-xdistteardown,以便在所有pytest会话完成后仅运行一次?我想对所有工人运行一次teardown。

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

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

最新更新