py.test - 如何在 funcarg/fixture 中使用上下文管理器 [英] py.test - how to use a context manager in a funcarg/fixture

查看:61
本文介绍了py.test - 如何在 funcarg/fixture 中使用上下文管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

密切相关: 在 python 中,是否有在设置/拆卸中使用上下文管理器的好习惯

我有一个上下文管理器,用于在测试中修复时间/时区.我想把它放在一个 pytest funcarg (或夹具,我们使用 pytest 2.2.3 但我可以向后翻译).我可以这样做:

I have a context manager that is used in tests to fix the time/timezone. I want to have it in a pytest funcarg (or fixture, we are using pytest 2.2.3 but I can translate backwards). I could just do this:

def pytest_funcarg__fixedTimezone(request):
    # fix timezone to match Qld, no DST to worry about and matches all
    # Eastern states in winter.
    fixedTime = offsetTime.DisplacedRealTime(tz=' Australia/Brisbane')

    def setup():
        fixedTime.__enter__()
        return fixedTime

    def teardown(fixedTime):
        # this seems rather odd?
        fixedTime.__exit__(None, None, None)

...不过有点恶心.在相关的 Q jsbueno 中指出:问题是你的代码没有规定调用对象的 __exit__ 方法正确,如果发生异常.

... but it's a bit icky. In the related Q jsbueno points out: The problem is that your code has no provision to call the object's __exit__ method properly if an exception occurs.

他的回答使用了元类方法.但这对于 pytest 来说不是很有用,因为 pytest 通常测试只是函数而不是类.那么解决这个问题的 pytest-y 方法是什么?涉及runtest hooks的事情?

His answer uses a metaclass approach. But this is not that useful for pytest where often tests are just functions, not classes. So what would be the pytest-y way to solve this? Something involving runtest hooks?

推荐答案

从 2.4 开始,py.test 具有 yield 样式的夹具支持.我们可以直接在其中使用 with 上下文.

Since 2.4, py.test has yield style fixture support. We could use a with context inside it directly.

@pytest.yield_fixture
def passwd():
    with open("/etc/passwd") as f:
        yield f.readlines()

从 3.0 开始,py.test 弃用了 @pytest.yield_fixture 的用法.我们可以直接使用 @pytest.fixture 作为上下文管理器.

Since 3.0, py.test deprecated the @pytest.yield_fixture usage. We could use @pytest.fixture as a context manager directly.

@pytest.fixture
def passwd():
    with open("/etc/passwd") as f:
        yield f.readlines()

这篇关于py.test - 如何在 funcarg/fixture 中使用上下文管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆