我有一些测试需要统计函数产生的警告数量。在Python 2.6中,这很简单,可以使用
with warnings.catch_warnings(record=True) as warn:
...
self.assertEquals(len(warn), 2)
很不幸,在Python 2.4中,with
不能使用,那我该使用什么呢?我不能简单地检查是否有单个警告(使用action='error'
的警告过滤器和try
/catch
),因为警告的数量很大。
我有一些测试需要统计函数产生的警告数量。在Python 2.6中,这很简单,可以使用
with warnings.catch_warnings(record=True) as warn:
...
self.assertEquals(len(warn), 2)
很不幸,在Python 2.4中,with
不能使用,那我该使用什么呢?我不能简单地检查是否有单个警告(使用action='error'
的警告过滤器和try
/catch
),因为警告的数量很大。
我打算建议与Ignacio一样的解决方法,下面是一个更完整的测试代码示例:
import warnings
def setup_warning_catcher():
""" Wrap warnings.showwarning with code that records warnings. """
caught_warnings = []
original_showwarning = warnings.showwarning
def custom_showwarning(*args, **kwargs):
caught_warnings.append(args[0])
return original_showwarning(*args, **kwargs)
warnings.showwarning = custom_showwarning
return caught_warnings
caught_warnings_list = setup_warning_catcher()
# trigger warning here
assert len(caught_warnings_list) == 1
warnings.catch_warnings()
的行为。保存当前值 warnings.showwarning
并用一个函数替换它,该函数将警告保存在列表中,在例程测试后检查列表的长度,然后恢复 warnings.showwarning
。oldsw = warnings.showwarning
warnings.showwarning = myshowwarning
...
self.assertEquals(len(somewarninglist), 2)
warnings.showwarning = oldsw