[Python-Dev] test.support.check_warnings

Brett Cannon brett at python.org
Sun Jan 12 02:37:50 CET 2014


On Sat, Jan 11, 2014 at 3:45 PM, Ethan Furman <ethan at stoneleaf.us> wrote:

> The docs say this [1]:
> ==========================================================
>  test.support.check_warnings(*filters, quiet=True)
>
>     A convenience wrapper for warnings.catch_warnings() that makes it
> easier to test that a warning was correctly raised. It is approximately
> equivalent to calling warnings.catch_warnings(record=True) with
> warnings.simplefilter() set to always and with the option to automatically
> validate the results that are recorded.
>
>     check_warnings accepts 2-tuples of the form ("message regexp",
> WarningCategory) as positional arguments. If one or more filters are
> provided, or if the optional keyword argument quiet is False, it checks to
> make sure the warnings are as expected: each specified filter must match at
> least one of the warnings raised by the enclosed code or the test fails,
> and if any warnings are raised that do not match any of the specified
> filters the test fails. To disable the first of these checks, set quiet to
> True.
> ==========================================================
>
> What I want is to make sure that DeprecationWarnings are being raised:
> ==========================================================
>         with support.check_warnings(
>                 ("automatic int conversions have been deprecated",
> DeprecationWarning),
>                 quiet=False,
>                 ):
>             exec("'%x' % pi")
>             exec("'%x' % 3.14")
>             exec("'%X' % 2.11")
>             exec("'%o' % 1.79")
>             exec("'%c' % pi")
> ==========================================================
>
> But if I throw in something that doesn't raise a deprecation warning, the
> test still passes:
> ==========================================================
>             exec("'%d' % 3")
> ==========================================================
>
> Am I doing something wrong?
>

You're assuming the context manager is doing something magical to verify
that all calls in the block raise the expected exception. What you want to
do is execute it in a loop::

  for test in (...):
    with support.check_warnings(("automatic int conversions have been
deprecated", DeprecationWarning), quiet=False):
      exec(test)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140111/12fb5aa1/attachment.html>


More information about the Python-Dev mailing list