【发布时间】: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