我在Python中有一个以下函数,我想用unittest进行测试,如果该函数将0作为参数,它将引发警告。我已经尝试过assertRaises,但是由于我没有提出警告,所以这行不通。
def isZero(i):
if i != 0:
print "OK"
else:
warning = Warning("the input is 0!")
print warning
return i
您可以使用catch_warnings
上下文管理器。本质上,这使您可以模拟警告处理程序,以便可以验证警告的详细信息。有关更完整的说明和示例测试代码,请参见官方文档。
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Trigger a warning.
fxn()
# Verify some things
assert len(w) == 1
assert issubclass(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句