Problem with Unittest:
Fredrik Lundh
fredrik at pythonware.com
Tue May 13 12:07:11 EDT 2003
Francis Avila wrote:
> When you raise an exception, you raise the exception CLASS, not an instance
> of the exception:
"raise" takes either an instance or a class; in the latter case, it creates
the instance for you. in modern Python, the actual exception (exc_value)
is *always* an instance of a class:
http://www.python.org/doc/current/ref/raise.html
> 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.
the exception machinery uses "isinstance", not "is". for details, see:
http://www.python.org/doc/current/ref/try.html
> (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....)
to save even more time, run modified code at least once before you
ship the product ;-)
</F>
More information about the Python-list
mailing list