密切相关: 在Python中,有没有一个在安装/拆卸中使用上下文管理器的好习惯用法 https://stackoverflow.com/questions/8416208/in-python-is-there-a-good-idiom-for-using-context-managers-in-setup-teardown
我有一个上下文管理器,用于在测试中修复时间/时区。我想把它放在 pytest funcarg (或固定装置中,我们正在使用pytest
2.2.3 但我可以向后翻译)。我可以这样做:
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)
……不过有点恶心。在相关的Qjsbueno https://stackoverflow.com/users/108205/jsbueno指出:问题是您的代码没有提供调用对象的__exit__
如果发生异常,请正确处理。
他的回答 https://stackoverflow.com/a/8529165/54056使用元类方法。但这对于 pytest 来说并不是那么有用,因为通常测试只是函数,而不是类。那么 pytest-y 解决这个问题的方法是什么?涉及某事运行测试挂钩 http://pytest.org/latest/plugins.html#generic-runtest-hooks?
从2.4开始,py.test
has yield
风格夹具支持。我们可以使用一个with
直接在它里面的上下文。
@pytest.yield_fixture
def passwd():
with open("/etc/passwd") as f:
yield f.readlines()
从3.0开始,py.test
已弃用@pytest.yield_fixture
用法。我们可以使用@pytest.fixture
直接作为上下文管理器。
@pytest.fixture
def passwd():
with open("/etc/passwd") as f:
yield f.readlines()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)