PyDev unittesting: How to capture text logged to a logging.Logger in “Captured Output”

后端 未结 7 2161
青春惊慌失措
青春惊慌失措 2020-12-07 20:08

I am using PyDev for development and unit-testing of my Python application. As for unit-testing, everything works great except the fact that no content is logged to the logg

7条回答
  •  长情又很酷
    2020-12-07 20:43

    I grew tired of having to manually add Fabio's great code to all setUps, so I subclassed unittest.TestCase with some __metaclass__ing:

    class LoggedTestCase(unittest.TestCase):
        __metaclass__ = LogThisTestCase
        logger = logging.getLogger("unittestLogger")
        logger.setLevel(logging.DEBUG) # or whatever you prefer
    
    class LogThisTestCase(type):
        def __new__(cls, name, bases, dct):
            # if the TestCase already provides setUp, wrap it
            if 'setUp' in dct:
                setUp = dct['setUp']
            else:
                setUp = lambda self: None
                print "creating setUp..."
    
            def wrappedSetUp(self):
                # for hdlr in self.logger.handlers:
                #    self.logger.removeHandler(hdlr)
                self.hdlr = logging.StreamHandler(sys.stdout)
                self.logger.addHandler(self.hdlr)
                setUp(self)
            dct['setUp'] = wrappedSetUp
    
            # same for tearDown
            if 'tearDown' in dct:
                tearDown = dct['tearDown']
            else:
                tearDown = lambda self: None
    
            def wrappedTearDown(self):
                tearDown(self)
                self.logger.removeHandler(self.hdlr)
            dct['tearDown'] = wrappedTearDown
    
            # return the class instance with the replaced setUp/tearDown
            return type.__new__(cls, name, bases, dct)
    

    Now your test case can simply inherit from LoggedTestCase, i.e. class TestCase(LoggedTestCase) instead of class TestCase(unittest.TestCase) and you're done. Alternatively, you can add the __metaclass__ line and define the logger either in the test or a slightly modified LogThisTestCase.

提交回复
热议问题