[Zope-CMF] Catching logging during unittesting?

Chris Withers chris at simplistix.co.uk
Fri Nov 18 09:56:10 EST 2005


Answering my own question and cc'ing Vinay in since I was also talking 
to him about this...

Chris Withers wrote:
> I'm unit testing something which does some logging. It's supposed to 
> log, so ideally I'd like to test for that, but I'd also like to not have 
> the log spew showing during tests runs, which seems to have started 
> happening in Zope 2.8 :-S

I added the following methods to our TestCase base class and then added 
the class below it:

     def _stopLogging(self):
         import logging
         root_logger = logging.getLogger()
         self.old_handlers = root_logger.handlers
         root_logger.handlers = [DummyLogger()]

     def _startLogging(self):
         old_handlers = getattr(self,'old_handlers',None)
         if old_handlers is not None:
             import logging
             logging.getLogger().handlers = old_handlers

class DummyLogger:

     def handle(self, record):
         pass

This can now be used in a unit test as follows:

         self._stopLogging()
         try:
           # stuff that ends up logging stuff
           self.assertRaises(AttributeError,self._runStep,'checkExpires')
         finally:
             checkExpires.DateTime = DateTime
             self._startLogging()

Hope this helps someone else :-)

cheers,

Chris

PS: Vinay: lemme know if there's a better way to do this...

-- 
Simplistix - Content Management, Zope & Python Consulting
            - http://www.simplistix.co.uk


More information about the Zope-CMF mailing list