There's more...

As mentioned previously, if a test raises an exception other than AssertionError, then it is treated as an error. This is very useful for discovering errors that occur while you are editing code for which a matched test already exists.

There are circumstances, however, in which you would want to run a test to verify that certain code actually produces an exception. For example, in cases when an invalid value is passed as an attribute of an object. In such cases, failUnlessRaises() makes the code clearer than capturing the exception in your code:

import unittest

def raises_error(*args, **kwds):
print (args, kwds)
raise ValueError
('Valore non valido:'+ str(args)+ str(kwds))

class ExceptionTest(unittest.TestCase):
def testTrapLocally(self):
try:
raises_error('a', b='c')
except ValueError:
pass
else:
self.fail('Non si vede ValueError')

def testFailUnlessRaises(self):
self.assertRaises
(ValueError, raises_error, 'a', b='c')

if __name__ == '__main__':
unittest.main()

The results for both are the same. However, the result for the second test, which uses failUnlessRaises(), is shorter:

> python unittest_exception.py -v
testFailUnlessRaises (__main__.ExceptionTest) ... ('a',) {'b': 'c'}
ok
testTrapLocally (__main__.ExceptionTest) ...('a',) {'b': 'c'}
ok

-----------------------------------------------------------
Ran 2 tests in 0.000s

OK
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.104.214