Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

unit testing - Python logging to StringIO handler

I have a python test in which I want to test if the logging works properly. For example I have a function that creates a user and at the end the logging writes to log file the response.

logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
handler = logging.handlers.WatchedFileHandler('mylogfile.log')
formatter = logging.Formatter('%(asctime)s: %(message)s',
                              '%d/%b/%Y:%H:%M:%S %z')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info('Some log text')

In my test case I want to send the log output to the StringIO.

class MyTest(unittest.TestCase):
    def setUp(self):
        stream = StringIO()
        self.handler = logging.StreamHandler(stream)
        log = logging.getLogger('mylogger')
        log.removeHandler(log.handlers[0])
        log.addHandler(self.handler)

    def tearDown(self):
        log = logging.getLogger('mylogger')
        log.removeHandler(self.handler)
        self.handler.close()

The problem is that I'm not sure how should I test wheter or not my logger is working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an example that works, make sure you set the level of your log, and flush the buffer.

class MyTest(unittest.TestCase):
    def setUp(self):
        self.stream = StringIO()
        self.handler = logging.StreamHandler(self.stream)
        self.log = logging.getLogger('mylogger')
        self.log.setLevel(logging.INFO)
        for handler in self.log.handlers: 
            self.log.removeHandler(handler)
        self.log.addHandler(self.handler)
    def testLog(self):
        self.log.info("test")
        self.handler.flush()
        print '[', self.stream.getvalue(), ']'
        self.assertEqual(self.stream.getvalue(), 'test')

    def tearDown(self):
        self.log.removeHandler(self.handler)
        self.handler.close()

if __name__=='__main__':
    unittest.main()

Further reading, here is an example Temporily Capturing Python Logging to a string buffer that show how you could also do formatting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...