Skip to content Skip to sidebar Skip to footer

Python Assertraises On User-defined Exceptions

The following question was triggered by the discussion in this post. Assume two files (foobar.py and foobar_unittest.py). File foobar.py contains a class (FooBar) with two function

Solution 1:

import MyException from foobar, don't redefine it.

import unittest
from foobar import MyException
import foobar as fb

classFooBarTestCases(unittest.TestCase):
    deftest_bar(self):
        with self.assertRaises(ValueError):
            fb.FooBar().bar()
    deftest_foo(self):
        with self.assertRaises(MyException):
            fb.FooBar().foo()
if __name__ == '__main__':
    unittest.main()

This code should work now as

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

Solution 2:

Be aware that the same happens (happened to me) if you use reload to import your exceptions.

In my unittests I have the relevant imports like

from importlib import reload
import foobar
reload(foobar)
from foobar importMyException

This does not work, too, for whatever reason. Writing this just as

from foobar importMyException

will work. Then, of course, you have to reload the modules yourself.

In case you wonder why I am using reload: How do I unload (reload) a Python module?.

Post a Comment for "Python Assertraises On User-defined Exceptions"