pytest中fixture和yield_fixture的区别

difference between fixture and yield_fixture in pytest

我正在查看 pytest fixtures,下面看起来很相似,最新作品也很相似。

是的,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")

唯一的区别在于可读性。我认为(虽然我不是 100% 确定)底层行为是相同的(即 yield 语句后的清理是 运行 作为终结器)。我总是更喜欢使用 yield fixtures 进行清理,因为它更具可读性。

如果您使用的是 pytest <3.0,您仍然需要使用 pytest.yield_fixture 才能获得该行为。但是,如果您能够使用 pytest 3.0+,pytest.yield_fixture 已弃用,您可以使用 pytest.fixture 获得相同的 yield_fixture 行为。

这里是the explanatory docs

Since pytest-3.0, fixtures using the normal fixture decorator can use a yield statement to provide fixture values and execute teardown code, exactly like yield_fixture in previous versions.

Marking functions as yield_fixture is still supported, but deprecated and should not be used in new code.

addfinalizer 与产量有两个主要区别:

  1. 可以注册多个终结器函数。
  2. 无论夹具设置如何,终结器都会被调用 代码引发异常。这很方便正确关闭所有 由固定装置创建的资源,即使其中之一未能被创建 created/acquired

来自the pytest docs