Python Pytest引发不捕获stopiteration错误

Python Pytest引发不捕获stopiteration错误,python,exception,pytest,Python,Exception,Pytest,Pytest不会捕获带有Pytest.raises的StopIteration错误 例如,这失败了: def test_stop_iteration(): def iterthis(): 对于范围(5)中的i: 产量一 提升停止迭代(“完成”) model=iterthis() 下一个(模型) 下一个(模型) 下一个(模型) 下一个(模型) 下一个(模型) 使用pytest.raises(StopIteration): 下一个(模型) 但这是过去的: def test_stop_迭代():

Pytest不会捕获带有
Pytest.raises的StopIteration错误

例如,这失败了:

def test_stop_iteration():
def iterthis():
对于范围(5)中的i:
产量一
提升停止迭代(“完成”)
model=iterthis()
下一个(模型)
下一个(模型)
下一个(模型)
下一个(模型)
下一个(模型)
使用pytest.raises(StopIteration):
下一个(模型)
但这是过去的:


def test_stop_迭代():
def iterthis():
对于范围(5)中的i:
产量一
提升停止迭代(“完成”)
model=iterthis()
下一个(模型)
下一个(模型)
下一个(模型)
下一个(模型)
下一个(模型)
使用pytest.raises(异常):
下一个(模型)
我在这里遗漏了什么吗?

这将在以下内容中介绍:

如果生成器代码直接或间接引发StopIteration,它将转换为运行时错误(保留StopIteration作为新异常的原因)

因此,如果您真的需要以这种方式捕获它,则必须捕获
RuntimeError

使用pytest.raises(RuntimeError)作为e:
下一个(模型)
在str(e.value)中断言“StopIteration”
异常还包含消息“generator引发的StopIteration”作为原因,因此您可以对此进行检查。 请注意,此行为特定于生成器。如果您只是在生成器外部引发一个
StopIteration
,它的行为将与任何其他异常类似:

def test_stop_iteration():
    def raise_stopiter():
        raise StopIteration("FINISHED")

    with pytest.raises(StopIteration):
        raise_stopiter()
这包括在以下内容中:

如果生成器代码直接或间接引发StopIteration,它将转换为运行时错误(保留StopIteration作为新异常的原因)

因此,如果您真的需要以这种方式捕获它,则必须捕获
RuntimeError

使用pytest.raises(RuntimeError)作为e:
下一个(模型)
在str(e.value)中断言“StopIteration”
异常还包含消息“generator引发的StopIteration”作为原因,因此您可以对此进行检查。 请注意,此行为特定于生成器。如果您只是在生成器外部引发一个
StopIteration
,它的行为将与任何其他异常类似:

def test_stop_iteration():
    def raise_stopiter():
        raise StopIteration("FINISHED")

    with pytest.raises(StopIteration):
        raise_stopiter()

谢谢我查Pytest文档是有原因的。谢谢!我查Pytest文档是有原因的。