diff options
author | Antoine Pitrou <solipsis@pitrou.net> | 2013-09-14 17:45:47 (GMT) |
---|---|---|
committer | Antoine Pitrou <solipsis@pitrou.net> | 2013-09-14 17:45:47 (GMT) |
commit | 0715b9fad375751d93de90f23bab20faba1b1b62 (patch) | |
tree | ca77149d5d6549d441ecdcabd3b69c52ced7b4b1 /Doc/library/unittest.rst | |
parent | 692ee9eaf0ae910a0a024f0122c4e51df6c04711 (diff) | |
download | cpython-0715b9fad375751d93de90f23bab20faba1b1b62.zip cpython-0715b9fad375751d93de90f23bab20faba1b1b62.tar.gz cpython-0715b9fad375751d93de90f23bab20faba1b1b62.tar.bz2 |
Issue #18937: Add an assertLogs() context manager to unittest.TestCase to ensure that a block of code emits a message using the logging module.
Diffstat (limited to 'Doc/library/unittest.rst')
-rw-r--r-- | Doc/library/unittest.rst | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst index 7a72e0b..380f058 100644 --- a/Doc/library/unittest.rst +++ b/Doc/library/unittest.rst @@ -1031,6 +1031,47 @@ Test cases .. versionchanged:: 3.3 Added the *msg* keyword argument when used as a context manager. + .. method:: assertLogs(logger=None, level=None) + + A context manager to test that at least one message is logged on + the *logger* or one of its children, with at least the given + *level*. + + If given, *logger* should be a :class:`logging.Logger` object or a + :class:`str` giving the name of a logger. The default is the root + logger, which will catch all messages. + + If given, *level* should be either a numeric logging level or + its string equivalent (for example either ``"ERROR"`` or + :attr:`logging.ERROR`). The default is :attr:`logging.INFO`. + + The test passes if at least one message emitted inside the ``with`` + block matches the *logger* and *level* conditions, otherwise it fails. + + The object returned by the context manager is a recording helper + which keeps tracks of the matching log messages. It has two + attributes: + + .. attribute:: records + + A list of :class:`logging.LogRecord` objects of the matching + log messages. + + .. attribute:: output + + A list of :class:`str` objects with the formatted output of + matching messages. + + Example:: + + 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']) + + .. versionadded:: 3.4 + There are also other methods used to perform more specific checks, such as: |