unittest issues

Alex Martelli aleaxit at yahoo.com
Sun Sep 12 18:44:43 EDT 2004


paul koelle <paul at subsignal.org> wrote:

> Hi,
> 
> I try to use the "failUnlessRaises()" method from unittest.TestCase as
> follows:
> 
>  >>self.failUnlessRaises(IntegrityError, myObject.new(**stuff))
> 
> where IntegrityError is an Exception somewhere deep inside pysqlite. 
> Running it spits out:
> 
>  >>NameError: global name 'IntegrityError' is not defined.
> 
> Do I really need to tell unittest  about each and every possible 
> Exception it might catch. Whats going on here?

You need to define any name you use before you use it, quite apart from
unittest.  You can't use a name that just isn't defined in that scope,
period: whether you're unit testing or doing anything else, you can't.

Once you have fixed this you'll find another problem: you need to pass
failUnlessRaises the callable and arguments separately, so it can
perform the call within a try clause.  What you're doing here is calling
the myObject.new method yourself, so it presumably raises well before
any kind of control is passed to the failUnlessRaises method -- no good.
I'm not sure you can pass an arbitrary set of keywords that way (at the
very least some keyword might happen to conflict with ones used in
unittest itself), so I suggest this approach:

    def localfun(): return myObject.new(**stuff)
    self.failUnlessRaises(Exception, localfun)

note that here I'm passing the function object itself, NOT the result of
calling it -- there IS quite a difference!


Alex



More information about the Python-list mailing list