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

后端 未结 7 2087
青春惊慌失措
青春惊慌失措 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:54

    The issue is that the unittest runner replaces sys.stdout/sys.stderr before the testing starts, and the StreamHandler is still writing to the original sys.stdout.

    If you assign the 'current' sys.stdout to the handler, it should work (see the code below).

    import sys
    import unittest
    import logging
    
    logger = logging.getLogger()
    logger.level = logging.DEBUG
    stream_handler = logging.StreamHandler(sys.stdout)
    logger.addHandler(stream_handler)
    
    class TestCase(unittest.TestCase):
        def testSimpleMsg(self):
            stream_handler.stream = sys.stdout
            print("AA")
            logging.getLogger().info("BB")
    

    Although, a better approach would be adding/removing the handler during the test:

    import sys
    import unittest
    import logging
    
    logger = logging.getLogger()
    logger.level = logging.DEBUG
    
    class TestCase(unittest.TestCase):
        def testSimpleMsg(self):
            stream_handler = logging.StreamHandler(sys.stdout)
            logger.addHandler(stream_handler)
            try:
                print("AA")
                logging.getLogger().info("BB")
            finally:
                logger.removeHandler(stream_handler)
    
    0 讨论(0)
提交回复
热议问题