How can I test 'warnings' from testsuite?

attn.steven.kuo at attn.steven.kuo at
Mon Sep 10 17:15:19 CEST 2007

On Sep 10, 7:08 am, billiejoex <gne... at> wrote:
> Hi there,
> into a module of mine I 'warn' a message if a certain situation
> occurs:
> def add_anonymous_user(permissions=('r'):
>       if 'w' in p:
>           import warnings
>           warnings.warn("it's not rencommended assigning 'w'
> permission to anonymous user.", RuntimeWarning, stacklevel=2)
> I'd like to test such event from test suite ("fail test if warn is not
> raised") but don't know how.
> Any suggestion?

You can (temporarily) change warnings to exceptions
for the purposes of testing; see filterwarnings in
the warnings module.  E.g.,

import warnings
import unittest

def foo():
    warnings.warn("Foo", RuntimeWarning, stacklevel=2)

class testWarn(unittest.TestCase):
    def setUp(self):
    def test_1(self):
        self.assertRaises(RuntimeWarning, foo)
    def tearDown(self):

s = unittest.TestSuite()

if __name__ == '__main__':
    import sys

Hope this helps,

More information about the Python-list mailing list