【问题标题】:Pytest setup/teardown hooks for session会话的 Pytest 设置/拆卸钩子
【发布时间】:2025-11-24 19:35:02
【问题描述】:

Pytest has setup and teardowns 挂钩 module, class, method

我想在设置中创建我的自定义测试环境(在测试会话开始之前)并在所有测试完成后进行清理。 换句话说,我怎样才能使用像setup_session and teardown_session这样的钩子?

【问题讨论】:

  • @AriGold。实际上我不使用任何单元测试类。我正在编写使用 pytest 夹具的测试函数。我在您的链接中看到了 setup_class/teardown_class 用法的示例。但我正在寻找类似 setup_session/teardown_session 的东西。

标签: python unit-testing hook pytest


【解决方案1】:

这些钩子对我很有效:

def pytest_sessionstart(session):
    # setup_stuff

def pytest_sessionfinish(session, exitstatus):
    # teardown_stuff

但实际上下一个具有会话范围的夹具看起来更漂亮:

@fixture(autouse=True, scope='session')
def my_fixture():
    # setup_stuff
    yield
    # teardown_stuff

【讨论】:

  • 这就是我使用的方法(会话范围的自动使用装置)。但是,在 pytest 版本中 4.0 they removed yield tests 这似乎不再起作用。您知道任何替代方案吗?
  • @campellcl 如我所见,您误解了产量测试和产量固定装置之间的区别。我刚刚用 pytest==4.0.0 测试了我的代码,它就像一个魅力)。所以你应该在测试中使用断言而不是 yeild-tests。
  • 当我们并行运行测试时,我们是否可以选择使其工作。我看到所有测试都在运行相同的代码
  • @Gauravkhurana 您可以尝试在设置中创建一些锁定机制(例如文件),在拆卸时删除并跳过初始化(如果它已经存在)。