[Zope-Coders] Help with Unit Testing: safe imports

Tres Seaver tseaver@zope.com
19 Aug 2002 09:02:59 -0400


On Mon, 2002-08-19 at 06:57, Chris Withers wrote:
> Shane Hathaway wrote:
> > 
> > Put the imports in the test methods or the setUp() method.
> 
> They don't work if you put them in the setUp() method.
> so, lots of duplicates in the test methods it is then :-(

Imports within the 'setUp' are dangerous if that method is doing
anything which might "leak" if 'tearDown' isn't called (e.g., opening
database connections).  The idiom I use for this is to add helper method
(.e.g., '_makeOne'), which imports the module-under-test and
instantiates on object.  In this mode, import failures generate test
failures, but 'setUp' / 'tearDown' will always be called and completed. 
E.g.:

  class FooTests( unittest.TestCase ):

      def _makeOne( self, *args, **kw ):

          from Products.FooProduct.Foo import Foo
          return Foo( *args, **kw )

      def testSomething( self ):

          foo = self._makeOne()

          #....

Tres.
-- 
===============================================================
Tres Seaver                                tseaver@zope.com
Zope Corporation      "Zope Dealers"       http://www.zope.com