5

I've got some tests that need to count the number of warnings raised by a function. In Python 2.6 this is simple, using

with warnings.catch_warnings(record=True) as warn:
    ...
    self.assertEquals(len(warn), 2)

Unfortunately, with is not available in Python 2.4, so what else could I use? I can't simply check if there's been a single warning (using warning filter with action='error' and try/catch), because the number of warnings is significant.

4

2 回答 2

6

我将建议与 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
于 2010-03-25T10:15:42.043 回答
3

你能做的就是复制warnings.catch_warnings()自己的行为。保存当前值warnings.showwarning并将其替换为将警告保存在列表中的函数,然后在例行程序后测试列表的长度,然后恢复warnings.showwarning

oldsw = warnings.showwarning
warnings.showwarning = myshowwarning
  ...
self.assertEquals(len(somewarninglist), 2)
warnings.showwarning = oldsw
于 2010-03-25T09:59:00.380 回答