Count warnings in Python 2.4

I have several tests in which I need to count the number of warnings caused by a function. In Python 2.6, it's simple using

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

Unfortunately withnot available in Python 2.4, so what else could I use? I can't just check if there was one warning (using warning filter with action='error'and try/ catch), since the number of warnings is significant.

+5
source share
2 answers

I was going to offer the same workaround as Ignacio, a slightly more complete test code example:

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
+6
source

, warnings.catch_warnings() . warnings.showwarning , , , warnings.showwarning.

oldsw = warnings.showwarning
warnings.showwarning = myshowwarning
  ...
self.assertEquals(len(somewarninglist), 2)
warnings.showwarning = oldsw
+3

All Articles