python - pytest中fixture和yield_fixture的区别

标签 python python-2.7 pytest fixtures

我正在检查 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/

相关文章:

python - Django 分页 - 如何重定向回 ListView 和页码

Python For 循环列表有趣的结果

python - 在 ListView 上测试 get_context_data() 会抛出 'AttributeError: object has no attribute ' object_list'

python - Pycharm 中带有 pytest 运行/调试日志的 ##teamcity[... 消息来自哪里?

python - pytest 只运行更改的文件?

带有UTF-8的Python unicode字符串?

python - 使用递归交换字符串中的两个字母

Python:将字符串分成子字符串

Python 3 : checking version before syntactic analysis

python - codeigniter 作为 web 和 python 作为 web 服务