Count warnings in Python 2.4
Asked Answered
S

2

6

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.

Stylographic answered 24/2, 2010 at 9:17 Comment(0)
A
6

I was going to suggest the same workaround as Ignacio, a bit more complete example of testing code:

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
Agoraphobia answered 25/3, 2010 at 10:15 Comment(0)
B
3

What you can do is duplicate the behavior of warnings.catch_warnings() yourself. Save the current value of warnings.showwarning and replace it with a function that saves the warning in a list, then after the routine test the length of the list and then restore warnings.showwarning.

oldsw = warnings.showwarning
warnings.showwarning = myshowwarning
  ...
self.assertEquals(len(somewarninglist), 2)
warnings.showwarning = oldsw
Burra answered 25/3, 2010 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.