Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing logger Messages with unittest

I'd like to test logger messages without printing them to the screen in my unittests. Given this code:

 import logging
 logging.basicConfig(level=logging.ERROR)
 logger = logging.getLogger('test')
 logger.warning('this is a warning')

 # How do I see that there was a warning?

How do I look at the log records in the logger to see that there was a warning? I cannot find an iterator in Logger that would do the job.

like image 526
Ray Salemi Avatar asked Mar 06 '23 03:03

Ray Salemi


1 Answers

You may need to use TestCase.assertLogs() context manager in such case. The documentation provides a pretty good example of what can be done with it:

with self.assertLogs('foo', level='INFO') as cm:
   logging.getLogger('foo').info('first message')
   logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])

Inside the context manager, you can access cm.records for a list of LogRecord instances, or cm.output for a list of formatted messages

like image 136
Antwane Avatar answered Mar 14 '23 11:03

Antwane