Problem with Unittest:

george young gry at ll.mit.edu
Tue May 13 12:35:35 EDT 2003


On Tue, 13 May 2003 11:20:26 -0400
"Francis Avila" <francisgavila at yahoo.com> threw this fish to the penguins:

> "Frithiof Andreas Jensen" <frithiof.jensen at removethis.ted.ericsson.dk> wrote
> in message news:b9r15s$1v$1 at newstree.wise.edt.ericsson.se...
...
> > 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?
...
> > def duffer():
> >     raise ValueError()
> >
> >
> > class dufferTest(unittest.TestCase):
> >     def test_duffer(self):
> >         self.assertRaises(ValueError(), duffer())
...

> 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.

Umm, since when is raising a instance deprecated?  See:
   http://www.python.org/dev/doc/devel/ref/raise.html#raise

In any case it shouldn't matter, e.g.:
%  python
Python 2.2 (#1, Mar 12 2002, 10:45:35) 
[GCC 3.0.4] on linux2
>>> class c: pass
...
>>> try:
...     raise c
... except c,x:
...     print 'x=',x
... 
x= <__main__.c instance at 0x8171ca4>
>>> try:
...     raise c()
... except c,x:
...     print 'x=',x
... 
x= <__main__.c instance at 0x8173a74>

In both cases the except clause gets an instance.  It's just a different
way of initiating the exception.

-- 
 I cannot think why the whole bed of the ocean is
 not one solid mass of oysters, so prolific they seem. Ah,
 I am wandering! Strange how the brain controls the brain!
	-- Sherlock Holmes in "The Dying Detective"




More information about the Python-list mailing list