[Python-checkins] cpython: Issue #18937: Add an assertLogs() context manager to unittest.TestCase to
Terry Reedy
tjreedy at udel.edu
Sat Sep 14 20:14:10 CEST 2013
On 9/14/2013 1:45 PM, antoine.pitrou wrote:
> http://hg.python.org/cpython/rev/4f5815747f58
> changeset: 85701:4f5815747f58
> user: Antoine Pitrou <solipsis at pitrou.net>
> date: Sat Sep 14 19:45:47 2013 +0200
> summary:
> Issue #18937: Add an assertLogs() context manager to unittest.TestCase to ensure that a block of code emits a message using the logging module.
>
> files:
> Doc/library/unittest.rst | 41 +++++++
> Lib/unittest/case.py | 109 +++++++++++++++++++-
> Lib/unittest/test/test_case.py | 96 ++++++++++++++++++
> Misc/NEWS | 2 +
> 4 files changed, 242 insertions(+), 6 deletions(-)
>
>
> diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
> --- a/Doc/library/unittest.rst
> +++ b/Doc/library/unittest.rst
> @@ -1031,6 +1031,47 @@
> .. versionchanged:: 3.3
> Added the *msg* keyword argument when used as a context manager.
assertWarnsRegex
> + .. 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:
The new method should be added to the table of raises/warns methods that
starts this group. The table intro sentence
"It is also possible to check that exceptions and warnings are raised
using the following methods:"
should be modified to something like
"It is also possible to check the production of exception, warning, and
log messages using the following methods:"
Terry
More information about the Python-checkins
mailing list