我正在检查 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.
关于python - pytest中fixture和yield_fixture的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45734061/