[英]Pytest doesn't throw exceptions into fixture generators
在pytest中,可以通过将finalizers添加到fixture中,方法是将它们变成生成器,并在第一个(也是唯一一个) yield
之后提供finalization代码。
令我惊讶的是,异常没有被抛回到生成器中。 我想这是有道理的,否则用户将不得不总是用try ... except或类似方法包装yield
。
我希望的是这样的工作:
import pytest
@pytest.fixture
def some_val():
return 42
@pytest.fixture
def a_val(some_val):
try:
yield some_val
except Exception as e:
print(f"An exception occurred: {e}")
def test_a_val(a_val):
raise ValueError("Something bad happened..")
为此,我想添加一个例程以提供有关特定错误类型的其他调试信息,而我真的不想将这些代码本身放入测试中。
理想情况下,我将使用上下文管理器包装收益以捕获异常,但是显然在这里存在相同的问题。
有一种我不知道的替代pytest方法可以使这项工作吗?
对于其他想要这种行为的人,可以使用pytest的一个钩子来模拟它,在这种情况下, pytest_pyfunc_call
会很好地工作。
conftest.py
:
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_pyfunc_call(pyfuncitem):
print("Hook executing...")
funcargs = pyfuncitem.funcargs
testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
print(f"funcargs: {funcargs}")
print(f"testargs: {testargs}")
try:
outcome = yield
outcome.get_result()
except Exception as e:
print(f"Got exception: {e}")
raise
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.