Unit test entry for formatted Python log output

How could you write unittest in Python that will verify that the output from the logger is really in the format you expect (i.e., via the logging.basicConfig () call)? I think the lines of the custom StreamHandler and use the 're' library, but it doesn’t look like the LogRecord passed to StreamHandler.emit () can give me a string to be output.

+5
source share
1 answer

From the documentation ( http://packages.python.org/testfixtures/logging.html ):

To help with this, TestFixtures makes it easy to capture the output of calls to the Pythons logging system and keep them as expected. There are three different methods, depending on the type of test you are writing.

Examples are included in the documentation. Abridged version below.

Context manager

>>> import logging
>>> from testfixtures import LogCapture
>>> with LogCapture() as l:
...     logger = logging.getLogger()
...     logger.info('a message')
...     logger.error('an error')

And after that you can check the logs for equality:

>>> l.check(
...     ('root', 'INFO', 'a message'),
...     ('root', 'ERROR', 'another error'),
...     )
Traceback (most recent call last):
 ...
AssertionError: Sequence not as expected:

same:
(('root', 'INFO', 'a message'),)

first:
(('root', 'ERROR', 'another error'),)

second:
(('root', 'ERROR', 'an error'),)

Decorator

Like the previous one, but applied to a specific function:

from testfixtures import log_capture

@log_capture()
def test_function(l):
    logger = logging.getLogger()
    logger.info('a message')
    logger.error('an error')

    l.check(
        ('root', 'INFO', 'a message'),
        ('root', 'ERROR', 'an error'),
        )

Manual use

>>> from testfixtures import LogCapture
>>> l = LogCapture()

After that, you can also “check” the logs:

>>> l.check(('root', 'INFO', 'a message'))
<...>

. -, l.records ( l LogCapture) (, msg , , levelname , ).

+5

All Articles