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)
class WarningTestMixin(object):
'A test which checks if the specified warning was raised'
def assertWarns(self, warning, callable, *args, **kwds):
with warnings.catch_warnings(record=True) as warning_list:
warnings.simplefilter('always')
result = callable(*args, **kwds)
self.assertTrue(any(item.category == warning for item in warning_list))
您可以使用
catch_warnings
上下文管理器。实际上,这允许您模拟警告处理程序,以便可以验证警告的详细信息。请参阅official docs以获得更完整的解释和示例测试代码。从Python 3.2开始,您可以简单地使用^{} 方法。
您可以编写自己的assertWarns函数来增加catch_warnings上下文。我刚刚用一个mixin实现了它:
用法示例:
如果
your_function
发出的警告中至少有一个是UserWarning类型,则测试将通过。相关问题 更多 >
编程相关推荐