How can I test 'warnings' from testsuite?

B

billiejoex

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?
 
A

attn.steven.kuo

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):
warnings.filterwarnings("error")
def test_1(self):
self.assertRaises(RuntimeWarning, foo)
def tearDown(self):
warnings.resetwarnings()

s = unittest.TestSuite()
s.addTest(unittest.makeSuite(testWarn))

if __name__ == '__main__':
import sys
sys.argv.append('-v')
unittest.TextTestRunner(verbosity=2).run(s)
 
B

billiejoex

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):
warnings.filterwarnings("error")
def test_1(self):
self.assertRaises(RuntimeWarning, foo)
def tearDown(self):
warnings.resetwarnings()

s = unittest.TestSuite()
s.addTest(unittest.makeSuite(testWarn))

if __name__ == '__main__':
import sys
sys.argv.append('-v')
unittest.TextTestRunner(verbosity=2).run(s)

This is exactly what I was searching for.
Thank you very much.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top