【问题标题】:difference between fixture and yield_fixture in pytestpytest中fixture和yield_fixture的区别
【发布时间】:2018-01-25 19:21:59
【问题描述】:

我正在浏览 pytest 固定装置,以下看起来非常相似,最新的作品非常相似。

是的,yield_fixure 的可读性更好,但是谁能告诉我到底有什么区别。

在下面提到的情况下,我应该使用哪个?

@pytest.fixture()
def open_browser(request):
    print("Browser opened")

    def close_browser():
        print("browser closed")

    request.addfinalizer(close_browser)

    return "browser object"

@pytest.yield_fixture()
def open_browser():
    print("Browser opened")
    yield "browser object"
    print("browser closed")


def test_google_search(open_browser):
    print(open_browser)
    print("test_google_search")

【问题讨论】:

  • yield 夹具使在夹具中使用上下文管理器变得自然
  • 从 pytest 3.0.0 (2016-08-18) 开始,带有 yield 语句的 @pytest.fixture 是编写拆卸代码的首选方式,@pytest.yield_fixture 已弃用(但尚未删除)。阅读更多here

标签: python python-2.7 pytest fixtures


【解决方案1】:

唯一的区别在于可读性。我认为(尽管我不是 100% 确定)基本行为是相同的(即 yield 语句之后的清理作为终结器运行)。我总是更喜欢使用 yield 固定装置进行清理,因为它更具可读性。

如果您使用的是 pytest pytest.yield_fixture 来获得该行为。但是,如果您能够使用 pytest 3.0+,则不推荐使用 pytest.yield_fixture,您可以使用 pytest.fixture 来获得相同的 yield_fixture 行为。

这里是the explanatory docs

从 pytest-3.0 开始,使用普通夹具装饰器的夹具可以使用 用于提供夹具值并执行拆卸代码的 yield 语句, 与之前版本中的 yield_fixture 完全一样。

仍支持将函数标记为 yield_fixture,但已弃用 并且不应在新代码中使用。

【讨论】:

【解决方案2】:

addfinalizer 在产量上有两个主要区别:

  1. 可以注册多个终结器函数。
  2. 无论夹具设置如何,都将始终调用终结器 代码引发异常。这很方便正确关闭所有 由夹具创建的资源,即使其中一个资源失败 创建/获得

来自the pytest docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-26
    • 2022-11-28
    • 2023-01-27
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 2022-11-30
    相关资源
    最近更新 更多