对 Python 来说是新手,但我正在尝试理解这段代码:
with pytest.raises(ValueError):
group_adjust(vals, [grps_1, grps_2], weights)
阅读后this tutorial on with ,我了解 pytest.raises() 返回一个上下文管理器,用于在调用 group_adjust()
之前和之后设置和清理内容。我还了解到,如果出现问题,group_adjust()
应该引发 ValueError
。
当发生 ValueError 时,pytest 如何“ react ”? AFAIK,只有设置和清理,所以我不确定它如何捕获异常。最终目标是了解使用 pytest 作为上下文管理器的好处。
最佳答案
__exit__
magic 函数接受 exception_type
、exception_value
和 traceback
参数:
In [5]: class RaisesContext:
...: def __enter__(self):
...: return self
...: def __exit__(self, exception_type, exception_value, traceback):
...: print('Exception type:', exception_type)
...: print('Exception value:', exception_value)
...: print('Traceback:', traceback)
...: return True
...:
In [6]: with RaisesContext():
...: raise ValueError('Something went wrong')
...:
Exception type: <class 'ValueError'>
Exception value: Something went wrong
Traceback: <traceback object at 0x7fd92f4a2c48>
如果 with
block 正常结束,则它们是 None
:
In [7]: with RaisesContext():
...: pass
...:
Exception type: None
Exception value: None
Traceback: None
关于python - pytest.raises(Error) 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34979138/