我有一个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会话完成之后,可以锁定pytest-xdist teardown来运行它一次吗?我想为所有的工人做一次催泪弹。
发布于 2022-10-13 04:21:38
不确定这是否回答了您的问题,或者是最理想的方法(我不太确定您想要删除的是什么样子),但是pytest_sessionfinish函数在所有测试结束时运行。如果您检查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
https://stackoverflow.com/questions/72225847
复制相似问题