Problem with Unittest:

Francis Avila francisgavila at yahoo.com
Tue May 13 11:20:26 EDT 2003


"Frithiof Andreas Jensen" <frithiof.jensen at removethis.ted.ericsson.dk> wrote
in message news:b9r15s$1v$1 at newstree.wise.edt.ericsson.se...
> Hi,
>
> I am trying to test some software using unittest with Python 2.2.2 (#37,
Oct
> 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 and I am having some
> problems with exceptions:
[...]
> In my opinion, the script should PASS because I specified that a
> ValueError() was the PASS criteria.
>
> What am I doing wrong?
>
>
> Test Script source:
> """
> Try some unittest functions
> """
> import unittest
>
> def duffer():
>     raise ValueError()
>
>
> class dufferTest(unittest.TestCase):
>     def test_duffer(self):
>         self.assertRaises(ValueError(), duffer())
>
> def suite():
>     duffer_suite = unittest.makeSuite(dufferTest,'test')
>
>     return unittest.TestSuite((duffer_suite,))
>
> if __name__ == '__main__':
>     runner = unittest.TextTestRunner()
>     runner.run(suite())
>
> # done.


When you raise an exception, you raise the exception CLASS, not an instance
of the exception:

    def duffer():
-       raise ValueError()
+       raise ValueError


    class dufferTest(unittest.TestCase):
        def test_duffer(self):
-           self.assertRaises(ValueError(), duffer())
+           self.assertRaises(ValueError, duffer())


My guess is that somewhere in the bowels of assertRaises there's a test like
this:

if (<ExceptionClass in 1st argument> is <ExceptionClass received by
executing the 2nd argument>):

This test will fail, because in your case it's comparing two different
instances: (ValueError() is ValueError()) will *always* be false, whereas
(ValueError is ValueError) will *always* be true, because its the same
class, and the same entity in memory.


If you've gotten into the habit of raising exception instances rather than
classes, break it right now, or you'll be plagued with problems like this.


(Just a little time-saving tip: instead of setting up a suite, for simple
unittest files you can do unittest.main(), which will run every test in the
file whose name conforms to some lexical rules I do not now remember....)
--
Francis Avila





More information about the Python-list mailing list